/
ConnectionManager.java
1579 lines (1423 loc) · 65.9 KB
/
ConnectionManager.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 2017-2022 original authors
*
* 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 io.micronaut.http.client.netty;
import io.micronaut.core.annotation.Internal;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.propagation.PropagatedContext;
import io.micronaut.core.reflect.InstantiationUtils;
import io.micronaut.core.util.StringUtils;
import io.micronaut.core.util.SupplierUtil;
import io.micronaut.http.client.HttpClientConfiguration;
import io.micronaut.http.client.HttpVersionSelection;
import io.micronaut.http.client.exceptions.HttpClientException;
import io.micronaut.http.client.exceptions.HttpClientExceptionUtils;
import io.micronaut.http.client.netty.ssl.ClientSslBuilder;
import io.micronaut.http.netty.channel.ChannelPipelineCustomizer;
import io.micronaut.http.netty.channel.NettyThreadFactory;
import io.micronaut.websocket.exceptions.WebSocketSessionException;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFactory;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpClientUpgradeHandler;
import io.netty.handler.codec.http.HttpContentDecompressor;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpScheme;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler;
import io.netty.handler.codec.http2.Http2ClientUpgradeCodec;
import io.netty.handler.codec.http2.Http2FrameCodec;
import io.netty.handler.codec.http2.Http2FrameCodecBuilder;
import io.netty.handler.codec.http2.Http2FrameLogger;
import io.netty.handler.codec.http2.Http2GoAwayFrame;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2MultiplexActiveStreamsException;
import io.netty.handler.codec.http2.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2SettingsAckFrame;
import io.netty.handler.codec.http2.Http2SettingsFrame;
import io.netty.handler.codec.http2.Http2StreamChannel;
import io.netty.handler.codec.http2.Http2StreamChannelBootstrap;
import io.netty.handler.codec.http2.Http2StreamFrameToHttpObjectCodec;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.proxy.HttpProxyHandler;
import io.netty.handler.proxy.Socks5ProxyHandler;
import io.netty.handler.ssl.ApplicationProtocolNames;
import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.SslHandshakeCompletionEvent;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.timeout.ReadTimeoutException;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.incubator.codec.http3.Http3;
import io.netty.incubator.codec.http3.Http3ClientConnectionHandler;
import io.netty.incubator.codec.http3.Http3FrameToHttpObjectCodec;
import io.netty.incubator.codec.http3.Http3HeadersFrame;
import io.netty.incubator.codec.http3.Http3RequestStreamInitializer;
import io.netty.incubator.codec.http3.Http3SettingsFrame;
import io.netty.incubator.codec.quic.QuicChannel;
import io.netty.incubator.codec.quic.QuicSslContext;
import io.netty.incubator.codec.quic.QuicStreamChannel;
import io.netty.resolver.NoopAddressResolverGroup;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ResourceLeakDetector;
import io.netty.util.ResourceLeakDetectorFactory;
import io.netty.util.ResourceLeakTracker;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.ScheduledFuture;
import org.slf4j.Logger;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
import reactor.core.scheduler.Schedulers;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLParameters;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
/**
* Connection manager for {@link DefaultHttpClient}. This class manages the lifecycle of netty
* channels (wrapped in {@link PoolHandle}s), including pooling and timeouts.<br>
* Note: This class is public for use in micronaut-oracle-cloud.
*/
@Internal
public class ConnectionManager {
private final HttpVersionSelection httpVersion;
private final Logger log;
private final Map<DefaultHttpClient.RequestKey, Pool> pools = new ConcurrentHashMap<>();
private final ClientSslBuilder nettyClientSslBuilder;
private EventLoopGroup group;
private final boolean shutdownGroup;
private final ThreadFactory threadFactory;
private final ChannelFactory<? extends Channel> socketChannelFactory;
private final ChannelFactory<? extends Channel> udpChannelFactory;
private Bootstrap bootstrap;
private Bootstrap udpBootstrap;
private final HttpClientConfiguration configuration;
private volatile SslContext sslContext;
private volatile /* QuicSslContext */ Object http3SslContext;
private volatile SslContext websocketSslContext;
private final NettyClientCustomizer clientCustomizer;
private final String informationalServiceId;
/**
* Copy constructor used by the test suite to patch this manager.
*
* @param from Original connection manager
*/
ConnectionManager(ConnectionManager from) {
this.httpVersion = from.httpVersion;
this.log = from.log;
this.group = from.group;
this.shutdownGroup = from.shutdownGroup;
this.threadFactory = from.threadFactory;
this.socketChannelFactory = from.socketChannelFactory;
this.udpChannelFactory = from.udpChannelFactory;
this.bootstrap = from.bootstrap;
this.udpBootstrap = from.udpBootstrap;
this.configuration = from.configuration;
this.sslContext = from.sslContext;
this.http3SslContext = from.http3SslContext;
this.websocketSslContext = from.websocketSslContext;
this.clientCustomizer = from.clientCustomizer;
this.informationalServiceId = from.informationalServiceId;
this.nettyClientSslBuilder = from.nettyClientSslBuilder;
}
ConnectionManager(
Logger log,
@Nullable EventLoopGroup eventLoopGroup,
@Nullable ThreadFactory threadFactory,
HttpClientConfiguration configuration,
@Nullable HttpVersionSelection httpVersion,
ChannelFactory<? extends Channel> socketChannelFactory,
ChannelFactory<? extends Channel> udpChannelFactory,
ClientSslBuilder nettyClientSslBuilder,
NettyClientCustomizer clientCustomizer,
String informationalServiceId) {
if (httpVersion == null) {
httpVersion = HttpVersionSelection.forClientConfiguration(configuration);
}
this.log = log;
this.httpVersion = httpVersion;
this.threadFactory = threadFactory;
this.socketChannelFactory = socketChannelFactory;
this.udpChannelFactory = udpChannelFactory;
this.configuration = configuration;
this.clientCustomizer = clientCustomizer;
this.informationalServiceId = informationalServiceId;
this.nettyClientSslBuilder = nettyClientSslBuilder;
if (eventLoopGroup != null) {
group = eventLoopGroup;
shutdownGroup = false;
} else {
group = createEventLoopGroup(configuration, threadFactory);
shutdownGroup = true;
}
refresh();
}
final void refresh() {
SslContext oldSslContext = sslContext;
SslContext oldWebsocketSslContext = websocketSslContext;
websocketSslContext = null;
if (configuration.getSslConfiguration().isEnabled()) {
sslContext = nettyClientSslBuilder.build(configuration.getSslConfiguration(), httpVersion);
} else {
sslContext = null;
}
if (httpVersion.isHttp3()) {
http3SslContext = nettyClientSslBuilder.buildHttp3(configuration.getSslConfiguration());
} else {
http3SslContext = null;
}
initBootstrap();
for (Pool pool : pools.values()) {
pool.forEachConnection(c -> ((Pool.ConnectionHolder) c).windDownConnection());
}
ReferenceCountUtil.release(oldSslContext);
ReferenceCountUtil.release(oldWebsocketSslContext);
}
/**
* Creates the {@link NioEventLoopGroup} for this client.
*
* @param configuration The configuration
* @param threadFactory The thread factory
* @return The group
*/
private static NioEventLoopGroup createEventLoopGroup(HttpClientConfiguration configuration, ThreadFactory threadFactory) {
OptionalInt numOfThreads = configuration.getNumOfThreads();
Optional<Class<? extends ThreadFactory>> threadFactoryType = configuration.getThreadFactory();
boolean hasThreads = numOfThreads.isPresent();
boolean hasFactory = threadFactoryType.isPresent();
NioEventLoopGroup group;
if (hasThreads && hasFactory) {
group = new NioEventLoopGroup(numOfThreads.getAsInt(), InstantiationUtils.instantiate(threadFactoryType.get()));
} else if (hasThreads) {
if (threadFactory != null) {
group = new NioEventLoopGroup(numOfThreads.getAsInt(), threadFactory);
} else {
group = new NioEventLoopGroup(numOfThreads.getAsInt());
}
} else {
if (threadFactory != null) {
group = new NioEventLoopGroup(NettyThreadFactory.getDefaultEventLoopThreads(), threadFactory);
} else {
group = new NioEventLoopGroup();
}
}
return group;
}
/**
* Allocator for this connection manager. Used by micronaut-oracle-cloud.
*
* @return The configured allocator
*/
public final ByteBufAllocator alloc() {
return (ByteBufAllocator) bootstrap.config().options().getOrDefault(ChannelOption.ALLOCATOR, ByteBufAllocator.DEFAULT);
}
/**
* For testing.
*
* @return Connected channels in all pools
* @since 4.0.0
*/
@NonNull
@SuppressWarnings("unused")
final List<Channel> getChannels() {
List<Channel> channels = new ArrayList<>();
for (Pool pool : pools.values()) {
pool.forEachConnection(c -> channels.add(((Pool.ConnectionHolder) c).channel));
}
return channels;
}
/**
* For testing.
*
* @return Number of running requests
* @since 4.0.0
*/
@SuppressWarnings("unused")
final int liveRequestCount() {
AtomicInteger count = new AtomicInteger();
for (Pool pool : pools.values()) {
pool.forEachConnection(c -> {
if (c instanceof Pool.Http1ConnectionHolder holder) {
if (holder.hasLiveRequests()) {
count.incrementAndGet();
}
} else {
count.addAndGet(((Pool.Http2ConnectionHolder) c).liveRequests.get());
}
});
}
return count.get();
}
/**
* @see DefaultHttpClient#start()
*/
public final void start() {
// only need to start new group if it's managed by us
if (shutdownGroup) {
group = createEventLoopGroup(configuration, threadFactory);
initBootstrap(); // rebuild bootstrap with new group
}
}
private void initBootstrap() {
this.bootstrap = new Bootstrap()
.group(group)
.channelFactory(socketChannelFactory)
.option(ChannelOption.SO_KEEPALIVE, true);
if (httpVersion.isHttp3()) {
this.udpBootstrap = new Bootstrap()
.group(group)
.channelFactory(udpChannelFactory);
}
Optional<Duration> connectTimeout = configuration.getConnectTimeout();
connectTimeout.ifPresent(duration -> bootstrap.option(
ChannelOption.CONNECT_TIMEOUT_MILLIS,
(int) duration.toMillis()
));
for (Map.Entry<String, Object> entry : configuration.getChannelOptions().entrySet()) {
Object v = entry.getValue();
if (v != null) {
String channelOption = entry.getKey();
bootstrap.option(ChannelOption.valueOf(channelOption), v);
}
}
}
/**
* @see DefaultHttpClient#stop()
*/
public final void shutdown() {
for (Pool pool : pools.values()) {
pool.shutdown();
}
if (shutdownGroup) {
Duration shutdownTimeout = configuration.getShutdownTimeout()
.orElse(Duration.ofMillis(HttpClientConfiguration.DEFAULT_SHUTDOWN_TIMEOUT_MILLISECONDS));
Duration shutdownQuietPeriod = configuration.getShutdownQuietPeriod()
.orElse(Duration.ofMillis(HttpClientConfiguration.DEFAULT_SHUTDOWN_QUIET_PERIOD_MILLISECONDS));
Future<?> future = group.shutdownGracefully(
shutdownQuietPeriod.toMillis(),
shutdownTimeout.toMillis(),
TimeUnit.MILLISECONDS
);
try {
future.await(shutdownTimeout.toMillis());
} catch (InterruptedException e) {
// ignore
Thread.currentThread().interrupt();
}
}
ReferenceCountUtil.release(sslContext);
ReferenceCountUtil.release(websocketSslContext);
sslContext = null;
websocketSslContext = null;
}
/**
* @see DefaultHttpClient#isRunning()
*
* @return Whether this connection manager is still running and can serve requests
*/
public final boolean isRunning() {
return !group.isShutdown();
}
/**
* Use the bootstrap to connect to the given host. Also does some proxy setup. This method is
* not final: The test suite overrides it to return embedded channels instead.
*
* @param requestKey The host to connect to
* @param channelInitializer The initializer to use
* @return Future that terminates when the TCP connection is established.
*/
ChannelFuture doConnect(DefaultHttpClient.RequestKey requestKey, ChannelInitializer<?> channelInitializer) {
String host = requestKey.getHost();
int port = requestKey.getPort();
Bootstrap localBootstrap = bootstrap.clone();
Proxy proxy = configuration.resolveProxy(requestKey.isSecure(), host, port);
if (proxy.type() != Proxy.Type.DIRECT) {
localBootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
}
localBootstrap.handler(channelInitializer);
return localBootstrap.connect(host, port);
}
/**
* Builds an {@link SslContext} for the given URI if necessary.
*
* @return The {@link SslContext} instance
*/
@Nullable
private SslContext buildSslContext(DefaultHttpClient.RequestKey requestKey) {
final SslContext sslCtx;
if (requestKey.isSecure()) {
sslCtx = sslContext;
//Allow https requests to be sent if SSL is disabled but a proxy is present
if (sslCtx == null && !configuration.getProxyAddress().isPresent()) {
throw decorate(new HttpClientException("Cannot send HTTPS request. SSL is disabled"));
}
} else {
sslCtx = null;
}
return sslCtx;
}
/**
* Get a connection for non-websocket http client methods.
*
* @param requestKey The remote to connect to
* @param blockHint Optional information about what threads are blocked for this connection request
* @return A mono that will complete once the channel is ready for transmission
*/
public final Mono<PoolHandle> connect(DefaultHttpClient.RequestKey requestKey, @Nullable BlockHint blockHint) {
return pools.computeIfAbsent(requestKey, Pool::new).acquire(blockHint);
}
/**
* Builds an {@link SslContext} for the given WebSocket URI if necessary.
*
* @return The {@link SslContext} instance
*/
@Nullable
private SslContext buildWebsocketSslContext(DefaultHttpClient.RequestKey requestKey) {
SslContext sslCtx = websocketSslContext;
if (requestKey.isSecure()) {
if (configuration.getSslConfiguration().isEnabled()) {
if (sslCtx == null) {
synchronized (this) {
sslCtx = websocketSslContext;
if (sslCtx == null) {
sslCtx = nettyClientSslBuilder.build(configuration.getSslConfiguration(), HttpVersionSelection.forWebsocket());
websocketSslContext = sslCtx;
}
}
}
} else if (configuration.getProxyAddress().isEmpty()){
throw decorate(new HttpClientException("Cannot send WSS request. SSL is disabled"));
}
}
return sslCtx;
}
/**
* Connect to a remote websocket. The given {@link ChannelHandler} is added to the pipeline
* when the handshakes complete.
*
* @param requestKey The remote to connect to
* @param handler The websocket message handler
* @return A mono that will complete when the handshakes complete
*/
final Mono<?> connectForWebsocket(DefaultHttpClient.RequestKey requestKey, ChannelHandler handler) {
Sinks.Empty<Object> initial = new CancellableMonoSink<>(null);
ChannelFuture connectFuture = doConnect(requestKey, new ChannelInitializer<Channel>() {
@Override
protected void initChannel(@NonNull Channel ch) {
addLogHandler(ch);
SslContext sslContext = buildWebsocketSslContext(requestKey);
if (sslContext != null) {
ch.pipeline().addLast(configureSslHandler(sslContext.newHandler(ch.alloc(), requestKey.getHost(), requestKey.getPort())));
}
ch.pipeline()
.addLast(ChannelPipelineCustomizer.HANDLER_HTTP_CLIENT_CODEC, new HttpClientCodec())
.addLast(ChannelPipelineCustomizer.HANDLER_HTTP_AGGREGATOR, new HttpObjectAggregator(configuration.getMaxContentLength()));
Optional<Duration> readIdleTime = configuration.getReadIdleTimeout();
if (readIdleTime.isPresent()) {
Duration duration = readIdleTime.get();
if (!duration.isNegative()) {
ch.pipeline()
.addLast(ChannelPipelineCustomizer.HANDLER_IDLE_STATE, new IdleStateHandler(duration.toMillis(), duration.toMillis(), duration.toMillis(), TimeUnit.MILLISECONDS));
}
}
try {
if (configuration.getWebSocketCompressionConfiguration() != null && configuration.getWebSocketCompressionConfiguration().isEnabled()) {
ch.pipeline().addLast(WebSocketClientCompressionHandler.INSTANCE);
}
ch.pipeline().addLast(ChannelPipelineCustomizer.HANDLER_MICRONAUT_WEBSOCKET_CLIENT, handler);
clientCustomizer.specializeForChannel(ch, NettyClientCustomizer.ChannelRole.CONNECTION).onInitialPipelineBuilt();
if (initial.tryEmitEmpty().isSuccess()) {
return;
}
} catch (Throwable e) {
initial.tryEmitError(new WebSocketSessionException("Error opening WebSocket client session: " + e.getMessage(), e));
}
// failed
ch.close();
}
});
withPropagation(connectFuture, future -> {
if (!future.isSuccess()) {
initial.tryEmitError(future.cause());
}
});
return initial.asMono();
}
private void configureProxy(ChannelPipeline pipeline, boolean secure, String host, int port) {
Proxy proxy = configuration.resolveProxy(secure, host, port);
if (Proxy.NO_PROXY.equals(proxy)) {
return;
}
Proxy.Type proxyType = proxy.type();
SocketAddress proxyAddress = proxy.address();
String username = configuration.getProxyUsername().orElse(null);
String password = configuration.getProxyPassword().orElse(null);
if (proxyAddress instanceof InetSocketAddress isa) {
if (isa.isUnresolved()) {
proxyAddress = new InetSocketAddress(isa.getHostString(), isa.getPort());
}
}
if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
switch (proxyType) {
case HTTP:
pipeline.addLast(ChannelPipelineCustomizer.HANDLER_HTTP_PROXY, new HttpProxyHandler(proxyAddress, username, password));
break;
case SOCKS:
pipeline.addLast(ChannelPipelineCustomizer.HANDLER_SOCKS_5_PROXY, new Socks5ProxyHandler(proxyAddress, username, password));
break;
default:
// no-op
}
} else {
switch (proxyType) {
case HTTP:
pipeline.addLast(ChannelPipelineCustomizer.HANDLER_HTTP_PROXY, new HttpProxyHandler(proxyAddress));
break;
case SOCKS:
pipeline.addLast(ChannelPipelineCustomizer.HANDLER_SOCKS_5_PROXY, new Socks5ProxyHandler(proxyAddress));
break;
default:
// no-op
}
}
}
final <V, C extends Future<V>> void withPropagation(Future<? extends V> channelFuture, GenericFutureListener<C> listener) {
PropagatedContext propagatedContext = PropagatedContext.getOrEmpty();
channelFuture.addListener(f -> {
try (PropagatedContext.Scope ignored = propagatedContext.propagate()) {
//noinspection unchecked
listener.operationComplete((C) f);
}
});
}
private Http2FrameCodec makeFrameCodec() {
Http2FrameCodecBuilder builder = Http2FrameCodecBuilder.forClient();
configuration.getLogLevel().ifPresent(logLevel -> {
try {
final io.netty.handler.logging.LogLevel nettyLevel =
io.netty.handler.logging.LogLevel.valueOf(logLevel.name());
builder.frameLogger(new Http2FrameLogger(nettyLevel, DefaultHttpClient.class));
} catch (IllegalArgumentException e) {
throw decorate(new HttpClientException("Unsupported log level: " + logLevel));
}
});
return builder.build();
}
private SslHandler configureSslHandler(SslHandler sslHandler) {
sslHandler.setHandshakeTimeoutMillis(configuration.getSslConfiguration().getHandshakeTimeout().toMillis());
SSLEngine engine = sslHandler.engine();
SSLParameters params = engine.getSSLParameters();
params.setEndpointIdentificationAlgorithm("HTTPS");
engine.setSSLParameters(params);
return sslHandler;
}
/**
* Initializer for HTTP1.1, called either in plaintext mode, or after ALPN in TLS.
*
* @param ch The plaintext channel
*/
private void initHttp1(Channel ch) {
addLogHandler(ch);
ch.pipeline()
.addLast(ChannelPipelineCustomizer.HANDLER_HTTP_CLIENT_CODEC, new HttpClientCodec())
.addLast(ChannelPipelineCustomizer.HANDLER_HTTP_DECODER, new HttpContentDecompressor());
}
private void addLogHandler(Channel ch) {
configuration.getLogLevel().ifPresent(logLevel -> {
try {
final io.netty.handler.logging.LogLevel nettyLevel =
io.netty.handler.logging.LogLevel.valueOf(logLevel.name());
ch.pipeline().addLast(new LoggingHandler(DefaultHttpClient.class, nettyLevel));
} catch (IllegalArgumentException e) {
throw decorate(new HttpClientException("Unsupported log level: " + logLevel));
}
});
}
/**
* Initializer for HTTP2 multiplexing, called either in h2c mode, or after ALPN in TLS. The
* channel should already contain a {@link #makeFrameCodec() frame codec} that does the HTTP2
* parsing, this method adds the handlers that do multiplexing, error handling, etc.
*
* @param pool The pool to add the connection to once the handshake is done
* @param ch The plaintext channel
* @param connectionCustomizer Customizer for the connection
*/
private void initHttp2(Pool pool, Channel ch, NettyClientCustomizer connectionCustomizer) {
Http2MultiplexHandler multiplexHandler = new Http2MultiplexHandler(new ChannelInitializer<Http2StreamChannel>() {
@Override
protected void initChannel(@NonNull Http2StreamChannel ch) throws Exception {
log.warn("Server opened HTTP2 stream {}, closing immediately", ch.stream().id());
ch.close();
}
}, new ChannelInitializer<Http2StreamChannel>() {
@Override
protected void initChannel(@NonNull Http2StreamChannel ch) throws Exception {
// discard any response data for the upgrade request
ch.close();
}
});
Pool.Http2ConnectionHolder connectionHolder = pool.new Http2ConnectionHolder(ch, connectionCustomizer);
ch.pipeline().addLast(multiplexHandler);
ch.pipeline().addLast(ChannelPipelineCustomizer.HANDLER_HTTP2_SETTINGS, new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(@NonNull ChannelHandlerContext ctx, @NonNull Object msg) throws Exception {
if (msg instanceof Http2SettingsFrame) {
ctx.pipeline().remove(ChannelPipelineCustomizer.HANDLER_HTTP2_SETTINGS);
ctx.pipeline().remove(ChannelPipelineCustomizer.HANDLER_INITIAL_ERROR);
connectionHolder.init();
return;
} else {
log.warn("Premature frame: {}", msg.getClass());
}
super.channelRead(ctx, msg);
}
});
// stream frames should be handled by the multiplexer
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
ctx.read();
}
@Override
public void channelRead(@NonNull ChannelHandlerContext ctx, @NonNull Object msg) throws Exception {
if (msg instanceof Http2SettingsAckFrame) {
// this is fine
return;
}
if (msg instanceof Http2GoAwayFrame goAway) {
connectionHolder.windDownConnection();
if (log.isDebugEnabled()) {
// include the debug content, but at most 64 bytes for safety
byte[] debug = new byte[Math.min(64, goAway.content().readableBytes())];
goAway.content().readBytes(debug);
log.debug("Server sent GOAWAY frame. errorCode={} base64(content)={}", goAway.errorCode(), Base64.getEncoder().encodeToString(debug));
}
goAway.release();
return;
}
log.warn("Unexpected message on HTTP2 connection channel: {}", msg);
ReferenceCountUtil.release(msg);
ctx.read();
}
});
}
private <E extends HttpClientException> E decorate(E exc) {
return HttpClientExceptionUtils.populateServiceId(exc, informationalServiceId, configuration);
}
/**
* Initializer for TLS channels. After ALPN we will proceed either with
* {@link #initHttp1(Channel)} or {@link #initHttp2(Pool, Channel, NettyClientCustomizer)}.
*/
private final class AdaptiveAlpnChannelInitializer extends ChannelInitializer<Channel> {
private final Pool pool;
private final SslContext sslContext;
private final String host;
private final int port;
AdaptiveAlpnChannelInitializer(Pool pool,
SslContext sslContext,
String host,
int port) {
this.pool = pool;
this.sslContext = sslContext;
this.host = host;
this.port = port;
}
/**
* @param ch The channel
*/
@Override
protected void initChannel(@NonNull Channel ch) {
NettyClientCustomizer channelCustomizer = clientCustomizer.specializeForChannel(ch, NettyClientCustomizer.ChannelRole.CONNECTION);
configureProxy(ch.pipeline(), true, host, port);
ch.pipeline()
.addLast(ChannelPipelineCustomizer.HANDLER_SSL, configureSslHandler(sslContext.newHandler(ch.alloc(), host, port)))
.addLast(
ChannelPipelineCustomizer.HANDLER_HTTP2_PROTOCOL_NEGOTIATOR,
// if the server doesn't do ALPN, fall back to HTTP 1
new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
ctx.pipeline().addLast(ChannelPipelineCustomizer.HANDLER_HTTP2_CONNECTION, makeFrameCodec());
initHttp2(pool, ctx.channel(), channelCustomizer);
} else if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
initHttp1(ctx.channel());
pool.new Http1ConnectionHolder(ch, channelCustomizer).init(false);
ctx.pipeline().remove(ChannelPipelineCustomizer.HANDLER_INITIAL_ERROR);
} else {
ctx.close();
throw decorate(new HttpClientException("Unknown Protocol: " + protocol));
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof SslHandshakeCompletionEvent event) {
if (!event.isSuccess()) {
InitialConnectionErrorHandler.setFailureCause(ctx.channel(), event.cause());
}
}
super.userEventTriggered(ctx, evt);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// let the HANDLER_INITIAL_ERROR handle the failure
if (cause instanceof DecoderException && cause.getCause() instanceof SSLException) {
// unwrap DecoderException
cause = cause.getCause();
}
ctx.fireExceptionCaught(cause);
}
})
.addLast(ChannelPipelineCustomizer.HANDLER_INITIAL_ERROR, pool.initialErrorHandler);
channelCustomizer.onInitialPipelineBuilt();
}
}
/**
* Initializer for H2C connections. Will proceed with
* {@link #initHttp2(Pool, Channel, NettyClientCustomizer)} when the upgrade is done.
*/
private final class Http2UpgradeInitializer extends ChannelInitializer<Channel> {
private final Pool pool;
Http2UpgradeInitializer(Pool pool) {
this.pool = pool;
}
@Override
protected void initChannel(@NonNull Channel ch) throws Exception {
NettyClientCustomizer connectionCustomizer = clientCustomizer.specializeForChannel(ch, NettyClientCustomizer.ChannelRole.CONNECTION);
Http2FrameCodec frameCodec = makeFrameCodec();
HttpClientCodec sourceCodec = new HttpClientCodec();
Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(frameCodec,
new ChannelInitializer<Channel>() {
@Override
protected void initChannel(@NonNull Channel ch) throws Exception {
ch.pipeline().addLast(ChannelPipelineCustomizer.HANDLER_HTTP2_CONNECTION, frameCodec);
initHttp2(pool, ch, connectionCustomizer);
}
});
HttpClientUpgradeHandler upgradeHandler = new HttpClientUpgradeHandler(sourceCodec, upgradeCodec, 65536);
ch.pipeline().addLast(ChannelPipelineCustomizer.HANDLER_HTTP_CLIENT_CODEC, sourceCodec);
ch.pipeline().addLast(upgradeHandler);
ch.pipeline().addLast(ChannelPipelineCustomizer.HANDLER_HTTP2_UPGRADE_REQUEST, new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(@NonNull ChannelHandlerContext ctx) throws Exception {
DefaultFullHttpRequest upgradeRequest =
new DefaultFullHttpRequest(io.netty.handler.codec.http.HttpVersion.HTTP_1_1, HttpMethod.GET, "/", Unpooled.EMPTY_BUFFER);
// Set HOST header as the remote peer may require it.
upgradeRequest.headers().set(HttpHeaderNames.HOST, pool.requestKey.getHost() + ':' + pool.requestKey.getPort());
ctx.writeAndFlush(upgradeRequest);
ctx.pipeline().remove(ChannelPipelineCustomizer.HANDLER_HTTP2_UPGRADE_REQUEST);
// read the upgrade response
ctx.read();
super.channelActive(ctx);
}
});
ch.pipeline().addLast(ChannelPipelineCustomizer.HANDLER_INITIAL_ERROR, pool.initialErrorHandler);
connectionCustomizer.onInitialPipelineBuilt();
}
}
private final class Http3ChannelInitializer extends ChannelOutboundHandlerAdapter {
private final Pool pool;
private final String host;
private final int port;
Http3ChannelInitializer(Pool pool, String host, int port) {
this.pool = pool;
this.host = host;
this.port = port;
}
// delay channel initialization until bind is complete. This is required so that we can see
// the local address
@Override
public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception {
ChannelPromise downstreamPromise = ctx.newPromise();
super.bind(ctx, localAddress, downstreamPromise);
downstreamPromise.addListener(future -> {
if (future.isSuccess()) {
try {
initChannel(promise.channel());
ctx.pipeline().remove(this);
promise.setSuccess();
} catch (Exception e) {
promise.setFailure(e);
}
} else {
promise.setFailure(future.cause());
}
});
}
private void initChannel(Channel ch) {
NettyClientCustomizer channelCustomizer = clientCustomizer.specializeForChannel(ch, NettyClientCustomizer.ChannelRole.CONNECTION);
ch.pipeline()
.addLast(Http3.newQuicClientCodecBuilder()
.sslEngineProvider(c -> ((QuicSslContext) http3SslContext).newEngine(c.alloc(), host, port))
.initialMaxData(10000000)
.initialMaxStreamDataBidirectionalLocal(1000000)
.build())
.addLast(ChannelPipelineCustomizer.HANDLER_INITIAL_ERROR, pool.initialErrorHandler);
channelCustomizer.onInitialPipelineBuilt();
QuicChannel.newBootstrap(ch)
.handler(new ChannelInboundHandlerAdapter() {
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
QuicChannel quicChannel = (QuicChannel) ctx.channel();
ctx.pipeline().addLast(ChannelPipelineCustomizer.HANDLER_HTTP2_CONNECTION, new Http3ClientConnectionHandler(
// control stream handler
new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof Http3SettingsFrame) {
ch.pipeline().remove(ChannelPipelineCustomizer.HANDLER_INITIAL_ERROR);
pool.new Http3ConnectionHolder(ch, quicChannel, channelCustomizer).init();
}
super.channelRead(ctx, msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ch.pipeline().remove(ChannelPipelineCustomizer.HANDLER_INITIAL_ERROR);
ch.close();
pool.onNewConnectionFailure(cause);
}
},
null,
null,
null,
false
));
ctx.pipeline().remove(this);
}
})
.remoteAddress(new InetSocketAddress(this.host, this.port))
.localAddress(ch.localAddress())
.connect()
.addListener((GenericFutureListener<Future<QuicChannel>>) future -> {
if (!future.isSuccess()) {
pool.onNewConnectionFailure(future.cause());
}
});
}
}
/**
* Handle for a pooled connection. One pool handle generally corresponds to one request, and
* once the request and response are done, the handle is {@link #release() released} and a new
* request can claim the same connection.
*/
public abstract static class PoolHandle {
private static final Supplier<ResourceLeakDetector<PoolHandle>> LEAK_DETECTOR = SupplierUtil.memoized(() ->
ResourceLeakDetectorFactory.instance().newResourceLeakDetector(PoolHandle.class));
final boolean http2;
final Channel channel;
boolean released = false;
private final ResourceLeakTracker<PoolHandle> tracker = LEAK_DETECTOR.get().track(this);
private PoolHandle(boolean http2, Channel channel) {
this.http2 = http2;
this.channel = channel;
}
public final Channel channel() {
return channel;
}
public final boolean http2() {
return http2;
}
/**
* Prevent this connection from being reused, e.g. because garbage was written because of
* an error.
*/
public abstract void taint();
/**
* Close this connection or release it back to the pool.
*/
public void release() {
if (released) {
throw new IllegalStateException("Already released");
}
released = true;
if (tracker != null) {
tracker.close(this);
}
}
/**
* Whether this connection may be returned to a connection pool (i.e. should be kept
* keepalive).
*
* @return Whether this connection may be reused
*/
public abstract boolean canReturn();
/**
* Notify any {@link NettyClientCustomizer} that the request pipeline has been built.
*/
public abstract void notifyRequestPipelineBuilt();
}
/**
* This class represents one pool, and matches to exactly one
* {@link io.micronaut.http.client.netty.DefaultHttpClient.RequestKey} (i.e. host, port and
* protocol are the same for one pool).
* <p>
* The superclass {@link PoolResizer} handles pool size management, this class just implements
* the HTTP parts.
*/
private final class Pool extends PoolResizer {
private final DefaultHttpClient.RequestKey requestKey;
/**
* {@link ChannelHandler} that is added to a connection to report failures during
* handshakes. It's removed once the connection is established and processes requests.
*/
private final InitialConnectionErrorHandler initialErrorHandler = new InitialConnectionErrorHandler() {
@Override
protected void onNewConnectionFailure(@Nullable Throwable cause) throws Exception {