-
Notifications
You must be signed in to change notification settings - Fork 630
/
Http2Pool.java
1066 lines (936 loc) · 31.5 KB
/
Http2Pool.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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2021-2022 VMware, Inc. or its affiliates, 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
*
* https://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 reactor.netty.http.client;
import java.time.Clock;
import java.time.Duration;
import java.util.Iterator;
import java.util.Objects;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.function.Function;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.ssl.ApplicationProtocolNames;
import io.netty.handler.ssl.SslHandler;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.core.Disposable;
import reactor.core.Disposables;
import reactor.core.Scannable;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Operators;
import reactor.netty.Connection;
import reactor.netty.FutureMono;
import reactor.netty.NettyPipeline;
import reactor.netty.internal.shaded.reactor.pool.InstrumentedPool;
import reactor.netty.internal.shaded.reactor.pool.PoolAcquirePendingLimitException;
import reactor.netty.internal.shaded.reactor.pool.PoolAcquireTimeoutException;
import reactor.netty.internal.shaded.reactor.pool.PoolConfig;
import reactor.netty.internal.shaded.reactor.pool.PoolShutdownException;
import reactor.netty.internal.shaded.reactor.pool.PooledRef;
import reactor.netty.internal.shaded.reactor.pool.PooledRefMetadata;
import reactor.netty.resources.ConnectionProvider;
import reactor.util.Logger;
import reactor.util.Loggers;
import reactor.util.annotation.Nullable;
import reactor.util.context.Context;
import static reactor.netty.ReactorNetty.format;
/**
* <p>This class is intended to be used only as {@code HTTP/2} connection pool. It doesn't have generic purpose.
* <p>
* The connection is removed from the pool when:
* <ul>
* <li>The connection is closed.</li>
* <li>GO_AWAY is received and there are no active streams.</li>
* <li>The eviction predicate evaluates to true and there are no active streams.</li>
* <li>When the client is in one of the two modes: 1) H2 and HTTP/1.1 or 2) H2C and HTTP/1.1,
* and the negotiated protocol is HTTP/1.1.</li>
* </ul>
* <p>
* The connection is filtered out when:
* <ul>
* <li>The connection's eviction predicate evaluates to true or GO_AWAY is received, and there are active streams. In this case, the
* connection stays in the pool, but it is not used. Once there are no active streams, the connection is removed
* from the pool.</li>
* <li>The connection has reached its max active streams configuration. In this case, the connection stays
* in the pool, but it is not used. Once the number of the active streams is below max active streams configuration,
* the connection can be used again.</li>
* </ul>
* <p>
* This pool always invalidate the {@link PooledRef}, there is no release functionality.
* <ul>
* <li>{@link PoolMetrics#acquiredSize()}, {@link PoolMetrics#allocatedSize()} and {@link PoolMetrics#idleSize()}
* always return the number of the cached connections.</li>
* <li>{@link Http2Pool#activeStreams()} always return the active streams from all connections currently in the pool.</li>
* </ul>
* <p>
* If minimum connections is specified, the cached connections with active streams will be kept at that minimum
* (can be the best effort). However, if the cached connections have reached max concurrent streams,
* then new connections will be allocated up to the maximum connections limit.
* <p>
* Configurations that are not applicable
* <ul>
* <li>{@link PoolConfig#destroyHandler()} - the destroy handler cannot be used as the destruction is more complex.</li>
* <li>{@link PoolConfig#metricsRecorder()} - no pool instrumentation.</li>
* <li>{@link PoolConfig#releaseHandler()} - release functionality works as invalidate.</li>
* <li>{@link PoolConfig#reuseIdleResourcesInLruOrder()} - FIFO is used when checking the connections.</li>
* <li>FIFO is used when obtaining the pending borrowers</li>
* <li>Warm up functionality is not supported</li>
* </ul>
* <p>This class is based on
* https://github.com/reactor/reactor-pool/blob/v0.2.7/src/main/java/reactor/pool/SimpleDequePool.java
*
* @author Violeta Georgieva
*/
final class Http2Pool implements InstrumentedPool<Connection>, InstrumentedPool.PoolMetrics {
static final Logger log = Loggers.getLogger(Http2Pool.class);
volatile int acquired;
static final AtomicIntegerFieldUpdater<Http2Pool> ACQUIRED =
AtomicIntegerFieldUpdater.newUpdater(Http2Pool.class, "acquired");
volatile ConcurrentLinkedQueue<Slot> connections;
@SuppressWarnings("rawtypes")
static final AtomicReferenceFieldUpdater<Http2Pool, ConcurrentLinkedQueue> CONNECTIONS =
AtomicReferenceFieldUpdater.newUpdater(Http2Pool.class, ConcurrentLinkedQueue.class, "connections");
volatile int idleSize;
private static final AtomicIntegerFieldUpdater<Http2Pool> IDLE_SIZE =
AtomicIntegerFieldUpdater.newUpdater(Http2Pool.class, "idleSize");
/**
* Pending borrowers queue. Never invoke directly the poll/add/remove methods and instead of that,
* use addPending/pollPending/removePending methods which take care of maintaining the pending queue size.
* @see #removePending(ConcurrentLinkedDeque, Borrower)
* @see #addPending(ConcurrentLinkedDeque, Borrower, boolean)
* @see #pollPending(ConcurrentLinkedDeque, boolean)
* @see #PENDING_SIZE
* @see #pendingSize
*/
volatile ConcurrentLinkedDeque<Borrower> pending;
@SuppressWarnings("rawtypes")
static final AtomicReferenceFieldUpdater<Http2Pool, ConcurrentLinkedDeque> PENDING =
AtomicReferenceFieldUpdater.newUpdater(Http2Pool.class, ConcurrentLinkedDeque.class, "pending");
volatile int pendingSize;
private static final AtomicIntegerFieldUpdater<Http2Pool> PENDING_SIZE =
AtomicIntegerFieldUpdater.newUpdater(Http2Pool.class, "pendingSize");
@SuppressWarnings("rawtypes")
static final ConcurrentLinkedDeque TERMINATED = new ConcurrentLinkedDeque();
volatile long totalMaxConcurrentStreams;
static final AtomicLongFieldUpdater<Http2Pool> TOTAL_MAX_CONCURRENT_STREAMS =
AtomicLongFieldUpdater.newUpdater(Http2Pool.class, "totalMaxConcurrentStreams");
volatile int wip;
static final AtomicIntegerFieldUpdater<Http2Pool> WIP =
AtomicIntegerFieldUpdater.newUpdater(Http2Pool.class, "wip");
final Clock clock;
final Long maxConcurrentStreams;
final int minConnections;
final PoolConfig<Connection> poolConfig;
long lastInteractionTimestamp;
Disposable evictionTask;
Http2Pool(PoolConfig<Connection> poolConfig, @Nullable ConnectionProvider.AllocationStrategy<?> allocationStrategy) {
this.clock = poolConfig.clock();
this.connections = new ConcurrentLinkedQueue<>();
this.lastInteractionTimestamp = clock.millis();
this.maxConcurrentStreams = allocationStrategy instanceof Http2AllocationStrategy ?
((Http2AllocationStrategy) allocationStrategy).maxConcurrentStreams() : -1;
this.minConnections = allocationStrategy == null ? 0 : allocationStrategy.permitMinimum();
this.pending = new ConcurrentLinkedDeque<>();
this.poolConfig = poolConfig;
recordInteractionTimestamp();
scheduleEviction();
}
@Override
public Mono<PooledRef<Connection>> acquire() {
return new BorrowerMono(this, Duration.ZERO);
}
@Override
public Mono<PooledRef<Connection>> acquire(Duration timeout) {
return new BorrowerMono(this, timeout);
}
@Override
public int acquiredSize() {
return allocatedSize() - idleSize();
}
@Override
public int allocatedSize() {
return poolConfig.allocationStrategy().permitGranted();
}
@Override
public PoolConfig<Connection> config() {
return poolConfig;
}
@Override
public Mono<Void> disposeLater() {
return Mono.defer(() -> {
recordInteractionTimestamp();
@SuppressWarnings("unchecked")
ConcurrentLinkedDeque<Borrower> q = PENDING.getAndSet(this, TERMINATED);
if (q != TERMINATED) {
evictionTask.dispose();
Borrower p;
while ((p = pollPending(q, true)) != null) {
p.fail(new PoolShutdownException());
}
@SuppressWarnings("unchecked")
ConcurrentLinkedQueue<Slot> slots = CONNECTIONS.getAndSet(this, null);
if (slots != null) {
Mono<Void> closeMonos = Mono.empty();
while (!slots.isEmpty()) {
Slot slot = pollSlot(slots);
if (slot != null) {
slot.invalidate();
closeMonos = closeMonos.and(DEFAULT_DESTROY_HANDLER.apply(slot.connection));
}
}
return closeMonos;
}
}
return Mono.empty();
});
}
@Override
public int getMaxAllocatedSize() {
return Integer.MAX_VALUE;
}
@Override
public int getMaxPendingAcquireSize() {
return poolConfig.maxPending() < 0 ? Integer.MAX_VALUE : poolConfig.maxPending();
}
@Override
public int idleSize() {
return idleSize;
}
@Override
public boolean isDisposed() {
return PENDING.get(this) == TERMINATED || CONNECTIONS.get(this) == null;
}
@Override
public boolean isInactiveForMoreThan(Duration duration) {
return pendingAcquireSize() == 0 && allocatedSize() == 0
&& secondsSinceLastInteraction() >= duration.getSeconds();
}
@Override
public PoolMetrics metrics() {
return this;
}
@Override
public int pendingAcquireSize() {
return pendingSize;
}
@Override
public long secondsSinceLastInteraction() {
long sinceMs = clock.millis() - lastInteractionTimestamp;
return sinceMs / 1000;
}
@Override
public Mono<Integer> warmup() {
return Mono.just(0);
}
int activeStreams() {
return acquired;
}
void cancelAcquire(Borrower borrower) {
if (!isDisposed()) {
ConcurrentLinkedDeque<Borrower> q = pending;
removePending(q, borrower);
}
}
@SuppressWarnings("FutureReturnValueIgnored")
Mono<Void> destroyPoolable(Http2PooledRef ref) {
assert ref.slot.connection.channel().eventLoop().inEventLoop();
Mono<Void> mono = Mono.empty();
try {
// By default, check the connection for removal on acquire and invalidate (only if there are no active streams)
if (ref.slot.decrementConcurrencyAndGet() == 0) {
// not HTTP/2 request
if (ref.slot.http2FrameCodecCtx() == null) {
ref.slot.invalidate();
removeSlot(ref.slot);
}
// If there is eviction in background, the background process will remove this connection
else if (poolConfig.evictInBackgroundInterval().isZero()) {
// not active
if (!ref.poolable().channel().isActive()) {
ref.slot.invalidate();
removeSlot(ref.slot);
}
// received GO_AWAY
if (ref.slot.goAwayReceived()) {
ref.slot.invalidate();
removeSlot(ref.slot);
}
// eviction predicate evaluates to true
else if (testEvictionPredicate(ref.slot)) {
//"FutureReturnValueIgnored" this is deliberate
ref.slot.connection.channel().close();
ref.slot.invalidate();
removeSlot(ref.slot);
}
}
}
}
catch (Throwable destroyFunctionError) {
mono = Mono.error(destroyFunctionError);
}
return mono;
}
void doAcquire(Borrower borrower) {
if (isDisposed()) {
borrower.fail(new PoolShutdownException());
return;
}
pendingOffer(borrower);
drain();
}
void drain() {
if (WIP.getAndIncrement(this) == 0) {
drainLoop();
}
}
void drainLoop() {
recordInteractionTimestamp();
int maxPending = poolConfig.maxPending();
for (;;) {
@SuppressWarnings("unchecked")
ConcurrentLinkedQueue<Slot> resources = CONNECTIONS.get(this);
@SuppressWarnings("unchecked")
ConcurrentLinkedDeque<Borrower> borrowers = PENDING.get(this);
if (resources == null || borrowers == TERMINATED) {
return;
}
int borrowersCount = pendingSize;
if (borrowersCount != 0) {
// find a connection that can be used for opening a new stream
// when cached connections are below minimum connections, then allocate a new connection
boolean belowMinConnections = minConnections > 0 &&
poolConfig.allocationStrategy().permitGranted() < minConnections;
Slot slot = belowMinConnections ? null : findConnection(resources);
if (slot != null) {
Borrower borrower = pollPending(borrowers, true);
if (borrower == null) {
offerSlot(resources, slot);
continue;
}
if (isDisposed()) {
borrower.fail(new PoolShutdownException());
return;
}
borrower.stopPendingCountdown();
if (log.isDebugEnabled()) {
log.debug(format(slot.connection.channel(), "Channel activated"));
}
ACQUIRED.incrementAndGet(this);
slot.connection.channel().eventLoop().execute(() -> {
borrower.deliver(new Http2PooledRef(slot));
drain();
});
}
else {
int resourcesCount = idleSize;
if (minConnections > 0 &&
poolConfig.allocationStrategy().permitGranted() >= minConnections &&
resourcesCount == 0) {
// connections allocations were triggered
}
else {
int permits = poolConfig.allocationStrategy().getPermits(1);
if (permits <= 0) {
if (maxPending >= 0) {
borrowersCount = pendingSize;
int toCull = borrowersCount - maxPending;
for (int i = 0; i < toCull; i++) {
Borrower extraneous = pollPending(borrowers, true);
if (extraneous != null) {
pendingAcquireLimitReached(extraneous, maxPending);
}
}
}
}
else {
if (permits > 1) {
// warmup is not supported
poolConfig.allocationStrategy().returnPermits(permits - 1);
}
Borrower borrower = pollPending(borrowers, true);
if (borrower == null) {
continue;
}
if (isDisposed()) {
borrower.fail(new PoolShutdownException());
return;
}
borrower.stopPendingCountdown();
Mono<Connection> allocator = poolConfig.allocator();
Mono<Connection> primary =
allocator.doOnEach(sig -> {
if (sig.isOnNext()) {
Connection newInstance = sig.get();
assert newInstance != null;
Slot newSlot = new Slot(this, newInstance);
if (log.isDebugEnabled()) {
log.debug(format(newInstance.channel(), "Channel activated"));
}
ACQUIRED.incrementAndGet(this);
borrower.deliver(new Http2PooledRef(newSlot));
}
else if (sig.isOnError()) {
Throwable error = sig.getThrowable();
assert error != null;
poolConfig.allocationStrategy().returnPermits(1);
borrower.fail(error);
}
})
.contextWrite(borrower.currentContext());
primary.subscribe(alreadyPropagated -> {}, alreadyPropagatedOrLogged -> drain(), this::drain);
}
}
}
}
if (WIP.decrementAndGet(this) == 0) {
recordInteractionTimestamp();
break;
}
}
}
@SuppressWarnings("FutureReturnValueIgnored")
void evictInBackground() {
@SuppressWarnings("unchecked")
ConcurrentLinkedQueue<Slot> resources = CONNECTIONS.get(this);
if (resources == null) {
//no need to schedule the task again, pool has been disposed
return;
}
if (WIP.getAndIncrement(this) == 0) {
if (pendingSize == 0) {
Iterator<Slot> slots = resources.iterator();
while (slots.hasNext()) {
Slot slot = slots.next();
if (slot.concurrency() == 0) {
if (!slot.connection.channel().isActive()) {
if (log.isDebugEnabled()) {
log.debug(format(slot.connection.channel(), "Channel is closed, remove from pool"));
}
recordInteractionTimestamp();
slots.remove();
IDLE_SIZE.decrementAndGet(this);
slot.invalidate();
continue;
}
if (slot.goAwayReceived()) {
if (log.isDebugEnabled()) {
log.debug(format(slot.connection.channel(), "Channel received GO_AWAY, remove from pool"));
}
recordInteractionTimestamp();
slots.remove();
IDLE_SIZE.decrementAndGet(this);
slot.invalidate();
continue;
}
if (testEvictionPredicate(slot)) {
if (log.isDebugEnabled()) {
log.debug(format(slot.connection.channel(), "Eviction predicate was true, remove from pool"));
}
//"FutureReturnValueIgnored" this is deliberate
slot.connection.channel().close();
recordInteractionTimestamp();
slots.remove();
IDLE_SIZE.decrementAndGet(this);
slot.invalidate();
}
}
}
}
//at the end if there are racing drain calls, go into the drainLoop
if (WIP.decrementAndGet(this) > 0) {
drainLoop();
}
}
//schedule the next iteration
scheduleEviction();
}
@Nullable
@SuppressWarnings("FutureReturnValueIgnored")
Slot findConnection(ConcurrentLinkedQueue<Slot> resources) {
int resourcesCount = idleSize;
while (resourcesCount > 0) {
// There are connections in the queue
resourcesCount--;
// get the connection
Slot slot = pollSlot(resources);
if (slot == null) {
continue;
}
// check the connection is active
if (!slot.connection.channel().isActive()) {
if (slot.concurrency() > 0) {
if (log.isDebugEnabled()) {
log.debug(format(slot.connection.channel(), "Channel is closed, {} active streams"),
slot.concurrency());
}
offerSlot(resources, slot);
}
else {
if (log.isDebugEnabled()) {
log.debug(format(slot.connection.channel(), "Channel is closed, remove from pool"));
}
slot.invalidate();
}
continue;
}
// check the connection received GO_AWAY
if (slot.goAwayReceived()) {
if (slot.concurrency() > 0) {
if (log.isDebugEnabled()) {
log.debug(format(slot.connection.channel(), "Channel received GO_AWAY, {} active streams"),
slot.concurrency());
}
offerSlot(resources, slot);
}
else {
if (log.isDebugEnabled()) {
log.debug(format(slot.connection.channel(), "Channel received GO_AWAY, remove from pool"));
}
slot.invalidate();
}
continue;
}
// check whether the eviction predicate for the connection evaluates to true
if (testEvictionPredicate(slot)) {
if (slot.concurrency() > 0) {
if (log.isDebugEnabled()) {
log.debug(format(slot.connection.channel(), "Eviction predicate was true, {} active streams"),
slot.concurrency());
}
offerSlot(resources, slot);
}
else {
if (log.isDebugEnabled()) {
log.debug(format(slot.connection.channel(), "Eviction predicate was true, remove from pool"));
}
//"FutureReturnValueIgnored" this is deliberate
slot.connection.channel().close();
slot.invalidate();
}
continue;
}
// check that the connection's max active streams has not been reached
if (!slot.canOpenStream()) {
offerSlot(resources, slot);
if (log.isDebugEnabled()) {
log.debug(format(slot.connection.channel(), "Max active streams is reached"));
}
continue;
}
return slot;
}
return null;
}
boolean testEvictionPredicate(Slot slot) {
return poolConfig.evictionPredicate().test(slot.connection, slot);
}
void pendingAcquireLimitReached(Borrower borrower, int maxPending) {
if (maxPending == 0) {
borrower.fail(new PoolAcquirePendingLimitException(0,
"No pending allowed and pool has reached allocation limit"));
}
else {
borrower.fail(new PoolAcquirePendingLimitException(maxPending));
}
}
/**
* @param borrower a new {@link Borrower} to add to the queue and later either serve or consider pending
*/
void pendingOffer(Borrower borrower) {
int maxPending = poolConfig.maxPending();
ConcurrentLinkedDeque<Borrower> pendingQueue = pending;
if (pendingQueue == TERMINATED) {
return;
}
int postOffer = addPending(pendingQueue, borrower, false);
if (WIP.getAndIncrement(this) == 0) {
ConcurrentLinkedQueue<Slot> ir = connections;
if (maxPending >= 0 && postOffer > maxPending && ir.isEmpty() && poolConfig.allocationStrategy().estimatePermitCount() == 0) {
Borrower toCull = pollPending(pendingQueue, false);
if (toCull != null) {
pendingAcquireLimitReached(toCull, maxPending);
}
if (WIP.decrementAndGet(this) > 0) {
drainLoop();
}
return;
}
drainLoop();
}
}
void recordInteractionTimestamp() {
this.lastInteractionTimestamp = clock.millis();
}
@Nullable
Borrower pollPending(ConcurrentLinkedDeque<Borrower> borrowers, boolean pollFirst) {
Borrower borrower = pollFirst ? borrowers.pollFirst() : borrowers.pollLast();
if (borrower != null) {
PENDING_SIZE.decrementAndGet(this);
}
return borrower;
}
void removePending(ConcurrentLinkedDeque<Borrower> borrowers, Borrower borrower) {
if (borrowers.remove(borrower)) {
PENDING_SIZE.decrementAndGet(this);
}
}
int addPending(ConcurrentLinkedDeque<Borrower> borrowers, Borrower borrower, boolean first) {
if (first) {
borrowers.offerFirst(borrower);
}
else {
borrowers.offerLast(borrower);
}
return PENDING_SIZE.incrementAndGet(this);
}
void offerSlot(@Nullable ConcurrentLinkedQueue<Slot> slots, Slot slot) {
if (slots != null && slots.offer(slot)) {
IDLE_SIZE.incrementAndGet(this);
}
}
@Nullable
Slot pollSlot(@Nullable ConcurrentLinkedQueue<Slot> slots) {
if (slots == null) {
return null;
}
Slot slot = slots.poll();
if (slot != null) {
IDLE_SIZE.decrementAndGet(this);
}
return slot;
}
void removeSlot(Slot slot) {
@SuppressWarnings("unchecked")
ConcurrentLinkedQueue<Slot> q = CONNECTIONS.get(slot.pool);
if (q != null && q.remove(slot)) {
IDLE_SIZE.decrementAndGet(this);
}
}
void scheduleEviction() {
if (!poolConfig.evictInBackgroundInterval().isZero()) {
long nanosEvictionInterval = poolConfig.evictInBackgroundInterval().toNanos();
this.evictionTask = poolConfig.evictInBackgroundScheduler()
.schedule(this::evictInBackground, nanosEvictionInterval, TimeUnit.NANOSECONDS);
}
else {
this.evictionTask = Disposables.disposed();
}
}
static final Function<Connection, Publisher<Void>> DEFAULT_DESTROY_HANDLER =
connection -> {
if (!connection.channel().isActive()) {
return Mono.empty();
}
return FutureMono.from(connection.channel().close());
};
static final class Borrower extends AtomicBoolean implements Scannable, Subscription, Runnable {
static final Disposable TIMEOUT_DISPOSED = Disposables.disposed();
final Duration acquireTimeout;
final CoreSubscriber<? super Http2PooledRef> actual;
final Http2Pool pool;
Disposable timeoutTask;
Borrower(CoreSubscriber<? super Http2PooledRef> actual, Http2Pool pool, Duration acquireTimeout) {
this.acquireTimeout = acquireTimeout;
this.actual = actual;
this.pool = pool;
this.timeoutTask = TIMEOUT_DISPOSED;
}
@Override
public void cancel() {
stopPendingCountdown();
if (compareAndSet(false, true)) {
pool.cancelAcquire(this);
}
}
Context currentContext() {
return actual.currentContext();
}
@Override
public void request(long n) {
if (Operators.validate(n)) {
long estimateStreamsCount = pool.totalMaxConcurrentStreams - pool.acquired;
int permits = pool.poolConfig.allocationStrategy().estimatePermitCount();
int pending = pool.pendingSize;
if (!acquireTimeout.isZero() && permits + estimateStreamsCount <= pending) {
timeoutTask = pool.poolConfig.pendingAcquireTimer().apply(this, acquireTimeout);
}
pool.doAcquire(this);
}
}
@Override
public void run() {
if (compareAndSet(false, true)) {
pool.cancelAcquire(Http2Pool.Borrower.this);
actual.onError(new PoolAcquireTimeoutException(acquireTimeout));
}
}
@Override
@Nullable
@SuppressWarnings("rawtypes")
public Object scanUnsafe(Attr key) {
if (key == Attr.CANCELLED) {
return get();
}
if (key == Attr.REQUESTED_FROM_DOWNSTREAM) {
return 1;
}
if (key == Attr.ACTUAL) {
return actual;
}
return null;
}
@Override
public String toString() {
return get() ? "Borrower(cancelled)" : "Borrower";
}
void deliver(Http2PooledRef poolSlot) {
assert poolSlot.slot.connection.channel().eventLoop().inEventLoop();
poolSlot.slot.incrementConcurrencyAndGet();
poolSlot.slot.deactivate();
if (get()) {
//CANCELLED or timeout reached
poolSlot.invalidate().subscribe(aVoid -> {}, e -> Operators.onErrorDropped(e, Context.empty()));
}
else {
actual.onNext(poolSlot);
actual.onComplete();
}
}
void fail(Throwable error) {
stopPendingCountdown();
if (!get()) {
actual.onError(error);
}
}
void stopPendingCountdown() {
timeoutTask.dispose();
}
}
static final class BorrowerMono extends Mono<PooledRef<Connection>> {
final Duration acquireTimeout;
final Http2Pool parent;
BorrowerMono(Http2Pool pool, Duration acquireTimeout) {
this.acquireTimeout = acquireTimeout;
this.parent = pool;
}
@Override
public void subscribe(CoreSubscriber<? super PooledRef<Connection>> actual) {
Objects.requireNonNull(actual, "subscribing with null");
Borrower borrower = new Borrower(actual, parent, acquireTimeout);
actual.onSubscribe(borrower);
}
}
static final class Http2PooledRef extends AtomicBoolean implements PooledRef<Connection>, PooledRefMetadata {
final int acquireCount;
final Slot slot;
Http2PooledRef(Slot slot) {
this.acquireCount = 0;
this.slot = slot;
}
@Override
public int acquireCount() {
return 1;
}
@Override
public long allocationTimestamp() {
return 0;
}
@Override
public long idleTime() {
return 0;
}
@Override
public Mono<Void> invalidate() {
return Mono.defer(() -> {
if (compareAndSet(false, true)) {
ACQUIRED.decrementAndGet(slot.pool);
return slot.pool.destroyPoolable(this).doFinally(st -> slot.pool.drain());
}
else {
return Mono.empty();
}
});
}
@Override
public long lifeTime() {
return 0;
}
@Override
public PooledRefMetadata metadata() {
return this;
}
@Override
public Connection poolable() {
return slot.connection;
}
@Override
public Mono<Void> release() {
return invalidate();
}
@Override
public long releaseTimestamp() {
return 0;
}
@Override
public String toString() {
return "PooledRef{poolable=" + slot.connection + '}';
}
}
static final class Slot extends AtomicBoolean implements PooledRefMetadata {
volatile int concurrency;
static final AtomicIntegerFieldUpdater<Slot> CONCURRENCY =
AtomicIntegerFieldUpdater.newUpdater(Slot.class, "concurrency");
final Connection connection;
final long creationTimestamp;
final Http2Pool pool;
final String applicationProtocol;
long idleTimestamp;
long maxConcurrentStreams;
volatile ChannelHandlerContext http2FrameCodecCtx;
volatile ChannelHandlerContext http2MultiplexHandlerCtx;
volatile ChannelHandlerContext h2cUpgradeHandlerCtx;
Slot(Http2Pool pool, Connection connection) {
this.connection = connection;
this.creationTimestamp = pool.clock.millis();
this.pool = pool;
SslHandler handler = connection.channel().pipeline().get(SslHandler.class);
if (handler != null) {
this.applicationProtocol = handler.applicationProtocol() != null ?
handler.applicationProtocol() : ApplicationProtocolNames.HTTP_1_1;
}
else {
this.applicationProtocol = null;
}
ChannelHandlerContext frameCodec = http2FrameCodecCtx();
if (frameCodec != null && http2MultiplexHandlerCtx() != null) {
this.maxConcurrentStreams = ((Http2FrameCodec) frameCodec.handler()).connection().local().maxActiveStreams();
this.maxConcurrentStreams = pool.maxConcurrentStreams == -1 ? maxConcurrentStreams :
Math.min(pool.maxConcurrentStreams, maxConcurrentStreams);
}
TOTAL_MAX_CONCURRENT_STREAMS.addAndGet(this.pool, this.maxConcurrentStreams);
}
boolean canOpenStream() {
ChannelHandlerContext frameCodec = http2FrameCodecCtx();
if (frameCodec != null && http2MultiplexHandlerCtx() != null) {
long maxActiveStreams = ((Http2FrameCodec) frameCodec.handler()).connection().local().maxActiveStreams();
maxActiveStreams = pool.maxConcurrentStreams == -1 ? maxActiveStreams :
Math.min(pool.maxConcurrentStreams, maxActiveStreams);
long diff = maxActiveStreams - maxConcurrentStreams;
if (diff != 0) {
maxConcurrentStreams = maxActiveStreams;
TOTAL_MAX_CONCURRENT_STREAMS.addAndGet(this.pool, diff);
}
int concurrency = this.concurrency;
return concurrency < maxActiveStreams;
}
return false;
}
int concurrency() {
return concurrency;
}
void deactivate() {
if (log.isDebugEnabled()) {
log.debug(format(connection.channel(), "Channel deactivated"));
}
@SuppressWarnings("unchecked")
ConcurrentLinkedQueue<Slot> slots = CONNECTIONS.get(pool);
pool.offerSlot(slots, this);
}
int decrementConcurrencyAndGet() {
int concurrency = CONCURRENCY.decrementAndGet(this);
idleTimestamp = pool.clock.millis();
return concurrency;
}
boolean goAwayReceived() {
ChannelHandlerContext frameCodec = http2FrameCodecCtx();
return frameCodec != null && ((Http2FrameCodec) frameCodec.handler()).connection().goAwayReceived();
}
@Nullable
ChannelHandlerContext http2FrameCodecCtx() {
ChannelHandlerContext ctx = http2FrameCodecCtx;
if (ctx != null && !ctx.isRemoved()) {
return ctx;
}
ctx = connection.channel().pipeline().context(Http2FrameCodec.class);
http2FrameCodecCtx = ctx;
return ctx;
}
@Nullable