-
Notifications
You must be signed in to change notification settings - Fork 628
/
HttpServerConfig.java
1182 lines (1057 loc) · 46 KB
/
HttpServerConfig.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) 2020-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.server;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.haproxy.HAProxyMessageDecoder;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpServerUpgradeHandler;
import io.netty.handler.codec.http.cookie.ServerCookieDecoder;
import io.netty.handler.codec.http.cookie.ServerCookieEncoder;
import io.netty.handler.codec.http2.CleartextHttp2ServerUpgradeHandler;
import io.netty.handler.codec.http2.Http2CodecUtil;
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.Http2MultiplexHandler;
import io.netty.handler.codec.http2.Http2ServerUpgradeCodec;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.codec.http2.Http2StreamFrameToHttpObjectCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.ApplicationProtocolNames;
import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler;
import io.netty.util.AsciiString;
import reactor.core.publisher.Mono;
import reactor.netty.ChannelPipelineConfigurer;
import reactor.netty.Connection;
import reactor.netty.ConnectionObserver;
import reactor.netty.NettyPipeline;
import reactor.netty.ReactorNetty;
import reactor.netty.channel.AbstractChannelMetricsHandler;
import reactor.netty.channel.ChannelMetricsRecorder;
import reactor.netty.channel.ChannelOperations;
import reactor.netty.http.Http2SettingsSpec;
import reactor.netty.http.HttpProtocol;
import reactor.netty.http.HttpResources;
import reactor.netty.http.server.logging.AccessLog;
import reactor.netty.http.server.logging.AccessLogArgProvider;
import reactor.netty.http.server.logging.AccessLogHandlerFactory;
import reactor.netty.resources.LoopResources;
import reactor.netty.tcp.SslProvider;
import reactor.netty.transport.ServerTransportConfig;
import reactor.netty.transport.logging.AdvancedByteBufFormat;
import reactor.util.Logger;
import reactor.util.Loggers;
import reactor.util.annotation.Nullable;
import java.net.SocketAddress;
import java.nio.charset.Charset;
import java.time.Duration;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Supplier;
import static reactor.netty.ReactorNetty.ACCESS_LOG_ENABLED;
import static reactor.netty.ReactorNetty.format;
import static reactor.netty.http.server.HttpServerFormDecoderProvider.DEFAULT_FORM_DECODER_SPEC;
/**
* Encapsulate all necessary configuration for HTTP server transport. The public API is read-only.
*
* @author Stephane Maldini
* @author Violeta Georgieva
* @author Andrey Shlykov
*/
public final class HttpServerConfig extends ServerTransportConfig<HttpServerConfig> {
/**
* Return the configured compression predicate or null.
*
* @return the configured compression predicate or null
*/
@Nullable
public BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate() {
return compressPredicate;
}
/**
* Return the configured {@link ServerCookieDecoder} or the default {@link ServerCookieDecoder#STRICT}.
*
* @return the configured {@link ServerCookieDecoder} or the default {@link ServerCookieDecoder#STRICT}
*/
public ServerCookieDecoder cookieDecoder() {
return cookieDecoder;
}
/**
* Return the configured {@link ServerCookieEncoder} or the default {@link ServerCookieEncoder#STRICT}.
*
* @return the configured {@link ServerCookieEncoder} or the default {@link ServerCookieEncoder#STRICT}
*/
public ServerCookieEncoder cookieEncoder() {
return cookieEncoder;
}
/**
* Return the configured HTTP request decoder options or the default.
*
* @return the configured HTTP request decoder options or the default
*/
public HttpRequestDecoderSpec decoder() {
return decoder;
}
/**
* Return the configured HTTP form decoder or the default.
*
* @return the configured HTTP form decoder or the default
* @since 1.0.11
*/
public HttpServerFormDecoderProvider formDecoderProvider() {
return formDecoderProvider;
}
/**
* Return the HTTP/2 configuration
*
* @return the HTTP/2 configuration
*/
public Http2SettingsSpec http2SettingsSpec() {
return http2Settings;
}
/**
* Return the configured idle timeout for the connection when it is waiting for an HTTP request or null.
*
* @return the configured idle timeout for the connection when it is waiting for an HTTP request or null
*/
@Nullable
public Duration idleTimeout() {
return idleTimeout;
}
/**
* Returns whether that {@link HttpServer} supports the {@code "Forwarded"} and {@code "X-Forwarded-*"}
* HTTP request headers for deriving information about the connection.
*
* @return true if that {@link HttpServer} supports the {@code "Forwarded"} and {@code "X-Forwarded-*"}
* HTTP request headers for deriving information about the connection
*/
public boolean isForwarded() {
return forwardedHeaderHandler != null;
}
/**
* Returns true if that {@link HttpServer} secured via SSL transport
*
* @return true if that {@link HttpServer} secured via SSL transport
*/
public boolean isSecure() {
return sslProvider != null;
}
/**
* The configured maximum number of HTTP/1.1 requests which can be served until the connection is closed by the server.
*
* @return the configured maximum number of HTTP/1.1 requests which can be served until the connection is closed by the server.
* @see HttpServer#maxKeepAliveRequests(int)
* @since 1.0.13
*/
public int maxKeepAliveRequests() {
return maxKeepAliveRequests;
}
/**
* Compression is performed once response size exceeds the minimum compression size in bytes.
*
* @return the minimum compression size in bytes
*/
public int minCompressionSize() {
return minCompressionSize;
}
/**
* Return the HTTP protocol to support. Default is {@link HttpProtocol#HTTP11}.
*
* @return the HTTP protocol to support
*/
public HttpProtocol[] protocols() {
return protocols;
}
/**
* Return the supported type for the {@code "HAProxy proxy protocol"}.
* The default is {@link ProxyProtocolSupportType#OFF}.
*
* @return the supported type for the {@code "HAProxy proxy protocol"}
*/
public ProxyProtocolSupportType proxyProtocolSupportType() {
return proxyProtocolSupportType;
}
/**
* Returns true if that {@link HttpServer} will redirect HTTP to HTTPS by changing
* the scheme only but otherwise leaving the port the same when SSL is enabled.
* This configuration is applicable only for HTTP/1.x.
*
* @return true if that {@link HttpServer} will redirect HTTP to HTTPS by changing
* the scheme only but otherwise leaving the port the same when SSL is enabled.
* This configuration is applicable only for HTTP/1.x.
*/
public boolean redirectHttpToHttps() {
return redirectHttpToHttps;
}
/**
* Returns the current {@link SslProvider} if that {@link HttpServer} secured via SSL
* transport or null.
*
* @return the current {@link SslProvider} if that {@link HttpServer} secured via SSL
* transport or null
*/
@Nullable
public SslProvider sslProvider() {
return sslProvider;
}
/**
* Returns the configured function that receives the actual uri and returns the uri tag value
* that will be used for the metrics with {@link reactor.netty.Metrics#URI} tag
*
* @return the configured function that receives the actual uri and returns the uri tag value
* that will be used for the metrics with {@link reactor.netty.Metrics#URI} tag
*/
@Nullable
public Function<String, String> uriTagValue() {
return uriTagValue;
}
// Protected/Package private write API
boolean accessLogEnabled;
Function<AccessLogArgProvider, AccessLog> accessLog;
BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate;
ServerCookieDecoder cookieDecoder;
ServerCookieEncoder cookieEncoder;
HttpRequestDecoderSpec decoder;
HttpServerFormDecoderProvider formDecoderProvider;
BiFunction<ConnectionInfo, HttpRequest, ConnectionInfo> forwardedHeaderHandler;
Http2SettingsSpec http2Settings;
Duration idleTimeout;
BiFunction<? super Mono<Void>, ? super Connection, ? extends Mono<Void>>
mapHandle;
int maxKeepAliveRequests;
int minCompressionSize;
HttpProtocol[] protocols;
int _protocols;
ProxyProtocolSupportType proxyProtocolSupportType;
boolean redirectHttpToHttps;
SslProvider sslProvider;
Function<String, String> uriTagValue;
HttpServerConfig(Map<ChannelOption<?>, ?> options, Map<ChannelOption<?>, ?> childOptions, Supplier<? extends SocketAddress> localAddress) {
super(options, childOptions, localAddress);
this.cookieDecoder = ServerCookieDecoder.STRICT;
this.cookieEncoder = ServerCookieEncoder.STRICT;
this.decoder = new HttpRequestDecoderSpec();
this.formDecoderProvider = DEFAULT_FORM_DECODER_SPEC;
this.maxKeepAliveRequests = -1;
this.minCompressionSize = -1;
this.protocols = new HttpProtocol[]{HttpProtocol.HTTP11};
this._protocols = h11;
this.proxyProtocolSupportType = ProxyProtocolSupportType.OFF;
this.accessLogEnabled = ACCESS_LOG;
}
HttpServerConfig(HttpServerConfig parent) {
super(parent);
this.accessLogEnabled = parent.accessLogEnabled;
this.accessLog = parent.accessLog;
this.compressPredicate = parent.compressPredicate;
this.cookieDecoder = parent.cookieDecoder;
this.cookieEncoder = parent.cookieEncoder;
this.decoder = parent.decoder;
this.formDecoderProvider = parent.formDecoderProvider;
this.forwardedHeaderHandler = parent.forwardedHeaderHandler;
this.http2Settings = parent.http2Settings;
this.idleTimeout = parent.idleTimeout;
this.mapHandle = parent.mapHandle;
this.maxKeepAliveRequests = parent.maxKeepAliveRequests;
this.minCompressionSize = parent.minCompressionSize;
this.protocols = parent.protocols;
this._protocols = parent._protocols;
this.proxyProtocolSupportType = parent.proxyProtocolSupportType;
this.redirectHttpToHttps = parent.redirectHttpToHttps;
this.sslProvider = parent.sslProvider;
this.uriTagValue = parent.uriTagValue;
}
@Override
protected LoggingHandler defaultLoggingHandler() {
return LOGGING_HANDLER;
}
@Override
protected LoopResources defaultLoopResources() {
return HttpResources.get();
}
@Override
protected ChannelMetricsRecorder defaultMetricsRecorder() {
return MicrometerHttpServerMetricsRecorder.INSTANCE;
}
@Override
protected ChannelPipelineConfigurer defaultOnChannelInit() {
return super.defaultOnChannelInit()
.then(new HttpServerChannelInitializer(this));
}
@Override
protected void loggingHandler(LoggingHandler loggingHandler) {
super.loggingHandler(loggingHandler);
}
@Override
protected void metricsRecorder(@Nullable Supplier<? extends ChannelMetricsRecorder> metricsRecorder) {
super.metricsRecorder(metricsRecorder);
}
void protocols(HttpProtocol... protocols) {
this.protocols = protocols;
int _protocols = 0;
for (HttpProtocol p : protocols) {
if (p == HttpProtocol.HTTP11) {
_protocols |= h11;
}
else if (p == HttpProtocol.H2) {
_protocols |= h2;
}
else if (p == HttpProtocol.H2C) {
_protocols |= h2c;
}
}
this._protocols = _protocols;
}
Http2Settings http2Settings() {
Http2Settings settings = Http2Settings.defaultSettings();
if (http2Settings != null) {
Long headerTableSize = http2Settings.headerTableSize();
if (headerTableSize != null) {
settings.headerTableSize(headerTableSize);
}
Integer initialWindowSize = http2Settings.initialWindowSize();
if (initialWindowSize != null) {
settings.initialWindowSize(initialWindowSize);
}
Long maxConcurrentStreams = http2Settings.maxConcurrentStreams();
if (maxConcurrentStreams != null) {
settings.maxConcurrentStreams(maxConcurrentStreams);
}
Integer maxFrameSize = http2Settings.maxFrameSize();
if (maxFrameSize != null) {
settings.maxFrameSize(maxFrameSize);
}
settings.maxHeaderListSize(http2Settings.maxHeaderListSize());
Boolean pushEnabled = http2Settings.pushEnabled();
if (pushEnabled != null) {
settings.pushEnabled(pushEnabled);
}
}
return settings;
}
static void addStreamHandlers(Channel ch,
boolean accessLogEnabled,
@Nullable Function<AccessLogArgProvider, AccessLog> accessLog,
@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate,
ServerCookieDecoder decoder,
ServerCookieEncoder encoder,
HttpServerFormDecoderProvider formDecoderProvider,
@Nullable BiFunction<ConnectionInfo, HttpRequest, ConnectionInfo> forwardedHeaderHandler,
ConnectionObserver listener,
@Nullable BiFunction<? super Mono<Void>, ? super Connection, ? extends Mono<Void>> mapHandle,
@Nullable ChannelMetricsRecorder metricsRecorder,
int minCompressionSize,
ChannelOperations.OnSetup opsFactory,
@Nullable Function<String, String> uriTagValue) {
ChannelPipeline pipeline = ch.pipeline();
if (accessLogEnabled) {
pipeline.addLast(NettyPipeline.AccessLogHandler, AccessLogHandlerFactory.H2.create(accessLog));
}
pipeline.addLast(NettyPipeline.H2ToHttp11Codec, HTTP2_STREAM_FRAME_TO_HTTP_OBJECT)
.addLast(NettyPipeline.HttpTrafficHandler,
new Http2StreamBridgeServerHandler(compressPredicate, decoder, encoder, formDecoderProvider,
forwardedHeaderHandler, listener, mapHandle));
boolean alwaysCompress = compressPredicate == null && minCompressionSize == 0;
if (alwaysCompress) {
pipeline.addLast(NettyPipeline.CompressionHandler, new SimpleCompressionHandler());
}
ChannelOperations.addReactiveBridge(ch, opsFactory, listener);
if (metricsRecorder != null) {
if (metricsRecorder instanceof HttpServerMetricsRecorder) {
ChannelHandler handler;
Channel parent = ch.parent();
ChannelHandler existingHandler = parent.pipeline().get(NettyPipeline.HttpMetricsHandler);
if (existingHandler != null) {
// This use case can happen only in HTTP/2 clear text connection upgrade
if (metricsRecorder instanceof MicrometerHttpServerMetricsRecorder) {
parent.pipeline().replace(NettyPipeline.HttpMetricsHandler, NettyPipeline.ChannelMetricsHandler,
new H2ChannelMetricsHandler(metricsRecorder));
}
else {
parent.pipeline().remove(NettyPipeline.HttpMetricsHandler);
}
handler = metricsRecorder instanceof ContextAwareHttpServerMetricsRecorder ?
new ContextAwareHttpServerMetricsHandler((ContextAwareHttpServerMetricsHandler) existingHandler) :
new HttpServerMetricsHandler((HttpServerMetricsHandler) existingHandler);
}
else {
handler = metricsRecorder instanceof ContextAwareHttpServerMetricsRecorder ?
new ContextAwareHttpServerMetricsHandler((ContextAwareHttpServerMetricsRecorder) metricsRecorder, uriTagValue) :
new HttpServerMetricsHandler((HttpServerMetricsRecorder) metricsRecorder, uriTagValue);
}
pipeline.addBefore(NettyPipeline.ReactiveBridge, NettyPipeline.HttpMetricsHandler, handler);
}
}
if (log.isDebugEnabled()) {
log.debug(format(ch, "Initialized HTTP/2 stream pipeline {}"), pipeline);
}
}
@Nullable
static BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate(
@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressionPredicate,
int minResponseSize) {
if (minResponseSize <= 0) {
return compressionPredicate;
}
BiPredicate<HttpServerRequest, HttpServerResponse> lengthPredicate =
(req, res) -> {
String length = res.responseHeaders()
.get(HttpHeaderNames.CONTENT_LENGTH);
if (length == null) {
return true;
}
try {
return Long.parseLong(length) >= minResponseSize;
}
catch (NumberFormatException nfe) {
return true;
}
};
if (compressionPredicate != null) {
lengthPredicate = lengthPredicate.and(compressionPredicate);
}
return lengthPredicate;
}
static void configureH2Pipeline(ChannelPipeline p,
boolean accessLogEnabled,
@Nullable Function<AccessLogArgProvider, AccessLog> accessLog,
@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate,
ServerCookieDecoder cookieDecoder,
ServerCookieEncoder cookieEncoder,
HttpServerFormDecoderProvider formDecoderProvider,
@Nullable BiFunction<ConnectionInfo, HttpRequest, ConnectionInfo> forwardedHeaderHandler,
Http2Settings http2Settings,
ConnectionObserver listener,
@Nullable BiFunction<? super Mono<Void>, ? super Connection, ? extends Mono<Void>> mapHandle,
@Nullable ChannelMetricsRecorder metricsRecorder,
int minCompressionSize,
ChannelOperations.OnSetup opsFactory,
@Nullable Function<String, String> uriTagValue,
boolean validate) {
p.remove(NettyPipeline.ReactiveBridge);
Http2FrameCodecBuilder http2FrameCodecBuilder =
Http2FrameCodecBuilder.forServer()
.validateHeaders(validate)
.initialSettings(http2Settings);
if (p.get(NettyPipeline.LoggingHandler) != null) {
http2FrameCodecBuilder.frameLogger(new Http2FrameLogger(LogLevel.DEBUG,
"reactor.netty.http.server.h2"));
}
p.addLast(NettyPipeline.HttpCodec, http2FrameCodecBuilder.build())
.addLast(NettyPipeline.H2MultiplexHandler,
new Http2MultiplexHandler(new H2Codec(accessLogEnabled, accessLog, compressPredicate, cookieDecoder,
cookieEncoder, formDecoderProvider, forwardedHeaderHandler, listener, mapHandle,
metricsRecorder, minCompressionSize, opsFactory, uriTagValue)));
if (metricsRecorder != null) {
if (metricsRecorder instanceof MicrometerHttpServerMetricsRecorder) {
// For sake of performance, we can replace the ChannelMetricsHandler because the MicrometerHttpServerMetricsRecorder
// is interested only in connections metrics .
p.replace(NettyPipeline.ChannelMetricsHandler, NettyPipeline.ChannelMetricsHandler,
new H2ChannelMetricsHandler(metricsRecorder));
}
}
}
static void configureHttp11OrH2CleartextPipeline(ChannelPipeline p,
boolean accessLogEnabled,
@Nullable Function<AccessLogArgProvider, AccessLog> accessLog,
@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate,
ServerCookieDecoder cookieDecoder,
ServerCookieEncoder cookieEncoder,
HttpRequestDecoderSpec decoder,
HttpServerFormDecoderProvider formDecoderProvider,
@Nullable BiFunction<ConnectionInfo, HttpRequest, ConnectionInfo> forwardedHeaderHandler,
Http2Settings http2Settings,
@Nullable Duration idleTimeout,
ConnectionObserver listener,
@Nullable BiFunction<? super Mono<Void>, ? super Connection, ? extends Mono<Void>> mapHandle,
int maxKeepAliveRequests,
@Nullable ChannelMetricsRecorder metricsRecorder,
int minCompressionSize,
ChannelOperations.OnSetup opsFactory,
@Nullable Function<String, String> uriTagValue) {
HttpServerCodec httpServerCodec =
new HttpServerCodec(decoder.maxInitialLineLength(), decoder.maxHeaderSize(),
decoder.maxChunkSize(), decoder.validateHeaders(), decoder.initialBufferSize(),
decoder.allowDuplicateContentLengths());
Http11OrH2CleartextCodec upgrader = new Http11OrH2CleartextCodec(accessLogEnabled, accessLog, compressPredicate,
cookieDecoder, cookieEncoder, p.get(NettyPipeline.LoggingHandler) != null, formDecoderProvider,
forwardedHeaderHandler, http2Settings, listener, mapHandle, metricsRecorder, minCompressionSize, opsFactory,
uriTagValue, decoder.validateHeaders());
ChannelHandler http2ServerHandler = new H2CleartextCodec(upgrader);
CleartextHttp2ServerUpgradeHandler h2cUpgradeHandler = new CleartextHttp2ServerUpgradeHandler(
httpServerCodec,
new HttpServerUpgradeHandler(httpServerCodec, upgrader, decoder.h2cMaxContentLength()),
http2ServerHandler);
p.addBefore(NettyPipeline.ReactiveBridge,
NettyPipeline.H2CUpgradeHandler, h2cUpgradeHandler)
.addBefore(NettyPipeline.ReactiveBridge,
NettyPipeline.HttpTrafficHandler,
new HttpTrafficHandler(compressPredicate, cookieDecoder, cookieEncoder, formDecoderProvider,
forwardedHeaderHandler, idleTimeout, listener, mapHandle, maxKeepAliveRequests));
if (accessLogEnabled) {
p.addBefore(NettyPipeline.HttpTrafficHandler, NettyPipeline.AccessLogHandler, AccessLogHandlerFactory.H1.create(accessLog));
}
boolean alwaysCompress = compressPredicate == null && minCompressionSize == 0;
if (alwaysCompress) {
p.addBefore(NettyPipeline.HttpTrafficHandler, NettyPipeline.CompressionHandler, new SimpleCompressionHandler());
}
if (metricsRecorder != null) {
if (metricsRecorder instanceof HttpServerMetricsRecorder) {
ChannelHandler handler = metricsRecorder instanceof ContextAwareHttpServerMetricsRecorder ?
new ContextAwareHttpServerMetricsHandler((ContextAwareHttpServerMetricsRecorder) metricsRecorder, uriTagValue) :
new HttpServerMetricsHandler((HttpServerMetricsRecorder) metricsRecorder, uriTagValue);
p.addAfter(NettyPipeline.HttpTrafficHandler, NettyPipeline.HttpMetricsHandler, handler);
if (metricsRecorder instanceof MicrometerHttpServerMetricsRecorder) {
// For sake of performance, we can remove the ChannelMetricsHandler because the MicrometerHttpServerMetricsRecorder
// does not implement metrics on TCP protocol level.
p.remove(NettyPipeline.ChannelMetricsHandler);
}
}
}
}
static void configureHttp11Pipeline(ChannelPipeline p,
boolean accessLogEnabled,
@Nullable Function<AccessLogArgProvider, AccessLog> accessLog,
@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate,
ServerCookieDecoder cookieDecoder,
ServerCookieEncoder cookieEncoder,
HttpRequestDecoderSpec decoder,
HttpServerFormDecoderProvider formDecoderProvider,
@Nullable BiFunction<ConnectionInfo, HttpRequest, ConnectionInfo> forwardedHeaderHandler,
@Nullable Duration idleTimeout,
ConnectionObserver listener,
@Nullable BiFunction<? super Mono<Void>, ? super Connection, ? extends Mono<Void>> mapHandle,
int maxKeepAliveRequests,
@Nullable ChannelMetricsRecorder metricsRecorder,
int minCompressionSize,
@Nullable Function<String, String> uriTagValue) {
p.addBefore(NettyPipeline.ReactiveBridge,
NettyPipeline.HttpCodec,
new HttpServerCodec(decoder.maxInitialLineLength(), decoder.maxHeaderSize(),
decoder.maxChunkSize(), decoder.validateHeaders(), decoder.initialBufferSize(),
decoder.allowDuplicateContentLengths()))
.addBefore(NettyPipeline.ReactiveBridge,
NettyPipeline.HttpTrafficHandler,
new HttpTrafficHandler(compressPredicate, cookieDecoder, cookieEncoder, formDecoderProvider,
forwardedHeaderHandler, idleTimeout, listener, mapHandle, maxKeepAliveRequests));
if (accessLogEnabled) {
p.addAfter(NettyPipeline.HttpCodec, NettyPipeline.AccessLogHandler, AccessLogHandlerFactory.H1.create(accessLog));
}
boolean alwaysCompress = compressPredicate == null && minCompressionSize == 0;
if (alwaysCompress) {
p.addBefore(NettyPipeline.HttpTrafficHandler, NettyPipeline.CompressionHandler, new SimpleCompressionHandler());
}
if (metricsRecorder != null) {
if (metricsRecorder instanceof HttpServerMetricsRecorder) {
ChannelHandler handler = metricsRecorder instanceof ContextAwareHttpServerMetricsRecorder ?
new ContextAwareHttpServerMetricsHandler((ContextAwareHttpServerMetricsRecorder) metricsRecorder, uriTagValue) :
new HttpServerMetricsHandler((HttpServerMetricsRecorder) metricsRecorder, uriTagValue);
p.addAfter(NettyPipeline.HttpTrafficHandler, NettyPipeline.HttpMetricsHandler, handler);
if (metricsRecorder instanceof MicrometerHttpServerMetricsRecorder) {
// For sake of performance, we can remove the ChannelMetricsHandler because the MicrometerHttpServerMetricsRecorder
// does not implement metrics on TCP protocol level.
p.remove(NettyPipeline.ChannelMetricsHandler);
}
}
}
}
static final boolean ACCESS_LOG = Boolean.parseBoolean(System.getProperty(ACCESS_LOG_ENABLED, "false"));
static final int h2 = 0b010;
static final int h2c = 0b001;
static final int h11 = 0b100;
static final int h11orH2 = h11 | h2;
static final int h11orH2C = h11 | h2c;
static final Http2StreamFrameToHttpObjectCodec HTTP2_STREAM_FRAME_TO_HTTP_OBJECT =
new Http2StreamFrameToHttpObjectCodec(true);
static final Logger log = Loggers.getLogger(HttpServerConfig.class);
static final LoggingHandler LOGGING_HANDLER =
AdvancedByteBufFormat.HEX_DUMP
.toLoggingHandler(HttpServer.class.getName(), LogLevel.DEBUG, Charset.defaultCharset());
/**
* Default value whether the SSL debugging on the server side will be enabled/disabled,
* fallback to SSL debugging disabled
*/
static final boolean SSL_DEBUG = Boolean.parseBoolean(System.getProperty(ReactorNetty.SSL_SERVER_DEBUG, "false"));
static final class H2ChannelMetricsHandler extends AbstractChannelMetricsHandler {
final ChannelMetricsRecorder recorder;
H2ChannelMetricsHandler(ChannelMetricsRecorder recorder) {
super(null, true);
this.recorder = recorder;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ctx.fireChannelRead(msg);
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) {
ctx.fireChannelRegistered();
}
@Override
public ChannelHandler connectMetricsHandler() {
return null;
}
@Override
public ChannelHandler tlsMetricsHandler() {
return null;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.fireExceptionCaught(cause);
}
@Override
public ChannelMetricsRecorder recorder() {
return recorder;
}
@Override
@SuppressWarnings("FutureReturnValueIgnored")
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
//"FutureReturnValueIgnored" this is deliberate
ctx.write(msg, promise);
}
}
static final class H2CleartextCodec extends ChannelHandlerAdapter {
final Http11OrH2CleartextCodec upgrader;
final boolean addHttp2FrameCodec;
final boolean removeMetricsHandler;
/**
* Used when full H2 preface is received
*/
H2CleartextCodec(Http11OrH2CleartextCodec upgrader) {
this(upgrader, true, true);
}
/**
* Used when upgrading from HTTP/1.1 to H2. When an upgrade happens {@link Http2FrameCodec}
* is added by {@link Http2ServerUpgradeCodec}
*/
H2CleartextCodec(Http11OrH2CleartextCodec upgrader, boolean addHttp2FrameCodec, boolean removeMetricsHandler) {
this.upgrader = upgrader;
this.addHttp2FrameCodec = addHttp2FrameCodec;
this.removeMetricsHandler = removeMetricsHandler;
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
ChannelPipeline pipeline = ctx.pipeline();
if (addHttp2FrameCodec) {
pipeline.addAfter(ctx.name(), NettyPipeline.HttpCodec, upgrader.http2FrameCodec);
}
pipeline.addAfter(ctx.pipeline().context(upgrader.http2FrameCodec).name(),
NettyPipeline.H2MultiplexHandler, new Http2MultiplexHandler(upgrader));
pipeline.remove(this);
if (pipeline.get(NettyPipeline.AccessLogHandler) != null) {
pipeline.remove(NettyPipeline.AccessLogHandler);
}
if (pipeline.get(NettyPipeline.CompressionHandler) != null) {
pipeline.remove(NettyPipeline.CompressionHandler);
}
if (removeMetricsHandler && pipeline.get(NettyPipeline.HttpMetricsHandler) != null) {
AbstractHttpServerMetricsHandler handler =
(AbstractHttpServerMetricsHandler) pipeline.get(NettyPipeline.HttpMetricsHandler);
if (handler.recorder() instanceof MicrometerHttpServerMetricsRecorder) {
pipeline.replace(NettyPipeline.HttpMetricsHandler, NettyPipeline.ChannelMetricsHandler,
new H2ChannelMetricsHandler(handler.recorder()));
}
else {
pipeline.remove(NettyPipeline.HttpMetricsHandler);
}
}
pipeline.remove(NettyPipeline.HttpTrafficHandler);
pipeline.remove(NettyPipeline.ReactiveBridge);
}
}
static final class H2Codec extends ChannelInitializer<Channel> {
final boolean accessLogEnabled;
final Function<AccessLogArgProvider, AccessLog> accessLog;
final BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate;
final ServerCookieDecoder cookieDecoder;
final ServerCookieEncoder cookieEncoder;
final HttpServerFormDecoderProvider formDecoderProvider;
final BiFunction<ConnectionInfo, HttpRequest, ConnectionInfo> forwardedHeaderHandler;
final ConnectionObserver listener;
final BiFunction<? super Mono<Void>, ? super Connection, ? extends Mono<Void>>
mapHandle;
final ChannelMetricsRecorder metricsRecorder;
final int minCompressionSize;
final ChannelOperations.OnSetup opsFactory;
final Function<String, String> uriTagValue;
H2Codec(
boolean accessLogEnabled,
@Nullable Function<AccessLogArgProvider, AccessLog> accessLog,
@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate,
ServerCookieDecoder decoder,
ServerCookieEncoder encoder,
HttpServerFormDecoderProvider formDecoderProvider,
@Nullable BiFunction<ConnectionInfo, HttpRequest, ConnectionInfo> forwardedHeaderHandler,
ConnectionObserver listener,
@Nullable BiFunction<? super Mono<Void>, ? super Connection, ? extends Mono<Void>> mapHandle,
@Nullable ChannelMetricsRecorder metricsRecorder,
int minCompressionSize,
ChannelOperations.OnSetup opsFactory,
@Nullable Function<String, String> uriTagValue) {
this.accessLogEnabled = accessLogEnabled;
this.accessLog = accessLog;
this.compressPredicate = compressPredicate;
this.cookieDecoder = decoder;
this.cookieEncoder = encoder;
this.formDecoderProvider = formDecoderProvider;
this.forwardedHeaderHandler = forwardedHeaderHandler;
this.listener = listener;
this.mapHandle = mapHandle;
this.metricsRecorder = metricsRecorder;
this.minCompressionSize = minCompressionSize;
this.opsFactory = opsFactory;
this.uriTagValue = uriTagValue;
}
@Override
protected void initChannel(Channel ch) {
ch.pipeline().remove(this);
addStreamHandlers(ch, accessLogEnabled, accessLog, compressPredicate, cookieDecoder, cookieEncoder,
formDecoderProvider, forwardedHeaderHandler, listener, mapHandle, metricsRecorder,
minCompressionSize, opsFactory, uriTagValue);
}
}
static final class Http11OrH2CleartextCodec extends ChannelInitializer<Channel>
implements HttpServerUpgradeHandler.UpgradeCodecFactory {
final boolean accessLogEnabled;
final Function<AccessLogArgProvider, AccessLog> accessLog;
final BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate;
final ServerCookieDecoder cookieDecoder;
final ServerCookieEncoder cookieEncoder;
final HttpServerFormDecoderProvider formDecoderProvider;
final BiFunction<ConnectionInfo, HttpRequest, ConnectionInfo> forwardedHeaderHandler;
final Http2FrameCodec http2FrameCodec;
final ConnectionObserver listener;
final BiFunction<? super Mono<Void>, ? super Connection, ? extends Mono<Void>>
mapHandle;
final ChannelMetricsRecorder metricsRecorder;
final int minCompressionSize;
final ChannelOperations.OnSetup opsFactory;
final Function<String, String> uriTagValue;
Http11OrH2CleartextCodec(
boolean accessLogEnabled,
@Nullable Function<AccessLogArgProvider, AccessLog> accessLog,
@Nullable BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate,
ServerCookieDecoder cookieDecoder,
ServerCookieEncoder cookieEncoder,
boolean debug,
HttpServerFormDecoderProvider formDecoderProvider,
@Nullable BiFunction<ConnectionInfo, HttpRequest, ConnectionInfo> forwardedHeaderHandler,
Http2Settings http2Settings,
ConnectionObserver listener,
@Nullable BiFunction<? super Mono<Void>, ? super Connection, ? extends Mono<Void>> mapHandle,
@Nullable ChannelMetricsRecorder metricsRecorder,
int minCompressionSize,
ChannelOperations.OnSetup opsFactory,
@Nullable Function<String, String> uriTagValue,
boolean validate) {
this.accessLogEnabled = accessLogEnabled;
this.accessLog = accessLog;
this.compressPredicate = compressPredicate;
this.cookieDecoder = cookieDecoder;
this.cookieEncoder = cookieEncoder;
this.formDecoderProvider = formDecoderProvider;
this.forwardedHeaderHandler = forwardedHeaderHandler;
Http2FrameCodecBuilder http2FrameCodecBuilder =
Http2FrameCodecBuilder.forServer()
.validateHeaders(validate)
.initialSettings(http2Settings);
if (debug) {
http2FrameCodecBuilder.frameLogger(new Http2FrameLogger(
LogLevel.DEBUG,
"reactor.netty.http.server.h2"));
}
this.http2FrameCodec = http2FrameCodecBuilder.build();
this.listener = listener;
this.mapHandle = mapHandle;
this.metricsRecorder = metricsRecorder;
this.minCompressionSize = minCompressionSize;
this.opsFactory = opsFactory;
this.uriTagValue = uriTagValue;
}
/**
* Inline channel initializer
*/
@Override
protected void initChannel(Channel ch) {
ch.pipeline().remove(this);
addStreamHandlers(ch, accessLogEnabled, accessLog, compressPredicate, cookieDecoder, cookieEncoder,
formDecoderProvider, forwardedHeaderHandler, listener, mapHandle, metricsRecorder,
minCompressionSize, opsFactory, uriTagValue);
}
@Override
@Nullable
public HttpServerUpgradeHandler.UpgradeCodec newUpgradeCodec(CharSequence protocol) {
if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) {
return new Http2ServerUpgradeCodec(http2FrameCodec, new H2CleartextCodec(this, false, false));
}
else {
return null;
}
}
}
static final class H2OrHttp11Codec extends ApplicationProtocolNegotiationHandler {
final boolean accessLogEnabled;
final Function<AccessLogArgProvider, AccessLog> accessLog;
final BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate;
final ServerCookieDecoder cookieDecoder;
final ServerCookieEncoder cookieEncoder;
final HttpRequestDecoderSpec decoder;
final HttpServerFormDecoderProvider formDecoderProvider;
final BiFunction<ConnectionInfo, HttpRequest, ConnectionInfo> forwardedHeaderHandler;
final Http2Settings http2Settings;
final Duration idleTimeout;
final ConnectionObserver listener;
final BiFunction<? super Mono<Void>, ? super Connection, ? extends Mono<Void>>
mapHandle;
final int maxKeepAliveRequests;
final ChannelMetricsRecorder metricsRecorder;
final int minCompressionSize;
final ChannelOperations.OnSetup opsFactory;
final Function<String, String> uriTagValue;
H2OrHttp11Codec(HttpServerChannelInitializer initializer, ConnectionObserver listener) {
super(ApplicationProtocolNames.HTTP_1_1);
this.accessLogEnabled = initializer.accessLogEnabled;
this.accessLog = initializer.accessLog;
this.compressPredicate = compressPredicate(initializer.compressPredicate, initializer.minCompressionSize);
this.cookieDecoder = initializer.cookieDecoder;
this.cookieEncoder = initializer.cookieEncoder;
this.decoder = initializer.decoder;
this.formDecoderProvider = initializer.formDecoderProvider;
this.forwardedHeaderHandler = initializer.forwardedHeaderHandler;
this.http2Settings = initializer.http2Settings;
this.idleTimeout = initializer.idleTimeout;
this.listener = listener;
this.mapHandle = initializer.mapHandle;
this.maxKeepAliveRequests = initializer.maxKeepAliveRequests;
this.metricsRecorder = initializer.metricsRecorder;
this.minCompressionSize = initializer.minCompressionSize;
this.opsFactory = initializer.opsFactory;
this.uriTagValue = initializer.uriTagValue;
}
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
if (log.isDebugEnabled()) {
log.debug(format(ctx.channel(), "Negotiated application-level protocol [" + protocol + "]"));
}
ChannelPipeline p = ctx.pipeline();
if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
configureH2Pipeline(p, accessLogEnabled, accessLog, compressPredicate, cookieDecoder, cookieEncoder,
formDecoderProvider, forwardedHeaderHandler, http2Settings, listener, mapHandle,
metricsRecorder, minCompressionSize, opsFactory, uriTagValue, decoder.validateHeaders());
return;
}
if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) {
configureHttp11Pipeline(p, accessLogEnabled, accessLog, compressPredicate, cookieDecoder, cookieEncoder,
decoder, formDecoderProvider, forwardedHeaderHandler, idleTimeout, listener, mapHandle,
maxKeepAliveRequests, metricsRecorder, minCompressionSize, uriTagValue);
return;
}
throw new IllegalStateException("unknown protocol: " + protocol);
}
}
static final class HttpServerChannelInitializer implements ChannelPipelineConfigurer {
final boolean accessLogEnabled;
final Function<AccessLogArgProvider, AccessLog> accessLog;
final BiPredicate<HttpServerRequest, HttpServerResponse> compressPredicate;
final ServerCookieDecoder cookieDecoder;
final ServerCookieEncoder cookieEncoder;