-
Notifications
You must be signed in to change notification settings - Fork 241
/
netty.clj
1710 lines (1496 loc) · 62.6 KB
/
netty.clj
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
(ns aleph.netty
(:refer-clojure :exclude [flush])
(:require
[clj-commons.byte-streams :as bs]
[clj-commons.primitive-math :as p]
[clojure.tools.logging :as log]
[manifold.deferred :as d]
[manifold.executor :as e]
[manifold.stream :as s]
[manifold.stream.core :as manifold]
[potemkin :refer [doary doit]])
(:import
(aleph.http AlephChannelInitializer)
(clojure.lang DynamicClassLoader)
(io.netty.bootstrap
Bootstrap
ServerBootstrap)
(io.netty.buffer
ByteBuf
Unpooled)
(io.netty.channel
Channel
ChannelFuture
ChannelHandler
ChannelHandlerContext
ChannelInboundHandler
ChannelInitializer
ChannelOption
ChannelOutboundHandler
ChannelOutboundInvoker
ChannelPipeline
EventLoopGroup
FileRegion)
(io.netty.channel.epoll
Epoll
EpollDatagramChannel
EpollEventLoopGroup
EpollServerSocketChannel
EpollSocketChannel)
(io.netty.channel.group
ChannelGroup
DefaultChannelGroup)
(io.netty.channel.kqueue
KQueue
KQueueDatagramChannel
KQueueEventLoopGroup
KQueueServerSocketChannel
KQueueSocketChannel)
(io.netty.channel.nio NioEventLoopGroup)
(io.netty.channel.socket
ChannelInputShutdownReadComplete
ServerSocketChannel)
(io.netty.channel.socket.nio
NioDatagramChannel
NioServerSocketChannel
NioSocketChannel)
(io.netty.handler.codec
CharSequenceValueConverter
DecoderException)
(io.netty.handler.codec.http2 Http2StreamChannel)
(io.netty.handler.logging
LogLevel
LoggingHandler)
(io.netty.handler.ssl
ApplicationProtocolConfig
ClientAuth
SslContext
SslContextBuilder
SslHandler
SslProvider)
(io.netty.handler.ssl.util
InsecureTrustManagerFactory
SelfSignedCertificate)
(io.netty.incubator.channel.uring
IOUring
IOUringDatagramChannel
IOUringEventLoopGroup
IOUringServerSocketChannel
IOUringSocketChannel)
(io.netty.resolver
AddressResolverGroup
NoopAddressResolverGroup
ResolvedAddressTypes)
(io.netty.resolver.dns
DnsAddressResolverGroup
DnsNameResolverBuilder
DnsServerAddressStreamProvider
SequentialDnsServerAddressStreamProvider
SingletonDnsServerAddressStreamProvider)
(io.netty.util
Attribute
AttributeKey
ResourceLeakDetector
ResourceLeakDetector$Level)
(io.netty.util.concurrent
FastThreadLocalThread
Future
GenericFutureListener
GlobalEventExecutor)
(io.netty.util.internal
StringUtil
SystemPropertyUtil)
(io.netty.util.internal.logging
InternalLoggerFactory
JdkLoggerFactory
Log4J2LoggerFactory
Log4JLoggerFactory
Slf4JLoggerFactory)
(java.io
File
IOException
InputStream)
(java.net
InetSocketAddress
SocketAddress
URI)
(java.nio ByteBuffer)
(java.security PrivateKey)
(java.security.cert X509Certificate)
(java.util.concurrent
CancellationException
ConcurrentHashMap
ScheduledFuture
ThreadFactory
TimeUnit)
(java.util.concurrent.atomic
AtomicLong)
(javax.net.ssl
SSLHandshakeException
TrustManager
TrustManagerFactory)))
(def ^:no-doc ^CharSequenceValueConverter char-seq-val-converter CharSequenceValueConverter/INSTANCE)
;;;
(definline release
"Decreases the reference count by 1 and deallocates this object if the reference count reaches at 0."
[x]
`(io.netty.util.ReferenceCountUtil/release ~x))
(definline acquire
"Increases the reference count by 1."
[x]
`(io.netty.util.ReferenceCountUtil/retain ~x))
(defn ^:no-doc leak-detector-level! [level]
(ResourceLeakDetector/setLevel
(case level
:disabled ResourceLeakDetector$Level/DISABLED
:simple ResourceLeakDetector$Level/SIMPLE
:advanced ResourceLeakDetector$Level/ADVANCED
:paranoid ResourceLeakDetector$Level/PARANOID)))
(defn set-logger!
"Changes the default logger factory.
The parameter can be either `:log4j`, `:log4j2`, `:slf4j` or `:jdk`."
[logger]
(InternalLoggerFactory/setDefaultFactory
(case logger
:log4j Log4JLoggerFactory/INSTANCE
:log4j2 Log4J2LoggerFactory/INSTANCE
:slf4j Slf4JLoggerFactory/INSTANCE
:jdk JdkLoggerFactory/INSTANCE)))
;;;
(defn ^:no-doc channel-server-name [^Channel ch]
(some-> ch ^InetSocketAddress (.localAddress) .getHostName))
(defn ^:no-doc channel-server-port [^Channel ch]
(some-> ch ^InetSocketAddress (.localAddress) .getPort))
(defn ^:no-doc channel-remote-address [^Channel ch]
(some-> ch ^InetSocketAddress (.remoteAddress) .getAddress .getHostAddress))
;;; Defaults defined here since they are not publically exposed by Netty
(def ^:const ^:no-doc default-shutdown-timeout
"Default timeout in seconds to wait for graceful shutdown complete"
15)
(def ^:const ^:no-doc byte-array-class (Class/forName "[B"))
#_
(defn ^:no-doc buf->array [^ByteBuf buf]
(let [dst (ByteBuffer/allocate (.readableBytes buf))]
(doary [^ByteBuffer buf (.nioBuffers buf)]
(.put dst buf))
(.array dst)))
(defn ^:no-doc buf->array [^ByteBuf buf]
(if (.hasArray buf)
(-> buf
(.array)
(java.util.Arrays/copyOfRange (.readerIndex buf) (.writerIndex buf)))
(let [dst (ByteBuffer/allocate (.readableBytes buf))]
(doary [^ByteBuffer buf (.nioBuffers buf)]
(.put dst buf))
(.array dst))))
(defn ^:no-doc release-buf->array [^ByteBuf buf]
(try
(buf->array buf)
(finally
(release buf))))
(defn ^:no-doc bufs->array [bufs]
(let [bufs' (mapcat #(.nioBuffers ^ByteBuf %) bufs)
dst (ByteBuffer/allocate
(loop [cnt 0, s bufs']
(if (empty? s)
cnt
(recur (p/+ cnt (.remaining ^ByteBuffer (first s))) (rest s)))))]
(doit [^ByteBuffer buf bufs']
(.put dst buf))
(.array dst)))
(bs/def-conversion ^{:cost 1} [ByteBuf byte-array-class]
[buf options]
(let [ary (buf->array buf)]
(release buf)
ary))
(bs/def-conversion ^{:cost 0} [ByteBuffer ByteBuf]
[buf options]
(Unpooled/wrappedBuffer buf))
(declare ^:no-doc allocate)
(let [charset (java.nio.charset.Charset/forName "UTF-8")]
(defn append-to-buf!
"Appends `x` to an existing `io.netty.buffer.ByteBuf`."
[^ByteBuf buf x]
(cond
(instance? byte-array-class x)
(.writeBytes buf ^bytes x)
(instance? String x)
(.writeBytes buf (.getBytes ^String x charset))
(instance? ByteBuf x)
(let [b (.writeBytes buf ^ByteBuf x)]
(release x)
b)
:else
(.writeBytes buf (bs/to-byte-buffer x))))
(defn ^ByteBuf to-byte-buf
"Converts `x` into a `io.netty.buffer.ByteBuf`."
([x]
(cond
(nil? x)
Unpooled/EMPTY_BUFFER
(instance? byte-array-class x)
(Unpooled/copiedBuffer ^bytes x)
(instance? String x)
(-> ^String x (.getBytes charset) ByteBuffer/wrap Unpooled/wrappedBuffer)
(instance? ByteBuffer x)
(Unpooled/wrappedBuffer ^ByteBuffer x)
(instance? ByteBuf x)
x
:else
(bs/convert x ByteBuf)))
([ch x]
;; todo(kachayev): do we really need to reallocate in case
;; we already have an instance of ByteBuf here?
(if (nil? x)
Unpooled/EMPTY_BUFFER
(doto (allocate ch)
(append-to-buf! x))))))
(defn to-byte-buf-stream
"Converts `x` into a manifold stream of `io.netty.ByteBuf` of `chunk-size`."
[x chunk-size]
(->> (bs/convert x (bs/stream-of ByteBuf) {:chunk-size chunk-size})
(s/onto nil)))
(defn ^:no-doc ensure-dynamic-classloader
"Ensure the context class loader has a valid loader chain to
prevent `ClassNotFoundException`.
https://github.com/clj-commons/aleph/issues/603."
[]
(let [thread (Thread/currentThread)
context-class-loader (.getContextClassLoader thread)
compiler-class-loader (.getClassLoader clojure.lang.Compiler)]
(when-not (instance? DynamicClassLoader context-class-loader)
(.setContextClassLoader
thread
(DynamicClassLoader. (or context-class-loader
compiler-class-loader))))))
(defn- operation-complete [^Future f d]
(cond
(.isSuccess f)
(d/success! d (.getNow f))
(.isCancelled f)
(d/error! d (CancellationException. "future is cancelled."))
(some? (.cause f))
(d/error! d (.cause f))
:else
(d/error! d (IllegalStateException. "future in unknown state"))))
(defn ^:no-doc wrap-future
[^Future f]
(when f
(let [d (d/deferred nil)]
(if (.isDone f)
(operation-complete f d)
(.addListener f
(reify GenericFutureListener
(operationComplete [_ _]
(ensure-dynamic-classloader)
(operation-complete f d)))))
d)))
(defn ^:no-doc allocate [x]
(if (instance? Channel x)
(-> ^Channel x .alloc .ioBuffer)
(-> ^ChannelHandlerContext x .alloc .ioBuffer)))
(defn ^:no-doc write [x msg]
(if (instance? Channel x)
(.write ^Channel x msg (.voidPromise ^Channel x))
(.write ^ChannelHandlerContext x msg (.voidPromise ^ChannelHandlerContext x)))
nil)
(defn ^:no-doc write-and-flush
[x msg]
(if (instance? Channel x)
(.writeAndFlush ^Channel x msg)
(.writeAndFlush ^ChannelHandlerContext x msg)))
(defn ^:no-doc flush [x]
(if (instance? Channel x)
(.flush ^Channel x)
(.flush ^ChannelHandlerContext x)))
(defn ^:no-doc close
[^ChannelOutboundInvoker x]
(.close x))
(defn ^:no-doc channel
^Channel [x]
(if (instance? Channel x)
x
(.channel ^ChannelHandlerContext x)))
(defn ^:no-doc ^ChannelGroup make-channel-group
"Create a channel group which can be used to perform channel operations on
several channels at once."
[]
(DefaultChannelGroup. GlobalEventExecutor/INSTANCE))
(defmacro ^:no-doc safe-execute
"Executes the body on the event-loop (an executor service) associated with the Netty channel.
Executes immediately if current thread is in the event loop. Otherwise, returns a deferred
that will hold the result once done."
[ch & body]
`(let [f# (fn [] ~@body)
event-loop# (-> ~ch aleph.netty/channel .eventLoop)]
(if (.inEventLoop event-loop#)
(f#)
(let [d# (d/deferred)]
(.execute event-loop#
(fn []
(try
(d/success! d# (f#))
(catch Throwable e#
(d/error! d# e#)))))
d#))))
(defn ^:no-doc put!
"Netty-aware put! that can apply backpressure to Netty channels if necessary"
[^Channel ch s msg]
(let [d (s/put! s msg)]
(d/success-error-unrealized d
val (if val
true
(do
(release msg)
(.close ch)
false))
err (do
(release msg)
(.close ch)
false)
(do
;; enable backpressure
(-> ch .config (.setAutoRead false))
(-> d
(d/finally'
(fn []
;; disable backpressure
(-> ch .config (.setAutoRead true))))
(d/chain'
(fn [result]
(when-not result
(release msg)
(.close ch)))))
d))))
;;;
(defn ^:no-doc attribute [s]
(AttributeKey/valueOf (name s)))
(defn ^:no-doc get-attribute [ch attr]
(-> ch channel ^Attribute (.attr attr) .get))
(defn ^:no-doc set-attribute [ch attr val]
(-> ch channel ^Attribute (.attr attr) (.set val)))
;;;
(def ^:no-doc ^ConcurrentHashMap channel-inbound-counter (ConcurrentHashMap.))
(def ^:no-doc ^ConcurrentHashMap channel-outbound-counter (ConcurrentHashMap.))
(def ^:no-doc ^ConcurrentHashMap channel-inbound-throughput (ConcurrentHashMap.))
(def ^:no-doc ^ConcurrentHashMap channel-outbound-throughput (ConcurrentHashMap.))
(defn- ^:no-doc connection-stats [^Channel ch inbound?]
(merge
{:local-address (str (.localAddress ch))
:remote-address (str (.remoteAddress ch))
:writable? (.isWritable ch)
:readable? (-> ch .config .isAutoRead)
:closed? (not (.isActive ch))}
(let [^ConcurrentHashMap throughput (if inbound?
channel-inbound-throughput
channel-outbound-throughput)]
(when-let [^AtomicLong throughput (.get throughput ch)]
{:throughput (.get throughput)}))))
(def ^:no-doc sink-close-marker ::sink-close)
(manifold/def-sink ChannelSink
[coerce-fn
downstream?
^Channel ch
additional-description]
(close [this]
(when downstream?
(close ch))
(.markClosed this)
true)
(description [_]
(let [ch (channel ch)]
(merge
{:type "netty"
:closed? (not (.isActive ch))
:sink? true
:connection (assoc (connection-stats ch false)
:direction :outbound)}
(additional-description))))
(isSynchronous [_]
false)
(put [this msg blocking?]
(if (s/closed? this)
(if blocking?
false
(d/success-deferred false))
(let [msg (try
(coerce-fn msg)
(catch Exception e
(log/error e
(str "cannot coerce "
(.getName (class msg))
" into binary representation"))
(close ch)))
d (cond
(nil? msg)
(d/success-deferred true)
(identical? sink-close-marker msg)
(do
(.markClosed this)
(d/success-deferred false))
:else
(let [^ChannelFuture f (write-and-flush ch msg)]
(-> f
wrap-future
(d/chain' (fn [_] true))
(d/catch' IOException (fn [_] false)))))]
(if blocking?
@d
d))))
(put [this msg blocking? timeout timeout-value]
(.put this msg blocking?)))
(defn ^:no-doc sink
([ch]
(sink ch true identity (fn [])))
([ch downstream? coerce-fn]
(sink ch downstream? coerce-fn (fn [])))
([ch downstream? coerce-fn additional-description]
(let [sink (->ChannelSink
coerce-fn
downstream?
ch
additional-description)]
(d/chain'
(wrap-future (.closeFuture (channel ch)))
(fn [_] (s/close! sink)))
(doto sink (reset-meta! {:aleph/channel ch})))))
(defn ^:no-doc source
[^Channel ch]
(let [src (s/stream*
{:description
(fn [m]
(assoc m
:type "netty"
:direction :inbound
:connection (assoc (connection-stats ch true)
:direction :inbound)))})]
(doto src (reset-meta! {:aleph/channel ch}))))
(defn ^:no-doc buffered-source
"A buffered Manifold stream with the originating Channel attached to the
stream's metadata"
[^Channel ch metric capacity]
(let [src (s/buffered-stream
metric
capacity
(fn [m]
(assoc m
:type "netty"
:connection (assoc (connection-stats ch true)
:direction :inbound))))]
(doto src (reset-meta! {:aleph/channel ch}))))
;;;
(defmacro ^:no-doc channel-handler
"Mimics the ChannelDuplexHandler in providing simple defaults or passing along all events"
[& {:as handlers}]
`(reify
ChannelHandler
ChannelInboundHandler
ChannelOutboundHandler
(handlerAdded
~@(or (:handler-added handlers) `([_# _#])))
(handlerRemoved
~@(or (:handler-removed handlers) `([_# _#])))
(exceptionCaught
~@(or (:exception-caught handlers)
`([_# ctx# cause#]
(.fireExceptionCaught ctx# cause#))))
(channelRegistered
~@(or (:channel-registered handlers)
`([_# ctx#]
(.fireChannelRegistered ctx#))))
(channelUnregistered
~@(or (:channel-unregistered handlers)
`([_# ctx#]
(.fireChannelUnregistered ctx#))))
(channelActive
~@(or (:channel-active handlers)
`([_# ctx#]
(.fireChannelActive ctx#))))
(channelInactive
~@(or (:channel-inactive handlers)
`([_# ctx#]
(.fireChannelInactive ctx#))))
(channelRead
~@(or (:channel-read handlers)
`([_# ctx# msg#]
(.fireChannelRead ctx# msg#))))
(channelReadComplete
~@(or (:channel-read-complete handlers)
`([_# ctx#]
(.fireChannelReadComplete ctx#))))
(userEventTriggered
~@(or (:user-event-triggered handlers)
`([_# ctx# evt#]
(.fireUserEventTriggered ctx# evt#))))
(channelWritabilityChanged
~@(or (:channel-writability-changed handlers)
`([_# ctx#]
(.fireChannelWritabilityChanged ctx#))))
(bind
~@(or (:bind handlers)
`([_# ctx# local-address# promise#]
(.bind ctx# local-address# promise#))))
(connect
~@(or (:connect handlers)
`([_# ctx# remote-address# local-address# promise#]
(.connect ctx# remote-address# local-address# promise#))))
(disconnect
~@(or (:disconnect handlers)
`([_# ctx# promise#]
(.disconnect ctx# promise#))))
(close
~@(or (:close handlers)
`([_# ctx# promise#]
(.close ctx# promise#))))
(read
~@(or (:read handlers)
`([_# ctx#]
(.read ctx#))))
(write
~@(or (:write handlers)
`([_# ctx# msg# promise#]
(.write ctx# msg# promise#))))
(flush
~@(or (:flush handlers)
`([_# ctx#]
(.flush ctx#))))))
(defmacro ^:no-doc channel-inbound-handler
"Effectively a macro version of ChannelInboundHandlerAdapter.
Default behavior is to pass along all events. Default handler
added/removed behavior is NOOP."
[& {:as handlers}]
`(reify
ChannelHandler
ChannelInboundHandler
(handlerAdded
~@(or (:handler-added handlers) `([_# _#])))
(handlerRemoved
~@(or (:handler-removed handlers) `([_# _#])))
(exceptionCaught
~@(or (:exception-caught handlers)
`([_# ctx# cause#]
(.fireExceptionCaught ctx# ^Throwable cause#))))
(channelRegistered
~@(or (:channel-registered handlers)
`([_# ctx#]
(.fireChannelRegistered ctx#))))
(channelUnregistered
~@(or (:channel-unregistered handlers)
`([_# ctx#]
(.fireChannelUnregistered ctx#))))
(channelActive
~@(or (:channel-active handlers)
`([_# ctx#]
(.fireChannelActive ctx#))))
(channelInactive
~@(or (:channel-inactive handlers)
`([_# ctx#]
(.fireChannelInactive ctx#))))
(channelRead
~@(or (:channel-read handlers)
`([_# ctx# msg#]
(.fireChannelRead ctx# msg#))))
(channelReadComplete
~@(or (:channel-read-complete handlers)
`([_# ctx#]
(.fireChannelReadComplete ctx#))))
(userEventTriggered
~@(or (:user-event-triggered handlers)
`([_# ctx# evt#]
(.fireUserEventTriggered ctx# evt#))))
(channelWritabilityChanged
~@(or (:channel-writability-changed handlers)
`([_# ctx#]
(.fireChannelWritabilityChanged ctx#))))))
(defmacro ^:no-doc channel-outbound-handler
"Effectively a macro version of ChannelOutboundHandlerAdapter.
Default behavior is to forward calls to the context. Default handler
added/removed behavior is NOOP."
[& {:as handlers}]
`(reify
ChannelHandler
ChannelOutboundHandler
(handlerAdded
~@(or (:handler-added handlers) `([_# _#])))
(handlerRemoved
~@(or (:handler-removed handlers) `([_# _#])))
(exceptionCaught
~@(or (:exception-caught handlers)
`([_# ctx# cause#]
(.fireExceptionCaught ctx# cause#))))
(bind
~@(or (:bind handlers)
`([_# ctx# local-address# promise#]
(.bind ctx# local-address# promise#))))
(connect
~@(or (:connect handlers)
`([_# ctx# remote-address# local-address# promise#]
(.connect ctx# remote-address# local-address# promise#))))
(disconnect
~@(or (:disconnect handlers)
`([_# ctx# promise#]
(.disconnect ctx# promise#))))
(close
~@(or (:close handlers)
`([_# ctx# promise#]
(.close ctx# promise#))))
(read
~@(or (:read handlers)
`([_# ctx#]
(.read ctx#))))
(write
~@(or (:write handlers)
`([_# ctx# msg# promise#]
(.write ctx# msg# promise#))))
(flush
~@(or (:flush handlers)
`([_# ctx#]
(.flush ctx#))))))
(defn ^:no-doc ^ChannelHandler bandwidth-tracker [^Channel ch]
(let [inbound-counter (AtomicLong. 0)
outbound-counter (AtomicLong. 0)
inbound-throughput (AtomicLong. 0)
outbound-throughput (AtomicLong. 0)
^ScheduledFuture future
(.scheduleAtFixedRate (-> ch .eventLoop .parent)
(fn []
(.set inbound-throughput (.getAndSet inbound-counter 0))
(.set outbound-throughput (.getAndSet outbound-counter 0)))
1000
1000
TimeUnit/MILLISECONDS)]
(.put channel-inbound-counter ch inbound-counter)
(.put channel-outbound-counter ch outbound-counter)
(.put channel-inbound-throughput ch inbound-throughput)
(.put channel-outbound-throughput ch outbound-throughput)
(channel-handler
:channel-inactive
([_ ctx]
(.cancel future true)
(.remove channel-inbound-counter ch)
(.remove channel-outbound-counter ch)
(.remove channel-inbound-throughput ch)
(.remove channel-outbound-throughput ch)
(.fireChannelInactive ctx))
:channel-read
([_ ctx msg]
(.addAndGet inbound-counter
(if (instance? FileRegion msg)
(.count ^FileRegion msg)
(.readableBytes ^ByteBuf msg)))
(.fireChannelRead ctx msg))
:write
([_ ctx msg promise]
(.addAndGet outbound-counter
(if (instance? FileRegion msg)
(.count ^FileRegion msg)
(.readableBytes ^ByteBuf msg)))
(.write ctx msg promise)))))
(defn ^:no-doc channel-tracking-handler
"Yields an inbound handler, ready to be added to a pipeline,
which keeps track of requests in a provided channel group.
The channel-group can be created via `make-channel-group`."
[^ChannelGroup group]
(channel-inbound-handler
:channel-active
([_ ctx]
(.add group (channel ctx))
(.fireChannelActive ctx))))
(defn pipeline-initializer
"Returns a ChannelInitializer which builds the pipeline.
`pipeline-builder` is a 1-arity fn that takes a ChannelPipeline and
configures it."
^ChannelInitializer
[pipeline-builder]
(AlephChannelInitializer. #(pipeline-builder (.pipeline ^Channel %))))
(defn remove-if-present
"Convenience function to remove a handler from a netty pipeline."
[^ChannelPipeline pipeline ^Class handler]
(when (some? (.get pipeline handler))
(.remove pipeline handler))
pipeline)
(defn ^:no-doc instrument!
[stream]
(if-let [^Channel ch (->> stream meta :aleph/channel)]
(do
(safe-execute ch
(let [pipeline (.pipeline ch)]
(when (and
(.isActive ch)
(nil? (.get pipeline "bandwidth-tracker")))
(.addFirst pipeline "bandwidth-tracker" (bandwidth-tracker ch)))))
true)
false))
(defn ^:no-doc pause-handler
"Returns a handler that stores all messages until removed from the pipeline."
[]
(let [msgs (atom [])
fire-buffered-msgs (fn [^ChannelHandlerContext ctx]
(log/debug "pause-handler - firing buffered msgs")
(run! #(.fireChannelRead ctx %) @msgs)
(.fireChannelReadComplete ctx))]
(channel-inbound-handler
{:channel-read
([_ ctx msg]
(log/trace "pause-handler buffering msg" msg)
(swap! msgs conj msg))
:handler-removed
([_ ctx]
(fire-buffered-msgs ctx))
:channel-inactive
([_ ctx]
(fire-buffered-msgs ctx)
(.fireChannelInactive ctx))
:user-event-triggered
([_ ctx evt]
(when (instance? ChannelInputShutdownReadComplete evt)
(fire-buffered-msgs ctx))
(.fireUserEventTriggered ctx evt))})))
(defn ^:no-doc coerce-log-level
"Returns a netty LogLevel. Accepts either a keyword or a LogLevel."
[level]
(if (instance? LogLevel level)
level
(let [netty-level (case level
:trace LogLevel/TRACE
:debug LogLevel/DEBUG
:info LogLevel/INFO
:warn LogLevel/WARN
:error LogLevel/ERROR
nil)]
(when (nil? netty-level)
(throw (IllegalArgumentException.
(str "unknown log level given: " level))))
netty-level)))
(defn ^:no-doc activity-logger
([level]
(LoggingHandler. ^LogLevel (coerce-log-level level)))
([^String name level]
(LoggingHandler. name ^LogLevel (coerce-log-level level))))
;;;
(defn ^:no-doc coerce-ssl-provider ^SslProvider [provider]
(case provider
:jdk SslProvider/JDK
:openssl SslProvider/OPENSSL
:openssl-refcnt SslProvider/OPENSSL_REFCNT))
(let [cert-array-class (class (into-array X509Certificate []))]
(defn- add-ssl-trust-manager! ^SslContextBuilder [^SslContextBuilder builder trust-store]
(cond (instance? File trust-store)
(.trustManager builder ^File trust-store)
(instance? InputStream trust-store)
(.trustManager builder ^InputStream trust-store)
(instance? TrustManager trust-store)
(.trustManager builder ^TrustManager trust-store)
(instance? TrustManagerFactory trust-store)
(.trustManager builder ^TrustManagerFactory trust-store)
(instance? cert-array-class trust-store)
(.trustManager builder ^"[Ljava.security.cert.X509Certificate;" trust-store)
(sequential? trust-store)
(let [^"[Ljava.security.cert.X509Certificate;" trust-store' (into-array X509Certificate trust-store)]
(.trustManager builder trust-store'))
:else
(throw
(IllegalArgumentException.
"ssl context arguments invalid"))))
(defn ssl-client-context
"Creates a new client SSL context.
Keyword arguments are:
Param key | Description
| --- | ---
| `private-key` | a `java.io.File`, `java.io.InputStream`, or `java.security.PrivateKey` containing the client-side private key.
| `certificate-chain` | a `java.io.File`, `java.io.InputStream`, sequence of `java.security.cert.X509Certificate`, or array of `java.security.cert.X509Certificate` containing the client's certificate chain.
| `private-key-password` | a string, the private key's password (optional).
| `trust-store` | a `java.io.File`, `java.io.InputStream`, array of `java.security.cert.X509Certificate`, `javax.net.ssl.TrustManager`, or a `javax.net.ssl.TrustManagerFactory` to initialize the context's trust manager.
| `ssl-provider` | `SslContext` implementation to use, one of `:jdk`, `:openssl` or `:openssl-refcnt`. Note, that when using OpenSSL-based implementations, the library should be installed and linked properly.
| `ciphers` | a sequence of strings, the cipher suites to enable, in the order of preference.
| `protocols` | a sequence of strings, the TLS protocol versions to enable.
| `session-cache-size` | the size of the cache used for storing SSL session objects.
| `session-timeout` | the timeout for the cached SSL session objects, in seconds.
| `application-protocol-config` | an `ApplicationProtocolConfig` instance to configure ALPN.
Note that if specified, the types of `private-key` and `certificate-chain` must be \"compatible\": either both input streams, both files, or a private key and an array of certificates."
(^SslContext
[]
(ssl-client-context {}))
(^SslContext
[{:keys [private-key
^String private-key-password
certificate-chain
trust-store
ssl-provider
^Iterable ciphers
protocols
^long session-cache-size
^long session-timeout
^ApplicationProtocolConfig application-protocol-config]}]
(let [^SslContextBuilder builder (SslContextBuilder/forClient)]
(when (or private-key certificate-chain)
(cond
(and (instance? File private-key)
(instance? File certificate-chain))
(.keyManager builder
^File certificate-chain
^File private-key
private-key-password)
(and (instance? InputStream private-key)
(instance? InputStream certificate-chain))
(.keyManager builder
^InputStream certificate-chain
^InputStream private-key
private-key-password)
(and (instance? PrivateKey private-key)
(instance? cert-array-class certificate-chain))
(.keyManager builder
^PrivateKey private-key
private-key-password
^"[Ljava.security.cert.X509Certificate;" certificate-chain)
(and (instance? PrivateKey private-key)
(sequential? certificate-chain))
(let [^"[Ljava.security.cert.X509Certificate;" certificate-chain' (into-array X509Certificate certificate-chain)]
(.keyManager builder
^PrivateKey private-key
private-key-password
certificate-chain'))
:else
(throw
(IllegalArgumentException. "ssl context arguments invalid"))))
(cond-> builder
(some? trust-store)
(add-ssl-trust-manager! trust-store)
(some? ssl-provider)
(.sslProvider (coerce-ssl-provider ssl-provider))
(some? ciphers)
(.ciphers ciphers)
(some? protocols)
(.protocols ^"[Ljava.lang.String;" (into-array String protocols))
(some? session-cache-size)
(.sessionCacheSize session-cache-size)
(some? session-timeout)
(.sessionTimeout session-timeout)
(some? application-protocol-config)
(.applicationProtocolConfig application-protocol-config))
(.build builder))))
(defn ssl-server-context
"Creates a new server SSL context.
Keyword arguments are:
Param key | Description
| --- | ---
| `private-key` | a `java.io.File`, `java.io.InputStream`, or `java.security.PrivateKey` containing the server-side private key.
| `certificate-chain` | a `java.io.File`, `java.io.InputStream`, or array of `java.security.cert.X509Certificate` containing the server's certificate chain.
| `private-key-password` | a string, the private key's password (optional).
| `trust-store` | a `java.io.File`, `java.io.InputStream`, sequence of `java.security.cert.X509Certificate`, array of `java.security.cert.X509Certificate`, `javax.net.ssl.TrustManager`, or a `javax.net.ssl.TrustManagerFactory` to initialize the context's trust manager.
| `ssl-provider` | `SslContext` implementation to use, on of `:jdk`, `:openssl` or `:openssl-refcnt`. Note, that when using OpenSSL based implementations, the library should be installed and linked properly.
| `ciphers` | a sequence of strings, the cipher suites to enable, in the order of preference.