/
ChannelPipeline.swift
1998 lines (1748 loc) · 79.6 KB
/
ChannelPipeline.swift
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// A list of `ChannelHandler`s that handle or intercept inbound events and outbound operations of a
/// `Channel`. `ChannelPipeline` implements an advanced form of the Intercepting Filter pattern
/// to give a user full control over how an event is handled and how the `ChannelHandler`s in a pipeline
/// interact with each other.
///
/// # Creation of a pipeline
///
/// Each `Channel` has its own `ChannelPipeline` and it is created automatically when a new `Channel` is created.
///
/// # How an event flows in a pipeline
///
/// The following diagram describes how I/O events are typically processed by `ChannelHandler`s in a `ChannelPipeline`.
/// An I/O event is handled by either a `ChannelInboundHandler` or a `ChannelOutboundHandler`
/// and is forwarded to the next handler in the `ChannelPipeline` by calling the event propagation methods defined in
/// `ChannelHandlerContext`, such as `ChannelHandlerContext.fireChannelRead` and
/// `ChannelHandlerContext.write`.
///
/// ```
/// I/O Request
/// via `Channel` or
/// `ChannelHandlerContext`
/// |
/// +---------------------------------------------------+---------------+
/// | ChannelPipeline | |
/// | TAIL \|/ |
/// | +---------------------+ +-----------+----------+ |
/// | | Inbound Handler N | | Outbound Handler 1 | |
/// | +----------+----------+ +-----------+----------+ |
/// | /|\ | |
/// | | \|/ |
/// | +----------+----------+ +-----------+----------+ |
/// | | Inbound Handler N-1 | | Outbound Handler 2 | |
/// | +----------+----------+ +-----------+----------+ |
/// | /|\ . |
/// | . . |
/// | ChannelHandlerContext.fireIN_EVT() ChannelHandlerContext.OUT_EVT()|
/// | [ method call] [method call] |
/// | . . |
/// | . \|/ |
/// | +----------+----------+ +-----------+----------+ |
/// | | Inbound Handler 2 | | Outbound Handler M-1 | |
/// | +----------+----------+ +-----------+----------+ |
/// | /|\ | |
/// | | \|/ |
/// | +----------+----------+ +-----------+----------+ |
/// | | Inbound Handler 1 | | Outbound Handler M | |
/// | +----------+----------+ +-----------+----------+ |
/// | /|\ HEAD | |
/// +---------------+-----------------------------------+---------------+
/// | \|/
/// +---------------+-----------------------------------+---------------+
/// | | | |
/// | [ Socket.read ] [ Socket.write ] |
/// | |
/// | SwiftNIO Internal I/O Threads (Transport Implementation) |
/// +-------------------------------------------------------------------+
/// ```
///
/// An inbound event is handled by the inbound handlers in the head-to-tail direction as shown on the left side of the
/// diagram. An inbound handler usually handles the inbound data generated by the I/O thread on the bottom of the
/// diagram. The inbound data is often read from a remote peer via the actual input operation such as
/// `Socket.read`. If an inbound event goes beyond the tail inbound handler, it is discarded
/// silently, or logged if it needs your attention.
///
/// An outbound event is handled by the outbound handlers in the tail-to-head direction as shown on the right side of the
/// diagram. An outbound handler usually generates or transforms the outbound traffic such as write requests.
/// If an outbound event goes beyond the head outbound handler, it is handled by an I/O thread associated with the
/// `Channel`. The I/O thread often performs the actual output operation such as `Socket.write`.
///
///
/// For example, let us assume that we created the following pipeline:
///
/// ```
/// ChannelPipeline p = ...
/// let future = p.add(name: "1", handler: InboundHandlerA()).flatMap {
/// p.add(name: "2", handler: InboundHandlerB())
/// }.flatMap {
/// p.add(name: "3", handler: OutboundHandlerA())
/// }.flatMap {
/// p.add(name: "4", handler: OutboundHandlerB())
/// }.flatMap {
/// p.add(name: "5", handler: InboundOutboundHandlerX())
/// }
/// // Handle the future as well ....
/// ```
///
/// In the example above, a class whose name starts with `Inbound` is an inbound handler.
/// A class whose name starts with `Outbound` is an outbound handler.
///
/// In the given example configuration, the handler evaluation order is 1, 2, 3, 4, 5 when an event goes inbound.
/// When an event goes outbound, the order is 5, 4, 3, 2, 1. On top of this principle, `ChannelPipeline` skips
/// the evaluation of certain handlers to shorten the stack depth:
///
/// - 3 and 4 don't implement `ChannelInboundHandler`, and therefore the actual evaluation order of an inbound event will be: 1, 2, and 5.
/// - 1 and 2 don't implement `ChannelOutboundHandler`, and therefore the actual evaluation order of a outbound event will be: 5, 4, and 3.
/// - If 5 implements both `ChannelInboundHandler` and `ChannelOutboundHandler`, the evaluation order of an inbound and a outbound event could be 125 and 543 respectively.
///
/// - Note: Handlers may choose not to propagate messages down the pipeline immediately. For example a handler may need to wait
/// for additional data before sending a protocol event to the next handler in the pipeline. Due to this you can't assume that later handlers
/// in the pipeline will receive the same number of events as were sent, or that events of different types will arrive in the same order.
/// For example - a user event could overtake a data event if a handler is aggregating data events before propagating but immediately
/// propagating user events.
///
/// # Forwarding an event to the next handler
///
/// As you might noticed in the diagram above, a handler has to invoke the event propagation methods in
/// `ChannelHandlerContext` to forward an event to its next handler.
/// Those methods include:
///
/// - Inbound event propagation methods defined in `ChannelInboundInvoker`
/// - Outbound event propagation methods defined in `ChannelOutboundInvoker`.
///
/// # Building a pipeline
///
/// A user is supposed to have one or more `ChannelHandler`s in a `ChannelPipeline` to receive I/O events (e.g. read) and
/// to request I/O operations (e.g. write and close). For example, a typical server will have the following handlers
/// in each channel's pipeline, but your mileage may vary depending on the complexity and characteristics of the
/// protocol and business logic:
///
/// - Protocol Decoder - translates binary data (e.g. `ByteBuffer`) into a struct / class
/// - Protocol Encoder - translates a struct / class into binary data (e.g. `ByteBuffer`)
/// - Business Logic Handler - performs the actual business logic (e.g. database access)
///
/// # Thread safety
///
/// A `ChannelHandler` can be added or removed at any time because a `ChannelPipeline` is thread safe.
public final class ChannelPipeline: ChannelInvoker {
private var head: Optional<ChannelHandlerContext>
private var tail: Optional<ChannelHandlerContext>
private var idx: Int = 0
internal private(set) var destroyed: Bool = false
/// The `EventLoop` that is used by the underlying `Channel`.
public let eventLoop: EventLoop
/// The `Channel` that this `ChannelPipeline` belongs to.
///
/// - note: This will be nil after the channel has closed
private var _channel: Optional<Channel>
/// The `Channel` that this `ChannelPipeline` belongs to.
internal var channel: Channel {
self.eventLoop.assertInEventLoop()
assert(self._channel != nil || self.destroyed)
return self._channel ?? DeadChannel(pipeline: self)
}
/// Add a `ChannelHandler` to the `ChannelPipeline`.
///
/// - parameters:
/// - name: the name to use for the `ChannelHandler` when it's added. If none is specified it will generate a name.
/// - handler: the `ChannelHandler` to add
/// - position: The position in the `ChannelPipeline` to add `handler`. Defaults to `.last`.
/// - returns: the `EventLoopFuture` which will be notified once the `ChannelHandler` was added.
public func addHandler(_ handler: ChannelHandler,
name: String? = nil,
position: ChannelPipeline.Position = .last) -> EventLoopFuture<Void> {
let future: EventLoopFuture<Void>
if self.eventLoop.inEventLoop {
future = self.eventLoop.makeCompletedFuture(self.addHandlerSync(handler, name: name, position: position))
} else {
future = self.eventLoop.submit {
try self.addHandlerSync(handler, name: name, position: position).get()
}
}
return future
}
/// Synchronously add a `ChannelHandler` to the `ChannelPipeline`.
///
/// May only be called from on the event loop.
///
/// - parameters:
/// - handler: the `ChannelHandler` to add
/// - name: the name to use for the `ChannelHandler` when it's added. If none is specified a name will be generated.
/// - position: The position in the `ChannelPipeline` to add `handler`. Defaults to `.last`.
/// - returns: the result of adding this handler - either success or failure with an error code if this could not be completed.
fileprivate func addHandlerSync(_ handler: ChannelHandler,
name: String? = nil,
position: ChannelPipeline.Position = .last) -> Result<Void, Error> {
self.eventLoop.assertInEventLoop()
if self.destroyed {
return .failure(ChannelError.ioOnClosedChannel)
}
switch position {
case .first:
return self.add0(name: name,
handler: handler,
relativeContext: head!,
operation: self.add0(context:after:))
case .last:
return self.add0(name: name,
handler: handler,
relativeContext: tail!,
operation: self.add0(context:before:))
case .before(let beforeHandler):
return self.add0(name: name,
handler: handler,
relativeHandler: beforeHandler,
operation: self.add0(context:before:))
case .after(let afterHandler):
return self.add0(name: name,
handler: handler,
relativeHandler: afterHandler,
operation: self.add0(context:after:))
}
}
/// Synchronously add a `ChannelHandler` to the pipeline, relative to another `ChannelHandler`,
/// where the insertion is done by a specific operation.
///
/// May only be called from on the event loop.
///
/// This will search the pipeline for `relativeHandler` and, if it cannot find it, will fail
/// `promise` with `ChannelPipelineError.notFound`.
///
/// - parameters:
/// - name: The name to use for the `ChannelHandler` when its added. If none is specified, a name will be
/// automatically generated.
/// - handler: The `ChannelHandler` to add.
/// - relativeHandler: The `ChannelHandler` already in the `ChannelPipeline` that `handler` will be
/// inserted relative to.
/// - operation: A callback that will insert `handler` relative to `relativeHandler`.
/// - returns: the result of adding this handler - either success or failure with an error code if this could not be completed.
private func add0(name: String?,
handler: ChannelHandler,
relativeHandler: ChannelHandler,
operation: (ChannelHandlerContext, ChannelHandlerContext) -> Void) -> Result<Void, Error> {
self.eventLoop.assertInEventLoop()
if self.destroyed {
return .failure(ChannelError.ioOnClosedChannel)
}
guard let context = self.contextForPredicate0({ $0.handler === relativeHandler }) else {
return .failure(ChannelPipelineError.notFound)
}
return self.add0(name: name, handler: handler, relativeContext: context, operation: operation)
}
/// Synchronously add a `ChannelHandler` to the pipeline, relative to a `ChannelHandlerContext`,
/// where the insertion is done by a specific operation.
///
/// May only be called from on the event loop.
///
/// This method is more efficient than the one that takes a `relativeHandler` as it does not need to
/// search the pipeline for the insertion point. It should be used whenever possible.
///
/// - parameters:
/// - name: The name to use for the `ChannelHandler` when its added. If none is specified, a name will be
/// automatically generated.
/// - handler: The `ChannelHandler` to add.
/// - relativeContext: The `ChannelHandlerContext` already in the `ChannelPipeline` that `handler` will be
/// inserted relative to.
/// - operation: A callback that will insert `handler` relative to `relativeHandler`.
/// - returns: the result of adding this handler - either success or failure with an error code if this could not be completed.
private func add0(name: String?,
handler: ChannelHandler,
relativeContext: ChannelHandlerContext,
operation: (ChannelHandlerContext, ChannelHandlerContext) -> Void) -> Result<Void, Error> {
self.eventLoop.assertInEventLoop()
if self.destroyed {
return .failure(ChannelError.ioOnClosedChannel)
}
let context = ChannelHandlerContext(name: name ?? nextName(), handler: handler, pipeline: self)
operation(context, relativeContext)
context.invokeHandlerAdded()
return .success(())
}
/// Synchronously add a single new `ChannelHandlerContext` after one that currently exists in the
/// pipeline.
///
/// Must be called from within the event loop thread, as it synchronously manipulates the
/// `ChannelHandlerContext`s on the `ChannelPipeline`.
///
/// - parameters:
/// - new: The `ChannelHandlerContext` to add to the pipeline.
/// - existing: The `ChannelHandlerContext` that `new` will be added after.
private func add0(context new: ChannelHandlerContext, after existing: ChannelHandlerContext) {
self.eventLoop.assertInEventLoop()
let next = existing.next
new.prev = existing
new.next = next
existing.next = new
next?.prev = new
}
/// Synchronously add a single new `ChannelHandlerContext` before one that currently exists in the
/// pipeline.
///
/// Must be called from within the event loop thread, as it synchronously manipulates the
/// `ChannelHandlerContext`s on the `ChannelPipeline`.
///
/// - parameters:
/// - new: The `ChannelHandlerContext` to add to the pipeline.
/// - existing: The `ChannelHandlerContext` that `new` will be added before.
private func add0(context new: ChannelHandlerContext, before existing: ChannelHandlerContext) {
self.eventLoop.assertInEventLoop()
let prev = existing.prev
new.prev = prev
new.next = existing
existing.prev = new
prev?.next = new
}
/// Remove a `ChannelHandler` from the `ChannelPipeline`.
///
/// - parameters:
/// - handler: the `ChannelHandler` to remove.
/// - returns: the `EventLoopFuture` which will be notified once the `ChannelHandler` was removed.
public func removeHandler(_ handler: RemovableChannelHandler) -> EventLoopFuture<Void> {
let promise = self.eventLoop.makePromise(of: Void.self)
self.removeHandler(handler, promise: promise)
return promise.futureResult
}
/// Remove a `ChannelHandler` from the `ChannelPipeline`.
///
/// - parameters:
/// - name: the name that was used to add the `ChannelHandler` to the `ChannelPipeline` before.
/// - returns: the `EventLoopFuture` which will be notified once the `ChannelHandler` was removed.
public func removeHandler(name: String) -> EventLoopFuture<Void> {
let promise = self.eventLoop.makePromise(of: Void.self)
self.removeHandler(name: name, promise: promise)
return promise.futureResult
}
/// Remove a `ChannelHandler` from the `ChannelPipeline`.
///
/// - parameters:
/// - context: the `ChannelHandlerContext` that belongs to `ChannelHandler` that should be removed.
/// - returns: the `EventLoopFuture` which will be notified once the `ChannelHandler` was removed.
public func removeHandler(context: ChannelHandlerContext) -> EventLoopFuture<Void> {
let promise = self.eventLoop.makePromise(of: Void.self)
self.removeHandler(context: context, promise: promise)
return promise.futureResult
}
/// Remove a `ChannelHandler` from the `ChannelPipeline`.
///
/// - parameters:
/// - handler: the `ChannelHandler` to remove.
/// - promise: An `EventLoopPromise` that will complete when the `ChannelHandler` is removed.
public func removeHandler(_ handler: RemovableChannelHandler, promise: EventLoopPromise<Void>?) {
func removeHandler0() {
switch self.contextSync(handler: handler) {
case .success(let context):
self.removeHandler(context: context, promise: promise)
case .failure(let error):
promise?.fail(error)
}
}
if self.eventLoop.inEventLoop {
removeHandler0()
} else {
self.eventLoop.execute {
removeHandler0()
}
}
}
/// Remove a `ChannelHandler` from the `ChannelPipeline`.
///
/// - parameters:
/// - name: the name that was used to add the `ChannelHandler` to the `ChannelPipeline` before.
/// - promise: An `EventLoopPromise` that will complete when the `ChannelHandler` is removed.
public func removeHandler(name: String, promise: EventLoopPromise<Void>?) {
func removeHandler0() {
switch self.contextSync(name: name) {
case .success(let context):
self.removeHandler(context: context, promise: promise)
case .failure(let error):
promise?.fail(error)
}
}
if self.eventLoop.inEventLoop {
removeHandler0()
} else {
self.eventLoop.execute {
removeHandler0()
}
}
}
/// Remove a `ChannelHandler` from the `ChannelPipeline`.
///
/// - parameters:
/// - context: the `ChannelHandlerContext` that belongs to `ChannelHandler` that should be removed.
/// - promise: An `EventLoopPromise` that will complete when the `ChannelHandler` is removed.
public func removeHandler(context: ChannelHandlerContext, promise: EventLoopPromise<Void>?) {
guard context.handler is RemovableChannelHandler else {
promise?.fail(ChannelError.unremovableHandler)
return
}
func removeHandler0() {
context.startUserTriggeredRemoval(promise: promise)
}
if self.eventLoop.inEventLoop {
removeHandler0()
} else {
self.eventLoop.execute {
removeHandler0()
}
}
}
/// Returns the `ChannelHandlerContext` that belongs to a `ChannelHandler`.
///
/// - parameters:
/// - handler: the `ChannelHandler` for which the `ChannelHandlerContext` should be returned
/// - returns: the `EventLoopFuture` which will be notified once the the operation completes.
public func context(handler: ChannelHandler) -> EventLoopFuture<ChannelHandlerContext> {
let promise = self.eventLoop.makePromise(of: ChannelHandlerContext.self)
if self.eventLoop.inEventLoop {
promise.completeWith(self.contextSync(handler: handler))
} else {
self.eventLoop.execute {
promise.completeWith(self.contextSync(handler: handler))
}
}
return promise.futureResult
}
/// Synchronously returns the `ChannelHandlerContext` that belongs to a `ChannelHandler`.
///
/// - Important: This must be called on the `EventLoop`.
/// - parameters:
/// - handler: the `ChannelHandler` for which the `ChannelHandlerContext` should be returned
/// - returns: the `ChannelHandlerContext` that belongs to the `ChannelHandler`, if one exists.
fileprivate func contextSync(handler: ChannelHandler) -> Result<ChannelHandlerContext, Error> {
return self._contextSync({ $0.handler === handler })
}
/// Returns the `ChannelHandlerContext` that belongs to a `ChannelHandler`.
///
/// - parameters:
/// - name: the name that was used to add the `ChannelHandler` to the `ChannelPipeline` before.
/// - returns: the `EventLoopFuture` which will be notified once the the operation completes.
public func context(name: String) -> EventLoopFuture<ChannelHandlerContext> {
let promise = self.eventLoop.makePromise(of: ChannelHandlerContext.self)
if self.eventLoop.inEventLoop {
promise.completeWith(self.contextSync(name: name))
} else {
self.eventLoop.execute {
promise.completeWith(self.contextSync(name: name))
}
}
return promise.futureResult
}
/// Synchronously finds and returns the `ChannelHandlerContext` that belongs to the
/// `ChannelHandler` with the given name.
///
/// - Important: This must be called on the `EventLoop`.
/// - Parameter name: The name of the `ChannelHandler` to find.
/// - Returns: the `ChannelHandlerContext` that belongs to the `ChannelHandler`, if one exists.
fileprivate func contextSync(name: String) -> Result<ChannelHandlerContext, Error> {
return self._contextSync({ $0.name == name })
}
/// Returns the `ChannelHandlerContext` that belongs to a `ChannelHandler` of the given type.
///
/// If multiple channel handlers of the same type are present in the pipeline, returns the context
/// belonging to the first such handler.
///
/// - parameters:
/// - handlerType: The type of the handler to search for.
/// - returns: the `EventLoopFuture` which will be notified once the the operation completes.
@inlinable
public func context<Handler: ChannelHandler>(handlerType: Handler.Type) -> EventLoopFuture<ChannelHandlerContext> {
let promise = self.eventLoop.makePromise(of: ChannelHandlerContext.self)
if self.eventLoop.inEventLoop {
promise.completeWith(self._contextSync(handlerType: handlerType))
} else {
self.eventLoop.execute {
promise.completeWith(self._contextSync(handlerType: handlerType))
}
}
return promise.futureResult
}
/// Synchronously finds and returns the `ChannelHandlerContext` that belongs to the first
/// `ChannelHandler` of the given type.
///
/// - Important: This must be called on the `EventLoop`.
/// - Parameter handlerType: The type of handler to search for.
/// - Returns: the `ChannelHandlerContext` that belongs to the `ChannelHandler`, if one exists.
@inlinable // should be fileprivate
internal func _contextSync<Handler: ChannelHandler>(handlerType: Handler.Type) -> Result<ChannelHandlerContext, Error> {
return self._contextSync({ $0.handler is Handler })
}
/// Synchronously finds a `ChannelHandlerContext` in the `ChannelPipeline`.
/// - Important: This must be called on the `EventLoop`.
@usableFromInline // should be fileprivate
internal func _contextSync(_ body: (ChannelHandlerContext) -> Bool) -> Result<ChannelHandlerContext, Error> {
self.eventLoop.assertInEventLoop()
if let context = self.contextForPredicate0(body) {
return .success(context)
} else {
return .failure(ChannelPipelineError.notFound)
}
}
/// Returns a `ChannelHandlerContext` which matches.
///
/// This skips head and tail (as these are internal and should not be accessible by the user).
///
/// - parameters:
/// - body: The predicate to execute per `ChannelHandlerContext` in the `ChannelPipeline`.
/// - returns: The first `ChannelHandlerContext` that matches or `nil` if none did.
private func contextForPredicate0(_ body: (ChannelHandlerContext) -> Bool) -> ChannelHandlerContext? {
var curCtx: ChannelHandlerContext? = self.head?.next
while let context = curCtx, context !== self.tail {
if body(context) {
return context
}
curCtx = context.next
}
return nil
}
/// Remove a `ChannelHandlerContext` from the `ChannelPipeline` directly without going through the
/// `RemovableChannelHandler` API. This must only be used to clear the pipeline on `Channel` tear down and
/// as a result of the `leavePipeline` call in the `RemovableChannelHandler` API.
internal func removeHandlerFromPipeline(context: ChannelHandlerContext, promise: EventLoopPromise<Void>?) {
self.eventLoop.assertInEventLoop()
let nextCtx = context.next
let prevCtx = context.prev
if let prevCtx = prevCtx {
prevCtx.next = nextCtx
}
if let nextCtx = nextCtx {
nextCtx.prev = prevCtx
}
context.invokeHandlerRemoved()
promise?.succeed(())
// We need to keep the current node alive until after the callout in case the user uses the context.
context.next = nil
context.prev = nil
}
/// Returns the next name to use for a `ChannelHandler`.
private func nextName() -> String {
self.eventLoop.assertInEventLoop()
let name = "handler\(idx)"
idx += 1
return name
}
/// Remove all the `ChannelHandler`s from the `ChannelPipeline` and destroy these.
///
/// This method must only be called from within the `EventLoop`. It should only be called from a `ChannelCore`
/// implementation. Once called, the `ChannelPipeline` is no longer active and cannot be used again.
func removeHandlers() {
self.eventLoop.assertInEventLoop()
if let head = self.head {
while let context = head.next {
removeHandlerFromPipeline(context: context, promise: nil)
}
removeHandlerFromPipeline(context: self.head!, promise: nil)
}
self.head = nil
self.tail = nil
self.destroyed = true
self._channel = nil
}
// Just delegate to the head and tail context
public func fireChannelRegistered() {
if eventLoop.inEventLoop {
fireChannelRegistered0()
} else {
eventLoop.execute {
self.fireChannelRegistered0()
}
}
}
public func fireChannelUnregistered() {
if eventLoop.inEventLoop {
fireChannelUnregistered0()
} else {
eventLoop.execute {
self.fireChannelUnregistered0()
}
}
}
public func fireChannelInactive() {
if eventLoop.inEventLoop {
fireChannelInactive0()
} else {
eventLoop.execute {
self.fireChannelInactive0()
}
}
}
public func fireChannelActive() {
if eventLoop.inEventLoop {
fireChannelActive0()
} else {
eventLoop.execute {
self.fireChannelActive0()
}
}
}
public func fireChannelRead(_ data: NIOAny) {
if eventLoop.inEventLoop {
fireChannelRead0(data)
} else {
eventLoop.execute {
self.fireChannelRead0(data)
}
}
}
public func fireChannelReadComplete() {
if eventLoop.inEventLoop {
fireChannelReadComplete0()
} else {
eventLoop.execute {
self.fireChannelReadComplete0()
}
}
}
public func fireChannelWritabilityChanged() {
if eventLoop.inEventLoop {
fireChannelWritabilityChanged0()
} else {
eventLoop.execute {
self.fireChannelWritabilityChanged0()
}
}
}
public func fireUserInboundEventTriggered(_ event: Any) {
if eventLoop.inEventLoop {
fireUserInboundEventTriggered0(event)
} else {
eventLoop.execute {
self.fireUserInboundEventTriggered0(event)
}
}
}
public func fireErrorCaught(_ error: Error) {
if eventLoop.inEventLoop {
fireErrorCaught0(error: error)
} else {
eventLoop.execute {
self.fireErrorCaught0(error: error)
}
}
}
public func close(mode: CloseMode = .all, promise: EventLoopPromise<Void>?) {
if eventLoop.inEventLoop {
close0(mode: mode, promise: promise)
} else {
eventLoop.execute {
self.close0(mode: mode, promise: promise)
}
}
}
public func flush() {
if eventLoop.inEventLoop {
flush0()
} else {
eventLoop.execute {
self.flush0()
}
}
}
public func read() {
if eventLoop.inEventLoop {
read0()
} else {
eventLoop.execute {
self.read0()
}
}
}
public func write(_ data: NIOAny, promise: EventLoopPromise<Void>?) {
if eventLoop.inEventLoop {
write0(data, promise: promise)
} else {
eventLoop.execute {
self.write0(data, promise: promise)
}
}
}
public func writeAndFlush(_ data: NIOAny, promise: EventLoopPromise<Void>?) {
if eventLoop.inEventLoop {
writeAndFlush0(data, promise: promise)
} else {
eventLoop.execute {
self.writeAndFlush0(data, promise: promise)
}
}
}
public func bind(to address: SocketAddress, promise: EventLoopPromise<Void>?) {
if eventLoop.inEventLoop {
bind0(to: address, promise: promise)
} else {
eventLoop.execute {
self.bind0(to: address, promise: promise)
}
}
}
public func connect(to address: SocketAddress, promise: EventLoopPromise<Void>?) {
if eventLoop.inEventLoop {
connect0(to: address, promise: promise)
} else {
eventLoop.execute {
self.connect0(to: address, promise: promise)
}
}
}
public func register(promise: EventLoopPromise<Void>?) {
if eventLoop.inEventLoop {
register0(promise: promise)
} else {
eventLoop.execute {
self.register0(promise: promise)
}
}
}
public func triggerUserOutboundEvent(_ event: Any, promise: EventLoopPromise<Void>?) {
if eventLoop.inEventLoop {
triggerUserOutboundEvent0(event, promise: promise)
} else {
eventLoop.execute {
self.triggerUserOutboundEvent0(event, promise: promise)
}
}
}
// These methods are expected to only be called from within the EventLoop
private var firstOutboundCtx: ChannelHandlerContext? {
return self.tail?.prev
}
private var firstInboundCtx: ChannelHandlerContext? {
return self.head?.next
}
private func close0(mode: CloseMode, promise: EventLoopPromise<Void>?) {
if let firstOutboundCtx = firstOutboundCtx {
firstOutboundCtx.invokeClose(mode: mode, promise: promise)
} else {
promise?.fail(ChannelError.alreadyClosed)
}
}
private func flush0() {
if let firstOutboundCtx = firstOutboundCtx {
firstOutboundCtx.invokeFlush()
}
}
private func read0() {
if let firstOutboundCtx = firstOutboundCtx {
firstOutboundCtx.invokeRead()
}
}
private func write0(_ data: NIOAny, promise: EventLoopPromise<Void>?) {
if let firstOutboundCtx = firstOutboundCtx {
firstOutboundCtx.invokeWrite(data, promise: promise)
} else {
promise?.fail(ChannelError.ioOnClosedChannel)
}
}
private func writeAndFlush0(_ data: NIOAny, promise: EventLoopPromise<Void>?) {
if let firstOutboundCtx = firstOutboundCtx {
firstOutboundCtx.invokeWriteAndFlush(data, promise: promise)
} else {
promise?.fail(ChannelError.ioOnClosedChannel)
}
}
private func bind0(to address: SocketAddress, promise: EventLoopPromise<Void>?) {
if let firstOutboundCtx = firstOutboundCtx {
firstOutboundCtx.invokeBind(to: address, promise: promise)
} else {
promise?.fail(ChannelError.ioOnClosedChannel)
}
}
private func connect0(to address: SocketAddress, promise: EventLoopPromise<Void>?) {
if let firstOutboundCtx = firstOutboundCtx {
firstOutboundCtx.invokeConnect(to: address, promise: promise)
} else {
promise?.fail(ChannelError.ioOnClosedChannel)
}
}
private func register0(promise: EventLoopPromise<Void>?) {
if let firstOutboundCtx = firstOutboundCtx {
firstOutboundCtx.invokeRegister(promise: promise)
} else {
promise?.fail(ChannelError.ioOnClosedChannel)
}
}
private func triggerUserOutboundEvent0(_ event: Any, promise: EventLoopPromise<Void>?) {
if let firstOutboundCtx = firstOutboundCtx {
firstOutboundCtx.invokeTriggerUserOutboundEvent(event, promise: promise)
} else {
promise?.fail(ChannelError.ioOnClosedChannel)
}
}
private func fireChannelRegistered0() {
if let firstInboundCtx = firstInboundCtx {
firstInboundCtx.invokeChannelRegistered()
}
}
private func fireChannelUnregistered0() {
if let firstInboundCtx = firstInboundCtx {
firstInboundCtx.invokeChannelUnregistered()
}
}
private func fireChannelInactive0() {
if let firstInboundCtx = firstInboundCtx {
firstInboundCtx.invokeChannelInactive()
}
}
private func fireChannelActive0() {
if let firstInboundCtx = firstInboundCtx {
firstInboundCtx.invokeChannelActive()
}
}
private func fireChannelRead0(_ data: NIOAny) {
if let firstInboundCtx = firstInboundCtx {
firstInboundCtx.invokeChannelRead(data)
}
}
private func fireChannelReadComplete0() {
if let firstInboundCtx = firstInboundCtx {
firstInboundCtx.invokeChannelReadComplete()
}
}
private func fireChannelWritabilityChanged0() {
if let firstInboundCtx = firstInboundCtx {
firstInboundCtx.invokeChannelWritabilityChanged()
}
}
private func fireUserInboundEventTriggered0(_ event: Any) {
if let firstInboundCtx = firstInboundCtx {
firstInboundCtx.invokeUserInboundEventTriggered(event)
}
}
private func fireErrorCaught0(error: Error) {
assert((error as? ChannelError).map { $0 != .eof } ?? true)
if let firstInboundCtx = firstInboundCtx {
firstInboundCtx.invokeErrorCaught(error)
}
}
private var inEventLoop: Bool {
return eventLoop.inEventLoop
}
/// Create `ChannelPipeline` for a given `Channel`. This method should never be called by the end-user
/// directly: it is only intended for use with custom `Channel` implementations. Users should always use
/// `channel.pipeline` to access the `ChannelPipeline` for a `Channel`.
///
/// - parameters:
/// - channel: The `Channel` this `ChannelPipeline` is created for.
public init(channel: Channel) {
self._channel = channel
self.eventLoop = channel.eventLoop
self.head = nil // we need to initialise these to `nil` so we can use `self` in the lines below
self.tail = nil // we need to initialise these to `nil` so we can use `self` in the lines below
self.head = ChannelHandlerContext(name: HeadChannelHandler.name, handler: HeadChannelHandler.sharedInstance, pipeline: self)
self.tail = ChannelHandlerContext(name: TailChannelHandler.name, handler: TailChannelHandler.sharedInstance, pipeline: self)
self.head?.next = self.tail
self.tail?.prev = self.head
}
}
#if swift(>=5.7)
extension ChannelPipeline: @unchecked Sendable {}
#endif
extension ChannelPipeline {
/// Adds the provided channel handlers to the pipeline in the order given, taking account
/// of the behaviour of `ChannelHandler.add(first:)`.
///
/// - parameters:
/// - handlers: The array of `ChannelHandler`s to be added.
/// - position: The position in the `ChannelPipeline` to add `handlers`. Defaults to `.last`.
///
/// - returns: A future that will be completed when all of the supplied `ChannelHandler`s were added.
public func addHandlers(_ handlers: [ChannelHandler],
position: ChannelPipeline.Position = .last) -> EventLoopFuture<Void> {
let future: EventLoopFuture<Void>
if self.eventLoop.inEventLoop {
future = self.eventLoop.makeCompletedFuture(self.addHandlersSync(handlers, position: position))
} else {
future = self.eventLoop.submit {
try self.addHandlersSync(handlers, position: position).get()
}
}
return future
}
/// Adds the provided channel handlers to the pipeline in the order given, taking account
/// of the behaviour of `ChannelHandler.add(first:)`.
///
/// - parameters:
/// - handlers: One or more `ChannelHandler`s to be added.
/// - position: The position in the `ChannelPipeline` to add `handlers`. Defaults to `.last`.
///
/// - returns: A future that will be completed when all of the supplied `ChannelHandler`s were added.
public func addHandlers(_ handlers: ChannelHandler...,
position: ChannelPipeline.Position = .last) -> EventLoopFuture<Void> {
return self.addHandlers(handlers, position: position)
}
/// Synchronously adds the provided `ChannelHandler`s to the pipeline in the order given, taking
/// account of the behaviour of `ChannelHandler.add(first:)`.
///
/// - Important: Must be called on the `EventLoop`.
/// - Parameters:
/// - handlers: The array of `ChannelHandler`s to add.
/// - position: The position in the `ChannelPipeline` to add the handlers.
/// - Returns: A result representing whether the handlers were added or not.
fileprivate func addHandlersSync(_ handlers: [ChannelHandler],
position: ChannelPipeline.Position) -> Result<Void, Error> {
switch position {