-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathResumableAsyncHandler.java
324 lines (267 loc) · 11 KB
/
ResumableAsyncHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/*
* Copyright (c) 2010-2012 Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.asynchttpclient.handler.resumable;
import io.netty.handler.codec.http.HttpHeaders;
import org.asynchttpclient.AsyncHandler;
import org.asynchttpclient.HttpResponseBodyPart;
import org.asynchttpclient.HttpResponseStatus;
import org.asynchttpclient.Request;
import org.asynchttpclient.RequestBuilder;
import org.asynchttpclient.Response;
import org.asynchttpclient.Response.ResponseBuilder;
import org.asynchttpclient.handler.TransferCompletionHandler;
import org.jspecify.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaderNames.RANGE;
/**
* An {@link AsyncHandler} which support resumable download, e.g. when used with an {@link ResumableIOExceptionFilter},
* this handler can resume the download operation at the point it was before the interruption occurred. This prevents having to
* download the entire file again. It's the responsibility of the {@link ResumableAsyncHandler}
* to track how many bytes has been transferred and to properly adjust the file's write position.
* <br>
* In case of a JVM crash/shutdown, you can create an instance of this class and pass the last valid bytes position.
* <p>
* Beware that it registers a shutdown hook, that will cause a ClassLoader leak when used in an appserver and only redeploying the application.
*/
public class ResumableAsyncHandler implements AsyncHandler<Response> {
private static final Logger logger = LoggerFactory.getLogger(TransferCompletionHandler.class);
private static final ResumableIndexThread resumeIndexThread = new ResumableIndexThread();
private static Map<String, Long> resumableIndex = Collections.emptyMap();
private final AtomicLong byteTransferred;
private final ResumableProcessor resumableProcessor;
private final @Nullable AsyncHandler<Response> decoratedAsyncHandler;
private final boolean accumulateBody;
private String url = "";
private final ResponseBuilder responseBuilder = new ResponseBuilder();
private ResumableListener resumableListener = new NULLResumableListener();
private ResumableAsyncHandler(long byteTransferred, @Nullable ResumableProcessor resumableProcessor,
@Nullable AsyncHandler<Response> decoratedAsyncHandler, boolean accumulateBody) {
this.byteTransferred = new AtomicLong(byteTransferred);
if (resumableProcessor == null) {
resumableProcessor = new NULLResumableHandler();
}
this.resumableProcessor = resumableProcessor;
resumableIndex = resumableProcessor.load();
resumeIndexThread.addResumableProcessor(resumableProcessor);
this.decoratedAsyncHandler = decoratedAsyncHandler;
this.accumulateBody = accumulateBody;
}
public ResumableAsyncHandler(long byteTransferred) {
this(byteTransferred, null, null, false);
}
public ResumableAsyncHandler(boolean accumulateBody) {
this(0, null, null, accumulateBody);
}
public ResumableAsyncHandler() {
this(0, null, null, false);
}
public ResumableAsyncHandler(AsyncHandler<Response> decoratedAsyncHandler) {
this(0, new PropertiesBasedResumableProcessor(), decoratedAsyncHandler, false);
}
public ResumableAsyncHandler(long byteTransferred, AsyncHandler<Response> decoratedAsyncHandler) {
this(byteTransferred, new PropertiesBasedResumableProcessor(), decoratedAsyncHandler, false);
}
public ResumableAsyncHandler(ResumableProcessor resumableProcessor) {
this(0, resumableProcessor, null, false);
}
public ResumableAsyncHandler(ResumableProcessor resumableProcessor, boolean accumulateBody) {
this(0, resumableProcessor, null, accumulateBody);
}
@Override
public State onStatusReceived(final HttpResponseStatus status) throws Exception {
responseBuilder.accumulate(status);
if (status.getStatusCode() == 200 || status.getStatusCode() == 206) {
url = status.getUri().toUrl();
} else {
return AsyncHandler.State.ABORT;
}
if (decoratedAsyncHandler != null) {
return decoratedAsyncHandler.onStatusReceived(status);
}
return AsyncHandler.State.CONTINUE;
}
@Override
public void onThrowable(Throwable t) {
if (decoratedAsyncHandler != null) {
decoratedAsyncHandler.onThrowable(t);
} else {
logger.debug("", t);
}
}
@Override
public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
if (accumulateBody) {
responseBuilder.accumulate(bodyPart);
}
State state = State.CONTINUE;
try {
resumableListener.onBytesReceived(bodyPart.getBodyByteBuffer());
} catch (IOException ex) {
return AsyncHandler.State.ABORT;
}
if (decoratedAsyncHandler != null) {
state = decoratedAsyncHandler.onBodyPartReceived(bodyPart);
}
byteTransferred.addAndGet(bodyPart.getBodyPartBytes().length);
resumableProcessor.put(url, byteTransferred.get());
return state;
}
@Override
public @Nullable Response onCompleted() throws Exception {
resumableProcessor.remove(url);
resumableListener.onAllBytesReceived();
if (decoratedAsyncHandler != null) {
decoratedAsyncHandler.onCompleted();
}
// Not sure
return responseBuilder.build();
}
@Override
public State onHeadersReceived(HttpHeaders headers) throws Exception {
responseBuilder.accumulate(headers);
String contentLengthHeader = headers.get(CONTENT_LENGTH);
if (contentLengthHeader != null) {
if (Long.parseLong(contentLengthHeader) == -1L) {
return AsyncHandler.State.ABORT;
}
}
if (decoratedAsyncHandler != null) {
return decoratedAsyncHandler.onHeadersReceived(headers);
}
return State.CONTINUE;
}
@Override
public State onTrailingHeadersReceived(HttpHeaders headers) {
responseBuilder.accumulate(headers);
return State.CONTINUE;
}
/**
* Invoke this API if you want to set the Range header on your {@link Request} based on the last valid bytes
* position.
*
* @param request {@link Request}
* @return a {@link Request} with the Range header properly set.
*/
public Request adjustRequestRange(Request request) {
Long ri = resumableIndex.get(request.getUrl());
if (ri != null) {
byteTransferred.set(ri);
}
// The Resumable
if (resumableListener != null && resumableListener.length() > 0 && byteTransferred.get() != resumableListener.length()) {
byteTransferred.set(resumableListener.length());
}
RequestBuilder builder = request.toBuilder();
if (request.getHeaders().get(RANGE) == null && byteTransferred.get() != 0) {
builder.setHeader(RANGE, "bytes=" + byteTransferred.get() + '-');
}
return builder.build();
}
/**
* Set a {@link ResumableListener}
*
* @param resumableListener a {@link ResumableListener}
* @return this
*/
public ResumableAsyncHandler setResumableListener(ResumableListener resumableListener) {
this.resumableListener = resumableListener;
return this;
}
/**
* An interface to implement in order to manage the way the incomplete file management are handled.
*/
public interface ResumableProcessor {
/**
* Associate a key with the number of bytes successfully transferred.
*
* @param key a key. The recommended way is to use an url.
* @param transferredBytes The number of bytes successfully transferred.
*/
void put(String key, long transferredBytes);
/**
* Remove the key associate value.
*
* @param key key from which the value will be discarded
*/
void remove(String key);
/**
* Save the current {@link Map} instance which contains information about the current transfer state.
* This method *only* invoked when the JVM is shutting down.
*
* @param map the current transfer state
*/
void save(Map<String, Long> map);
/**
* Load the {@link Map} in memory, contains information about the transferred bytes.
*
* @return {@link Map} current transfer state
*/
Map<String, Long> load();
}
private static class ResumableIndexThread extends Thread {
public final ConcurrentLinkedQueue<ResumableProcessor> resumableProcessors = new ConcurrentLinkedQueue<>();
private ResumableIndexThread() {
Runtime.getRuntime().addShutdownHook(this);
}
public void addResumableProcessor(ResumableProcessor p) {
resumableProcessors.offer(p);
}
@Override
public void run() {
for (ResumableProcessor p : resumableProcessors) {
p.save(resumableIndex);
}
}
}
private static class NULLResumableHandler implements ResumableProcessor {
@Override
public void put(String url, long transferredBytes) {
}
@Override
public void remove(String uri) {
}
@Override
public void save(Map<String, Long> map) {
}
@Override
public Map<String, Long> load() {
return new HashMap<>();
}
}
private static class NULLResumableListener implements ResumableListener {
private long length;
private NULLResumableListener() {
length = 0L;
}
@Override
public void onBytesReceived(ByteBuffer byteBuffer) {
length += byteBuffer.remaining();
}
@Override
public void onAllBytesReceived() {
}
@Override
public long length() {
return length;
}
}
}