-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathNettyResponseFuture.java
executable file
·560 lines (468 loc) · 18 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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
/*
* Copyright (c) 2014-2024 AsyncHttpClient Project. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.asynchttpclient.netty;
import io.netty.channel.Channel;
import org.asynchttpclient.AsyncHandler;
import org.asynchttpclient.ListenableFuture;
import org.asynchttpclient.Realm;
import org.asynchttpclient.Request;
import org.asynchttpclient.channel.ChannelPoolPartitioning;
import org.asynchttpclient.netty.channel.ChannelState;
import org.asynchttpclient.netty.channel.Channels;
import org.asynchttpclient.netty.channel.ConnectionSemaphore;
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;
import java.io.IOException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
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.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import static org.asynchttpclient.util.DateUtils.unpreciseMillisTime;
/**
* 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> implements ListenableFuture<V> {
private static final Logger LOGGER = LoggerFactory.getLogger(NettyResponseFuture.class);
@SuppressWarnings("rawtypes")
private static final AtomicIntegerFieldUpdater<NettyResponseFuture> REDIRECT_COUNT_UPDATER = AtomicIntegerFieldUpdater
.newUpdater(NettyResponseFuture.class, "redirectCount");
@SuppressWarnings("rawtypes")
private static final AtomicIntegerFieldUpdater<NettyResponseFuture> CURRENT_RETRY_UPDATER = AtomicIntegerFieldUpdater
.newUpdater(NettyResponseFuture.class, "currentRetry");
@SuppressWarnings("rawtypes")
private static final AtomicIntegerFieldUpdater<NettyResponseFuture> IS_DONE_FIELD = AtomicIntegerFieldUpdater
.newUpdater(NettyResponseFuture.class, "isDone");
@SuppressWarnings("rawtypes")
private static final AtomicIntegerFieldUpdater<NettyResponseFuture> IS_CANCELLED_FIELD = AtomicIntegerFieldUpdater
.newUpdater(NettyResponseFuture.class, "isCancelled");
@SuppressWarnings("rawtypes")
private static final AtomicIntegerFieldUpdater<NettyResponseFuture> IN_AUTH_FIELD = AtomicIntegerFieldUpdater
.newUpdater(NettyResponseFuture.class, "inAuth");
@SuppressWarnings("rawtypes")
private static final AtomicIntegerFieldUpdater<NettyResponseFuture> IN_PROXY_AUTH_FIELD = AtomicIntegerFieldUpdater
.newUpdater(NettyResponseFuture.class, "inProxyAuth");
@SuppressWarnings("rawtypes")
private static final AtomicIntegerFieldUpdater<NettyResponseFuture> CONTENT_PROCESSED_FIELD = AtomicIntegerFieldUpdater
.newUpdater(NettyResponseFuture.class, "contentProcessed");
@SuppressWarnings("rawtypes")
private static final AtomicIntegerFieldUpdater<NettyResponseFuture> ON_THROWABLE_CALLED_FIELD = AtomicIntegerFieldUpdater
.newUpdater(NettyResponseFuture.class, "onThrowableCalled");
@SuppressWarnings("rawtypes")
private static final AtomicReferenceFieldUpdater<NettyResponseFuture, TimeoutsHolder> TIMEOUTS_HOLDER_FIELD = AtomicReferenceFieldUpdater
.newUpdater(NettyResponseFuture.class, TimeoutsHolder.class, "timeoutsHolder");
@SuppressWarnings("rawtypes")
private static final AtomicReferenceFieldUpdater<NettyResponseFuture, Object> PARTITION_KEY_LOCK_FIELD = AtomicReferenceFieldUpdater
.newUpdater(NettyResponseFuture.class, Object.class, "partitionKeyLock");
private final long start = unpreciseMillisTime();
private final ChannelPoolPartitioning connectionPoolPartitioning;
private final ConnectionSemaphore connectionSemaphore;
private final ProxyServer proxyServer;
private final int maxRetry;
private final CompletableFuture<V> future = new CompletableFuture<>();
public Throwable pendingException;
// state mutated from outside the event loop
// TODO check if they are indeed mutated outside the event loop
private volatile int isDone;
private volatile int isCancelled;
private volatile int inAuth;
private volatile int inProxyAuth;
@SuppressWarnings("unused")
private volatile int contentProcessed;
@SuppressWarnings("unused")
private volatile int onThrowableCalled;
@SuppressWarnings("unused")
private volatile TimeoutsHolder timeoutsHolder;
// partition key, when != null used to release lock in ChannelManager
private volatile Object partitionKeyLock;
// volatile where we need CAS ops
private volatile int redirectCount;
private volatile int currentRetry;
// volatile where we don't need CAS ops
private volatile long touch = unpreciseMillisTime();
private volatile ChannelState channelState = ChannelState.NEW;
// state mutated only inside the event loop
private Channel channel;
private boolean keepAlive = true;
private Request targetRequest;
private Request currentRequest;
private NettyRequest nettyRequest;
private AsyncHandler<V> asyncHandler;
private boolean streamAlreadyConsumed;
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,
ChannelPoolPartitioning connectionPoolPartitioning,
ConnectionSemaphore connectionSemaphore,
ProxyServer proxyServer) {
this.asyncHandler = asyncHandler;
targetRequest = currentRequest = originalRequest;
this.nettyRequest = nettyRequest;
this.connectionPoolPartitioning = connectionPoolPartitioning;
this.connectionSemaphore = connectionSemaphore;
this.proxyServer = proxyServer;
this.maxRetry = maxRetry;
}
private void releasePartitionKeyLock() {
if (connectionSemaphore == null) {
return;
}
Object partitionKey = takePartitionKeyLock();
if (partitionKey != null) {
connectionSemaphore.releaseChannelLock(partitionKey);
}
}
// Take partition key lock object,
// but do not release channel lock.
public Object takePartitionKeyLock() {
// shortcut, much faster than getAndSet
if (partitionKeyLock == null) {
return null;
}
return PARTITION_KEY_LOCK_FIELD.getAndSet(this, null);
}
// java.util.concurrent.Future
@Override
public boolean isDone() {
return isDone != 0 || isCancelled();
}
@Override
public boolean isCancelled() {
return isCancelled != 0;
}
@Override
public boolean cancel(boolean force) {
releasePartitionKeyLock();
cancelTimeouts();
if (IS_CANCELLED_FIELD.getAndSet(this, 1) != 0) {
return false;
}
// cancel could happen before channel was attached
if (channel != null) {
Channels.setDiscard(channel);
Channels.silentlyCloseChannel(channel);
}
if (ON_THROWABLE_CALLED_FIELD.getAndSet(this, 1) == 0) {
try {
asyncHandler.onThrowable(new CancellationException());
} catch (Throwable t) {
LOGGER.warn("cancel", t);
}
}
future.cancel(false);
return true;
}
@Override
public V get() throws InterruptedException, ExecutionException {
return future.get();
}
@Override
public V get(long l, TimeUnit tu) throws InterruptedException, TimeoutException, ExecutionException {
return future.get(l, tu);
}
private void loadContent() throws ExecutionException {
if (future.isDone()) {
try {
future.get();
} catch (InterruptedException e) {
throw new RuntimeException("unreachable", e);
}
}
// No more retry
CURRENT_RETRY_UPDATER.set(this, maxRetry);
if (CONTENT_PROCESSED_FIELD.getAndSet(this, 1) == 0) {
try {
future.complete(asyncHandler.onCompleted());
} catch (Throwable ex) {
if (ON_THROWABLE_CALLED_FIELD.getAndSet(this, 1) == 0) {
try {
try {
asyncHandler.onThrowable(ex);
} catch (Throwable t) {
LOGGER.debug("asyncHandler.onThrowable", t);
}
} finally {
cancelTimeouts();
}
}
future.completeExceptionally(ex);
}
}
future.getNow(null);
}
// org.asynchttpclient.ListenableFuture
private boolean terminateAndExit() {
releasePartitionKeyLock();
cancelTimeouts();
channel = null;
reuseChannel = false;
return IS_DONE_FIELD.getAndSet(this, 1) != 0 || isCancelled != 0;
}
@Override
public void done() {
if (terminateAndExit()) {
return;
}
try {
loadContent();
} catch (ExecutionException ignored) {
} catch (RuntimeException t) {
future.completeExceptionally(t);
} catch (Throwable t) {
future.completeExceptionally(t);
throw t;
}
}
@Override
public void abort(final Throwable t) {
if (terminateAndExit()) {
return;
}
future.completeExceptionally(t);
if (ON_THROWABLE_CALLED_FIELD.compareAndSet(this, 0, 1)) {
try {
asyncHandler.onThrowable(t);
} catch (Throwable te) {
LOGGER.debug("asyncHandler.onThrowable", te);
}
}
}
@Override
public void touch() {
touch = unpreciseMillisTime();
}
@Override
public ListenableFuture<V> addListener(Runnable listener, Executor exec) {
if (exec == null) {
exec = Runnable::run;
}
future.whenCompleteAsync((r, v) -> listener.run(), exec);
return this;
}
@Override
public CompletableFuture<V> toCompletableFuture() {
return future;
}
// INTERNAL
public Uri getUri() {
return targetRequest.getUri();
}
public ProxyServer getProxyServer() {
return proxyServer;
}
public void cancelTimeouts() {
TimeoutsHolder ref = TIMEOUTS_HOLDER_FIELD.getAndSet(this, null);
if (ref != null) {
ref.cancel();
}
}
public Request getTargetRequest() {
return targetRequest;
}
public void setTargetRequest(Request targetRequest) {
this.targetRequest = targetRequest;
}
public Request getCurrentRequest() {
return currentRequest;
}
public void setCurrentRequest(Request currentRequest) {
this.currentRequest = currentRequest;
}
public NettyRequest getNettyRequest() {
return nettyRequest;
}
public void setNettyRequest(NettyRequest nettyRequest) {
this.nettyRequest = nettyRequest;
}
public AsyncHandler<V> getAsyncHandler() {
return asyncHandler;
}
public void setAsyncHandler(AsyncHandler<V> asyncHandler) {
this.asyncHandler = asyncHandler;
}
public boolean isKeepAlive() {
return keepAlive;
}
public void setKeepAlive(final boolean keepAlive) {
this.keepAlive = keepAlive;
}
public int incrementAndGetCurrentRedirectCount() {
return REDIRECT_COUNT_UPDATER.incrementAndGet(this);
}
public TimeoutsHolder getTimeoutsHolder() {
return TIMEOUTS_HOLDER_FIELD.get(this);
}
public void setTimeoutsHolder(TimeoutsHolder timeoutsHolder) {
TimeoutsHolder ref = TIMEOUTS_HOLDER_FIELD.getAndSet(this, timeoutsHolder);
if (ref != null) {
ref.cancel();
}
}
public boolean isInAuth() {
return inAuth != 0;
}
public void setInAuth(boolean inAuth) {
this.inAuth = inAuth ? 1 : 0;
}
public boolean isAndSetInAuth(boolean set) {
return IN_AUTH_FIELD.getAndSet(this, set ? 1 : 0) != 0;
}
public boolean isInProxyAuth() {
return inProxyAuth != 0;
}
public void setInProxyAuth(boolean inProxyAuth) {
this.inProxyAuth = inProxyAuth ? 1 : 0;
}
public boolean isAndSetInProxyAuth(boolean inProxyAuth) {
return IN_PROXY_AUTH_FIELD.getAndSet(this, inProxyAuth ? 1 : 0) != 0;
}
public ChannelState getChannelState() {
return channelState;
}
public void setChannelState(ChannelState channelState) {
this.channelState = channelState;
}
public boolean isStreamConsumed() {
return streamAlreadyConsumed;
}
public void setStreamConsumed(boolean streamConsumed) {
streamAlreadyConsumed = streamConsumed;
}
public long getLastTouch() {
return touch;
}
public boolean isHeadersAlreadyWrittenOnContinue() {
return headersAlreadyWrittenOnContinue;
}
public void setHeadersAlreadyWrittenOnContinue(boolean headersAlreadyWrittenOnContinue) {
this.headersAlreadyWrittenOnContinue = headersAlreadyWrittenOnContinue;
}
public boolean isDontWriteBodyBecauseExpectContinue() {
return dontWriteBodyBecauseExpectContinue;
}
public void setDontWriteBodyBecauseExpectContinue(boolean dontWriteBodyBecauseExpectContinue) {
this.dontWriteBodyBecauseExpectContinue = dontWriteBodyBecauseExpectContinue;
}
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 isReuseChannel() {
return reuseChannel;
}
public void setReuseChannel(boolean reuseChannel) {
this.reuseChannel = reuseChannel;
}
public boolean incrementRetryAndCheck() {
return maxRetry > 0 && CURRENT_RETRY_UPDATER.incrementAndGet(this) <= maxRetry;
}
/**
* 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 isReplayPossible() {
return !isDone() && !(Channels.isChannelActive(channel) && !"https".equalsIgnoreCase(getUri().getScheme()))
&& inAuth == 0 && inProxyAuth == 0;
}
public long getStart() {
return start;
}
public Object getPartitionKey() {
return connectionPoolPartitioning.getPartitionKey(targetRequest.getUri(), targetRequest.getVirtualHost(),
proxyServer);
}
public void acquirePartitionLockLazily() throws IOException {
if (connectionSemaphore == null || partitionKeyLock != null) {
return;
}
Object partitionKey = getPartitionKey();
connectionSemaphore.acquireChannelLock(partitionKey);
Object prevKey = PARTITION_KEY_LOCK_FIELD.getAndSet(this, partitionKey);
if (prevKey != null) {
// self-check
connectionSemaphore.releaseChannelLock(prevKey);
releasePartitionKeyLock();
throw new IllegalStateException("Trying to acquire partition lock concurrently. Please report.");
}
if (isDone()) {
// may be cancelled while we acquired a lock
releasePartitionKeyLock();
}
}
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\tfuture=" + future + //
",\n\turi=" + getUri() + //
",\n\tkeepAlive=" + keepAlive + //
",\n\tredirectCount=" + redirectCount + //
",\n\ttimeoutsHolder=" + TIMEOUTS_HOLDER_FIELD.get(this) + //
",\n\tinAuth=" + inAuth + //
",\n\ttouch=" + touch + //
'}';
}
}