/
NettyResponseFuture.java
executable file
·490 lines (402 loc) · 15 KB
/
NettyResponseFuture.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/*
* Copyright (c) 2014 AsyncHttpClient Project. 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.netty;
import static org.asynchttpclient.util.DateUtils.millisTime;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpHeaders;
import java.net.SocketAddress;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.asynchttpclient.AsyncHandler;
import org.asynchttpclient.Realm;
import org.asynchttpclient.Request;
import org.asynchttpclient.channel.pool.ConnectionPoolPartitioning;
import org.asynchttpclient.future.AbstractListenableFuture;
import org.asynchttpclient.netty.channel.ChannelState;
import org.asynchttpclient.netty.channel.Channels;
import org.asynchttpclient.netty.request.NettyRequest;
import org.asynchttpclient.netty.timeout.TimeoutsHolder;
import org.asynchttpclient.proxy.ProxyServer;
import org.asynchttpclient.uri.Uri;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A {@link Future} that can be used to track when an asynchronous HTTP request has been fully processed.
*
* @param <V> the result type
*/
public final class NettyResponseFuture<V> extends AbstractListenableFuture<V> {
private static final Logger LOGGER = LoggerFactory.getLogger(NettyResponseFuture.class);
private final long start = millisTime();
private final ConnectionPoolPartitioning connectionPoolPartitioning;
private final ProxyServer proxyServer;
private final int maxRetry;
private final CountDownLatch latch = new CountDownLatch(1);
// state mutated from outside the event loop
// TODO check if they are indeed mutated outside the event loop
private final AtomicBoolean isDone = new AtomicBoolean(false);
private final AtomicBoolean isCancelled = new AtomicBoolean(false);
private final AtomicInteger redirectCount = new AtomicInteger();
private final AtomicBoolean inAuth = new AtomicBoolean(false);
private final AtomicBoolean inProxyAuth = new AtomicBoolean(false);
private final AtomicBoolean statusReceived = new AtomicBoolean(false);
private final AtomicLong touch = new AtomicLong(millisTime());
private final AtomicReference<ChannelState> channelState = new AtomicReference<>(ChannelState.NEW);
private final AtomicBoolean contentProcessed = new AtomicBoolean(false);
private final AtomicInteger currentRetry = new AtomicInteger(0);
private final AtomicBoolean onThrowableCalled = new AtomicBoolean(false);
private final AtomicReference<V> content = new AtomicReference<>();
private final AtomicReference<ExecutionException> exEx = new AtomicReference<>();
private volatile TimeoutsHolder timeoutsHolder;
// state mutated only inside the event loop
private Channel channel;
private boolean keepAlive = true;
private Request targetRequest;
private Request currentRequest;
private NettyRequest nettyRequest;
private HttpHeaders httpHeaders;
private AsyncHandler<V> asyncHandler;
private boolean streamWasAlreadyConsumed;
private boolean reuseChannel;
private boolean headersAlreadyWrittenOnContinue;
private boolean dontWriteBodyBecauseExpectContinue;
private boolean allowConnect;
private Realm realm;
private Realm proxyRealm;
public NettyResponseFuture(Request originalRequest,//
AsyncHandler<V> asyncHandler,//
NettyRequest nettyRequest,//
int maxRetry,//
ConnectionPoolPartitioning connectionPoolPartitioning,//
ProxyServer proxyServer) {
this.asyncHandler = asyncHandler;
this.targetRequest = currentRequest = originalRequest;
this.nettyRequest = nettyRequest;
this.connectionPoolPartitioning = connectionPoolPartitioning;
this.proxyServer = proxyServer;
this.maxRetry = maxRetry;
}
// java.util.concurrent.Future
@Override
public boolean isDone() {
return isDone.get() || isCancelled();
}
@Override
public boolean isCancelled() {
return isCancelled.get();
}
@Override
public boolean cancel(boolean force) {
cancelTimeouts();
if (isCancelled.getAndSet(true))
return false;
// cancel could happen before channel was attached
if (channel != null) {
Channels.setDiscard(channel);
Channels.silentlyCloseChannel(channel);
}
if (!onThrowableCalled.getAndSet(true)) {
try {
asyncHandler.onThrowable(new CancellationException());
} catch (Throwable t) {
LOGGER.warn("cancel", t);
}
}
latch.countDown();
runListeners();
return true;
}
@Override
public V get() throws InterruptedException, ExecutionException {
latch.await();
return getContent();
}
@Override
public V get(long l, TimeUnit tu) throws InterruptedException, TimeoutException, ExecutionException {
if (!latch.await(l, tu))
throw new TimeoutException();
return getContent();
}
private V getContent() throws ExecutionException {
if (isCancelled())
throw new CancellationException();
ExecutionException e = exEx.get();
if (e != null)
throw e;
V update = content.get();
// No more retry
currentRetry.set(maxRetry);
if (!contentProcessed.getAndSet(true)) {
try {
update = asyncHandler.onCompleted();
} catch (Throwable ex) {
if (!onThrowableCalled.getAndSet(true)) {
try {
try {
asyncHandler.onThrowable(ex);
} catch (Throwable t) {
LOGGER.debug("asyncHandler.onThrowable", t);
}
throw new RuntimeException(ex);
} finally {
cancelTimeouts();
}
}
}
content.compareAndSet(null, update);
}
return update;
}
// org.asynchttpclient.ListenableFuture
private boolean terminateAndExit() {
cancelTimeouts();
this.channel = null;
this.reuseChannel = false;
return isDone.getAndSet(true) || isCancelled.get();
}
public final void done() {
if (terminateAndExit())
return;
try {
getContent();
} catch (ExecutionException t) {
return;
} catch (RuntimeException t) {
Throwable exception = t.getCause() != null ? t.getCause() : t;
exEx.compareAndSet(null, new ExecutionException(exception));
} finally {
latch.countDown();
}
runListeners();
}
public final void abort(final Throwable t) {
exEx.compareAndSet(null, new ExecutionException(t));
if (terminateAndExit())
return;
if (onThrowableCalled.compareAndSet(false, true)) {
try {
asyncHandler.onThrowable(t);
} catch (Throwable te) {
LOGGER.debug("asyncHandler.onThrowable", te);
}
}
latch.countDown();
runListeners();
}
@Override
public void touch() {
touch.set(millisTime());
}
@Override
public CompletableFuture<V> toCompletableFuture() {
CompletableFuture<V> completable = new CompletableFuture<>();
addListener(new Runnable() {
@Override
public void run() {
ExecutionException e = exEx.get();
if (e != null)
completable.completeExceptionally(e);
else
completable.complete(content.get());
}
}, new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
});
return completable;
}
// INTERNAL
public Uri getUri() {
return targetRequest.getUri();
}
public ConnectionPoolPartitioning getConnectionPoolPartitioning() {
return connectionPoolPartitioning;
}
public ProxyServer getProxyServer() {
return proxyServer;
}
public void setAsyncHandler(AsyncHandler<V> asyncHandler) {
this.asyncHandler = asyncHandler;
}
public void cancelTimeouts() {
if (timeoutsHolder != null) {
timeoutsHolder.cancel();
timeoutsHolder = null;
}
}
public final Request getTargetRequest() {
return targetRequest;
}
public final Request getCurrentRequest() {
return currentRequest;
}
public final NettyRequest getNettyRequest() {
return nettyRequest;
}
public final void setNettyRequest(NettyRequest nettyRequest) {
this.nettyRequest = nettyRequest;
}
public final AsyncHandler<V> getAsyncHandler() {
return asyncHandler;
}
public final boolean isKeepAlive() {
return keepAlive;
}
public final void setKeepAlive(final boolean keepAlive) {
this.keepAlive = keepAlive;
}
public final HttpHeaders getHttpHeaders() {
return httpHeaders;
}
public final void setHttpHeaders(HttpHeaders httpHeaders) {
this.httpHeaders = httpHeaders;
}
public int incrementAndGetCurrentRedirectCount() {
return redirectCount.incrementAndGet();
}
public void setTimeoutsHolder(TimeoutsHolder timeoutsHolder) {
this.timeoutsHolder = timeoutsHolder;
}
public AtomicBoolean getInAuth() {
return inAuth;
}
public AtomicBoolean getInProxyAuth() {
return inProxyAuth;
}
public ChannelState getChannelState() {
return channelState.get();
}
public void setChannelState(ChannelState channelState) {
this.channelState.set(channelState);
}
public boolean getAndSetStatusReceived(boolean sr) {
return statusReceived.getAndSet(sr);
}
public boolean isStreamWasAlreadyConsumed() {
return streamWasAlreadyConsumed;
}
public void setStreamWasAlreadyConsumed(boolean streamWasAlreadyConsumed) {
this.streamWasAlreadyConsumed = streamWasAlreadyConsumed;
}
public long getLastTouch() {
return touch.get();
}
public void setHeadersAlreadyWrittenOnContinue(boolean headersAlreadyWrittenOnContinue) {
this.headersAlreadyWrittenOnContinue = headersAlreadyWrittenOnContinue;
}
public boolean isHeadersAlreadyWrittenOnContinue() {
return headersAlreadyWrittenOnContinue;
}
public void setDontWriteBodyBecauseExpectContinue(boolean dontWriteBodyBecauseExpectContinue) {
this.dontWriteBodyBecauseExpectContinue = dontWriteBodyBecauseExpectContinue;
}
public boolean isDontWriteBodyBecauseExpectContinue() {
return dontWriteBodyBecauseExpectContinue;
}
public void setReuseChannel(boolean reuseChannel) {
this.reuseChannel = reuseChannel;
}
public boolean isConnectAllowed() {
return allowConnect;
}
public void setConnectAllowed(boolean allowConnect) {
this.allowConnect = allowConnect;
}
public void attachChannel(Channel channel, boolean reuseChannel) {
// future could have been cancelled first
if (isDone()) {
Channels.silentlyCloseChannel(channel);
}
this.channel = channel;
this.reuseChannel = reuseChannel;
}
public Channel channel() {
return channel;
}
public boolean reuseChannel() {
return reuseChannel;
}
public boolean canRetry() {
return maxRetry > 0 && currentRetry.incrementAndGet() <= maxRetry;
}
public SocketAddress getChannelRemoteAddress() {
return channel != null ? channel.remoteAddress() : null;
}
public void setTargetRequest(Request targetRequest) {
this.targetRequest = targetRequest;
}
public void setCurrentRequest(Request currentRequest) {
this.currentRequest = currentRequest;
}
/**
* Return true if the {@link Future} can be recovered. There is some scenario where a connection can be closed by an
* unexpected IOException, and in some situation we can recover from that exception.
*
* @return true if that {@link Future} cannot be recovered.
*/
public boolean canBeReplayed() {
return !isDone() && canRetry()
&& !(Channels.isChannelValid(channel) && !getUri().getScheme().equalsIgnoreCase("https")) && !inAuth.get() && !inProxyAuth.get();
}
public long getStart() {
return start;
}
public Object getPartitionKey() {
return connectionPoolPartitioning.getPartitionKey(targetRequest.getUri(), targetRequest.getVirtualHost(), proxyServer);
}
public Realm getRealm() {
return realm;
}
public void setRealm(Realm realm) {
this.realm = realm;
}
public Realm getProxyRealm() {
return proxyRealm;
}
public void setProxyRealm(Realm proxyRealm) {
this.proxyRealm = proxyRealm;
}
@Override
public String toString() {
return "NettyResponseFuture{" + //
"currentRetry=" + currentRetry + //
",\n\tisDone=" + isDone + //
",\n\tisCancelled=" + isCancelled + //
",\n\tasyncHandler=" + asyncHandler + //
",\n\tnettyRequest=" + nettyRequest + //
",\n\tcontent=" + content + //
",\n\turi=" + getUri() + //
",\n\tkeepAlive=" + keepAlive + //
",\n\thttpHeaders=" + httpHeaders + //
",\n\texEx=" + exEx + //
",\n\tredirectCount=" + redirectCount + //
",\n\ttimeoutsHolder=" + timeoutsHolder + //
",\n\tinAuth=" + inAuth + //
",\n\tstatusReceived=" + statusReceived + //
",\n\ttouch=" + touch + //
'}';
}
}