forked from FranzBusch/swift-async-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMultiProducerSingleConsumerChannel+Internal.swift
1409 lines (1191 loc) · 57.7 KB
/
MultiProducerSingleConsumerChannel+Internal.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 Swift Async Algorithms open source project
//
// Copyright (c) 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#if compiler(>=6.0)
import DequeModule
extension MultiProducerSingleConsumerChannel {
@usableFromInline
enum _InternalBackpressureStrategy: Sendable, CustomStringConvertible {
@usableFromInline
struct _Watermark: Sendable, CustomStringConvertible {
/// The low watermark where demand should start.
@usableFromInline
let _low: Int
/// The high watermark where demand should be stopped.
@usableFromInline
let _high: Int
/// The current watermark level.
@usableFromInline
var _currentWatermark: Int = 0
/// A closure that can be used to calculate the watermark impact of a single element
@usableFromInline
let _waterLevelForElement: (@Sendable (Element) -> Int)?
@usableFromInline
var description: String {
"watermark(\(self._currentWatermark))"
}
init(low: Int, high: Int, waterLevelForElement: (@Sendable (Element) -> Int)?) {
precondition(low <= high)
self._low = low
self._high = high
self._waterLevelForElement = waterLevelForElement
}
@inlinable
mutating func didSend(elements: Deque<Element>.SubSequence) -> Bool {
if let waterLevelForElement = self._waterLevelForElement {
self._currentWatermark += elements.reduce(0) { $0 + waterLevelForElement($1) }
} else {
self._currentWatermark += elements.count
}
precondition(self._currentWatermark >= 0)
// We are demanding more until we reach the high watermark
return self._currentWatermark < self._high
}
@inlinable
mutating func didConsume(element: Element) -> Bool {
if let waterLevelForElement = self._waterLevelForElement {
self._currentWatermark -= waterLevelForElement(element)
} else {
self._currentWatermark -= 1
}
precondition(self._currentWatermark >= 0)
// We start demanding again once we are below the low watermark
return self._currentWatermark < self._low
}
}
@usableFromInline
struct _Unbounded: Sendable, CustomStringConvertible {
@usableFromInline
var description: String {
return "unbounded"
}
init() { }
@inlinable
mutating func didSend(elements: Deque<Element>.SubSequence) -> Bool {
return true
}
@inlinable
mutating func didConsume(element: Element) -> Bool {
return true
}
}
/// A watermark based strategy.
case watermark(_Watermark)
/// An unbounded based strategy.
case unbounded(_Unbounded)
@usableFromInline
var description: String {
switch /*consume*/ self {
case .watermark(let strategy):
return strategy.description
case .unbounded(let unbounded):
return unbounded.description
}
}
@inlinable
mutating func didSend(elements: Deque<Element>.SubSequence) -> Bool {
switch /*consume*/ self {
case .watermark(var strategy):
let result = strategy.didSend(elements: elements)
self = .watermark(strategy)
return result
case .unbounded(var strategy):
let result = strategy.didSend(elements: elements)
self = .unbounded(strategy)
return result
}
}
@inlinable
mutating func didConsume(element: Element) -> Bool {
switch /*consume*/ self {
case .watermark(var strategy):
let result = strategy.didConsume(element: element)
self = .watermark(strategy)
return result
case .unbounded(var strategy):
let result = strategy.didConsume(element: element)
self = .unbounded(strategy)
return result
}
}
}
}
extension MultiProducerSingleConsumerChannel {
@usableFromInline
final class _Storage {
@usableFromInline
let _lock = Lock.allocate()
/// The state machine
@usableFromInline
var _stateMachine: _StateMachine
var onTermination: (@Sendable () -> Void)? {
set {
self._lock.withLockVoid {
self._stateMachine._onTermination = newValue
}
}
get {
self._lock.withLock {
self._stateMachine._onTermination
}
}
}
init(
backpressureStrategy: _InternalBackpressureStrategy
) {
self._stateMachine = .init(backpressureStrategy: backpressureStrategy)
}
func sequenceDeinitialized() {
let action = self._lock.withLock {
self._stateMachine.sequenceDeinitialized()
}
switch action {
case .callOnTermination(let onTermination):
onTermination?()
case .failProducersAndCallOnTermination(let producerContinuations, let onTermination):
for producerContinuation in producerContinuations {
switch producerContinuation {
case .closure(let onProduceMore):
onProduceMore(.failure(MultiProducerSingleConsumerChannelAlreadyFinishedError()))
case .continuation(let continuation):
continuation.resume(throwing: MultiProducerSingleConsumerChannelAlreadyFinishedError())
}
}
onTermination?()
case .none:
break
}
}
func iteratorInitialized() {
self._lock.withLockVoid {
self._stateMachine.iteratorInitialized()
}
}
func iteratorDeinitialized() {
let action = self._lock.withLock {
self._stateMachine.iteratorDeinitialized()
}
switch action {
case .callOnTermination(let onTermination):
onTermination?()
case .failProducersAndCallOnTermination(let producerContinuations, let onTermination):
for producerContinuation in producerContinuations {
switch producerContinuation {
case .closure(let onProduceMore):
onProduceMore(.failure(MultiProducerSingleConsumerChannelAlreadyFinishedError()))
case .continuation(let continuation):
continuation.resume(throwing: MultiProducerSingleConsumerChannelAlreadyFinishedError())
}
}
onTermination?()
case .none:
break
}
}
func sourceDeinitialized() {
let action = self._lock.withLock {
self._stateMachine.sourceDeinitialized()
}
switch action {
case .callOnTermination(let onTermination):
onTermination?()
case .failProducersAndCallOnTermination(let producerContinuations, let onTermination):
for producerContinuation in producerContinuations {
switch producerContinuation {
case .closure(let onProduceMore):
onProduceMore(.failure(MultiProducerSingleConsumerChannelAlreadyFinishedError()))
case .continuation(let continuation):
continuation.resume(throwing: MultiProducerSingleConsumerChannelAlreadyFinishedError())
}
}
onTermination?()
case .none:
break
}
}
//@inlinable
func send(
contentsOf sequence: some Sequence<Element>
) throws -> MultiProducerSingleConsumerChannel<Element, Failure>.Source.SendResult {
let action = self._lock.withLock {
return self._stateMachine.send(sequence)
}
switch action {
case .returnProduceMore:
return .produceMore
case .returnEnqueue(let callbackToken):
return .enqueueCallback(.init(id: callbackToken))
case .resumeConsumerAndReturnProduceMore(let continuation, let element):
continuation.resume(returning: element)
return .produceMore
case .resumeConsumerAndReturnEnqueue(let continuation, let element, let callbackToken):
continuation.resume(returning: element)
return .enqueueCallback(.init(id: callbackToken))
case .throwFinishedError:
throw MultiProducerSingleConsumerChannelAlreadyFinishedError()
}
}
//@inlinable
func enqueueProducer(
callbackToken: UInt64,
continuation: UnsafeContinuation<Void, any Error>
) {
let action = self._lock.withLock {
self._stateMachine.enqueueContinuation(callbackToken: callbackToken, continuation: continuation)
}
switch action {
case .resumeProducer(let continuation):
continuation.resume()
case .resumeProducerWithError(let continuation, let error):
continuation.resume(throwing: error)
case .none:
break
}
}
//@inlinable
func enqueueProducer(
callbackToken: UInt64,
onProduceMore: sending @escaping (Result<Void, Error>) -> Void
) {
let action = self._lock.withLock {
self._stateMachine.enqueueProducer(callbackToken: callbackToken, onProduceMore: onProduceMore)
}
switch action {
case .resumeProducer(let onProduceMore):
onProduceMore(Result<Void, Error>.success(()))
case .resumeProducerWithError(let onProduceMore, let error):
onProduceMore(Result<Void, Error>.failure(error))
case .none:
break
}
}
//@inlinable
func cancelProducer(
callbackToken: UInt64
) {
let action = self._lock.withLock {
self._stateMachine.cancelProducer(callbackToken: callbackToken)
}
switch action {
case .resumeProducerWithCancellationError(let onProduceMore):
switch onProduceMore {
case .closure(let onProduceMore):
onProduceMore(.failure(CancellationError()))
case .continuation(let continuation):
continuation.resume(throwing: CancellationError())
}
case .none:
break
}
}
//@inlinable
func finish(_ failure: Failure?) {
let action = self._lock.withLock {
self._stateMachine.finish(failure)
}
switch action {
case .callOnTermination(let onTermination):
onTermination?()
case .resumeConsumerAndCallOnTermination(let consumerContinuation, let failure, let onTermination):
switch failure {
case .some(let error):
consumerContinuation.resume(throwing: error)
case .none:
consumerContinuation.resume(returning: nil)
}
onTermination?()
case .resumeProducers(let producerContinuations):
for producerContinuation in producerContinuations {
switch producerContinuation {
case .closure(let onProduceMore):
onProduceMore(.failure(MultiProducerSingleConsumerChannelAlreadyFinishedError()))
case .continuation(let continuation):
continuation.resume(throwing: MultiProducerSingleConsumerChannelAlreadyFinishedError())
}
}
case .none:
break
}
}
//@inlinable
func next(isolation actor: isolated (any Actor)?) async throws -> Element? {
let action = self._lock.withLock {
self._stateMachine.next()
}
switch action {
case .returnElement(let element):
return element
case .returnElementAndResumeProducers(let element, let producerContinuations):
for producerContinuation in producerContinuations {
switch producerContinuation {
case .closure(let onProduceMore):
onProduceMore(.success(()))
case .continuation(let continuation):
continuation.resume()
}
}
return element
case .returnFailureAndCallOnTermination(let failure, let onTermination):
onTermination?()
switch failure {
case .some(let error):
throw error
case .none:
return nil
}
case .returnNil:
return nil
case .suspendTask:
return try await self.suspendNext(isolation: actor)
}
}
//@inlinable
func suspendNext(isolation actor: isolated (any Actor)?) async throws -> Element? {
return try await withTaskCancellationHandler {
return try await withUnsafeThrowingContinuation { continuation in
let action = self._lock.withLock {
self._stateMachine.suspendNext(continuation: continuation)
}
switch action {
case .resumeConsumerWithElement(let continuation, let element):
continuation.resume(returning: element)
case .resumeConsumerWithElementAndProducers(let continuation, let element, let producerContinuations):
continuation.resume(returning: element)
for producerContinuation in producerContinuations {
switch producerContinuation {
case .closure(let onProduceMore):
onProduceMore(.failure(CancellationError()))
case .continuation(let continuation):
continuation.resume()
}
}
case .resumeConsumerWithFailureAndCallOnTermination(let continuation, let failure, let onTermination):
switch failure {
case .some(let error):
continuation.resume(throwing: error)
case .none:
continuation.resume(returning: nil)
}
onTermination?()
case .resumeConsumerWithNil(let continuation):
continuation.resume(returning: nil)
case .none:
break
}
}
} onCancel: {
let action = self._lock.withLock {
self._stateMachine.cancelNext()
}
switch action {
case .resumeConsumerWithNilAndCallOnTermination(let continuation, let onTermination):
continuation.resume(returning: nil)
onTermination?()
case .failProducersAndCallOnTermination(let producerContinuations, let onTermination):
for producerContinuation in producerContinuations {
switch producerContinuation {
case .closure(let onProduceMore):
onProduceMore(.failure(MultiProducerSingleConsumerChannelAlreadyFinishedError()))
case .continuation(let continuation):
continuation.resume(throwing: MultiProducerSingleConsumerChannelAlreadyFinishedError())
}
}
onTermination?()
case .none:
break
}
}
}
}
}
extension MultiProducerSingleConsumerChannel._Storage {
/// The state machine of the channel.
@usableFromInline
struct _StateMachine: ~Copyable {
/// The state machine's current state.
@usableFromInline
var _state: _State
//@inlinable
var _onTermination: (@Sendable () -> Void)? {
set {
switch (consume self)._state {
case .channeling(var channeling):
channeling.onTermination = newValue
self = .init(state: .channeling(channeling))
case .sourceFinished(var sourceFinished):
sourceFinished.onTermination = newValue
self = .init(state: .sourceFinished(sourceFinished))
case .finished(let finished):
self = .init(state: .finished(finished))
}
}
get {
switch self._state {
case .channeling(let channeling):
return channeling.onTermination
case .sourceFinished(let sourceFinished):
return sourceFinished.onTermination
case .finished:
return nil
}
}
}
init(
backpressureStrategy: MultiProducerSingleConsumerChannel._InternalBackpressureStrategy
) {
self._state = .channeling(
.init(
backpressureStrategy: backpressureStrategy,
iteratorInitialized: false,
buffer: .init(),
producerContinuations: .init(),
cancelledAsyncProducers: .init(),
hasOutstandingDemand: true,
activeProducers: 1,
nextCallbackTokenID: 0
)
)
}
//@inlinable
init(state: consuming _State) {
self._state = state
}
/// Actions returned by `sourceDeinitialized()`.
@usableFromInline
enum SourceDeinitializedAction {
/// Indicates that `onTermination` should be called.
case callOnTermination((@Sendable () -> Void)?)
/// Indicates that all producers should be failed and `onTermination` should be called.
case failProducersAndCallOnTermination(
_TinyArray<_MultiProducerSingleConsumerSuspendedProducer>,
(@Sendable () -> Void)?
)
}
//@inlinable
mutating func sourceDeinitialized() -> SourceDeinitializedAction? {
switch (consume self)._state {
case .channeling(var channeling):
channeling.activeProducers -= 1
if channeling.activeProducers == 0 {
// This was the last producer so we can transition to source finished now
self = .init(state: .sourceFinished(.init(
iteratorInitialized: channeling.iteratorInitialized,
buffer: channeling.buffer
)))
if channeling.suspendedProducers.isEmpty {
return .callOnTermination(channeling.onTermination)
} else {
return .failProducersAndCallOnTermination(
.init(channeling.suspendedProducers.lazy.map { $0.1 }),
channeling.onTermination
)
}
} else {
// We still have more producers
self = .init(state: .channeling(channeling))
return nil
}
case .sourceFinished(let sourceFinished):
// This can happen if one producer calls finish and another deinits afterwards
self = .init(state: .sourceFinished(sourceFinished))
return nil
case .finished(let finished):
// This can happen if the consumer finishes and the producers deinit
self = .init(state: .finished(finished))
return nil
}
}
/// Actions returned by `sequenceDeinitialized()`.
@usableFromInline
enum SequenceDeinitializedAction {
/// Indicates that `onTermination` should be called.
case callOnTermination((@Sendable () -> Void)?)
/// Indicates that all producers should be failed and `onTermination` should be called.
case failProducersAndCallOnTermination(
_TinyArray<_MultiProducerSingleConsumerSuspendedProducer>,
(@Sendable () -> Void)?
)
}
//@inlinable
mutating func sequenceDeinitialized() -> SequenceDeinitializedAction? {
switch (consume self)._state {
case .channeling(var channeling):
guard channeling.iteratorInitialized else {
// No iterator was created so we can transition to finished right away.
self = .init(state: .finished(.init(iteratorInitialized: false, sourceFinished: false)))
return .failProducersAndCallOnTermination(
.init(channeling.suspendedProducers.lazy.map { $0.1 }),
channeling.onTermination
)
}
// An iterator was created and we deinited the sequence.
// This is an expected pattern and we just continue on normal.
self = .init(state: .channeling(channeling))
return .none
case .sourceFinished(var sourceFinished):
guard sourceFinished.iteratorInitialized else {
// No iterator was created so we can transition to finished right away.
self = .init(state: .finished(.init(iteratorInitialized: false, sourceFinished: true)))
return .callOnTermination(sourceFinished.onTermination)
}
// An iterator was created and we deinited the sequence.
// This is an expected pattern and we just continue on normal.
self = .init(state: .sourceFinished(sourceFinished))
return .none
case .finished(var finished):
// We are already finished so there is nothing left to clean up.
// This is just the references dropping afterwards.
self = .init(state: .finished(finished))
return .none
}
}
//@inlinable
mutating func iteratorInitialized() {
switch (consume self)._state {
case .channeling(var channeling):
if channeling.iteratorInitialized {
// Our sequence is a unicast sequence and does not support multiple AsyncIterator's
fatalError("Only a single AsyncIterator can be created")
} else {
// The first and only iterator was initialized.
channeling.iteratorInitialized = true
self = .init(state: .channeling(channeling))
}
case .sourceFinished(var sourceFinished):
if sourceFinished.iteratorInitialized {
// Our sequence is a unicast sequence and does not support multiple AsyncIterator's
fatalError("Only a single AsyncIterator can be created")
} else {
// The first and only iterator was initialized.
sourceFinished.iteratorInitialized = true
self = .init(state: .sourceFinished(sourceFinished))
}
case .finished(let finished):
if finished.iteratorInitialized {
// Our sequence is a unicast sequence and does not support multiple AsyncIterator's
fatalError("Only a single AsyncIterator can be created")
} else {
self = .init(state: .finished(.init(iteratorInitialized: true, sourceFinished: finished.sourceFinished)))
}
}
}
/// Actions returned by `iteratorDeinitialized()`.
@usableFromInline
enum IteratorDeinitializedAction {
/// Indicates that `onTermination` should be called.
case callOnTermination((@Sendable () -> Void)?)
/// Indicates that all producers should be failed and `onTermination` should be called.
case failProducersAndCallOnTermination(
_TinyArray<_MultiProducerSingleConsumerSuspendedProducer>,
(@Sendable () -> Void)?
)
}
//@inlinable
mutating func iteratorDeinitialized() -> IteratorDeinitializedAction? {
switch (consume self)._state {
case .channeling(let channeling):
if channeling.iteratorInitialized {
// An iterator was created and deinited. Since we only support
// a single iterator we can now transition to finish.
self = .init(state: .finished(.init(iteratorInitialized: true, sourceFinished: false)))
return .failProducersAndCallOnTermination(
.init(channeling.suspendedProducers.lazy.map { $0.1 }),
channeling.onTermination
)
} else {
// An iterator needs to be initialized before it can be deinitialized.
fatalError("MultiProducerSingleConsumerChannel internal inconsistency")
}
case .sourceFinished(let sourceFinished):
if sourceFinished.iteratorInitialized {
// An iterator was created and deinited. Since we only support
// a single iterator we can now transition to finish.
self = .init(state: .finished(.init(iteratorInitialized: true, sourceFinished: true)))
return .callOnTermination(sourceFinished.onTermination)
} else {
// An iterator needs to be initialized before it can be deinitialized.
fatalError("MultiProducerSingleConsumerChannel internal inconsistency")
}
case .finished(var finished):
// We are already finished so there is nothing left to clean up.
// This is just the references dropping afterwards.
self = .init(state: .finished(finished))
return .none
}
}
/// Actions returned by `send()`.
@usableFromInline
enum SendAction {
/// Indicates that the producer should be notified to produce more.
case returnProduceMore
/// Indicates that the producer should be suspended to stop producing.
case returnEnqueue(
callbackToken: UInt64
)
/// Indicates that the consumer should be resumed and the producer should be notified to produce more.
case resumeConsumerAndReturnProduceMore(
continuation: UnsafeContinuation<Element?, Error>,
element: Element
)
/// Indicates that the consumer should be resumed and the producer should be suspended.
case resumeConsumerAndReturnEnqueue(
continuation: UnsafeContinuation<Element?, Error>,
element: Element,
callbackToken: UInt64
)
/// Indicates that the producer has been finished.
case throwFinishedError
@inlinable
init(
callbackToken: UInt64?,
continuationAndElement: (UnsafeContinuation<Element?, Error>, Element)? = nil
) {
switch (callbackToken, continuationAndElement) {
case (.none, .none):
self = .returnProduceMore
case (.some(let callbackToken), .none):
self = .returnEnqueue(callbackToken: callbackToken)
case (.none, .some((let continuation, let element))):
self = .resumeConsumerAndReturnProduceMore(
continuation: continuation,
element: element
)
case (.some(let callbackToken), .some((let continuation, let element))):
self = .resumeConsumerAndReturnEnqueue(
continuation: continuation,
element: element,
callbackToken: callbackToken
)
}
}
}
//@inlinable
mutating func send(_ sequence: some Sequence<Element>) -> SendAction {
switch (consume self)._state {
case .channeling(var channeling):
// We have an element and can resume the continuation
let bufferEndIndexBeforeAppend = channeling.buffer.endIndex
channeling.buffer.append(contentsOf: sequence)
var shouldProduceMore = channeling.backpressureStrategy.didSend(
elements: channeling.buffer[bufferEndIndexBeforeAppend...]
)
channeling.hasOutstandingDemand = shouldProduceMore
guard let consumerContinuation = channeling.consumerContinuation else {
// We don't have a suspended consumer so we just buffer the elements
let callbackToken = shouldProduceMore ? nil : channeling.nextCallbackToken()
self = .init(state: .channeling(channeling))
return .init(
callbackToken: callbackToken
)
}
guard let element = channeling.buffer.popFirst() else {
// We got a send of an empty sequence. We just tolerate this.
let callbackToken = shouldProduceMore ? nil : channeling.nextCallbackToken()
self = .init(state: .channeling(channeling))
return .init(callbackToken: callbackToken)
}
// We need to tell the back pressure strategy that we consumed
shouldProduceMore = channeling.backpressureStrategy.didConsume(element: element)
channeling.hasOutstandingDemand = shouldProduceMore
// We got a consumer continuation and an element. We can resume the consumer now
channeling.consumerContinuation = nil
let callbackToken = shouldProduceMore ? nil : channeling.nextCallbackToken()
self = .init(state: .channeling(channeling))
return .init(
callbackToken: callbackToken,
continuationAndElement: (consumerContinuation, element)
)
case .sourceFinished(let sourceFinished):
// If the source has finished we are dropping the elements.
self = .init(state: .sourceFinished(sourceFinished))
return .throwFinishedError
case .finished(let finished):
// If the source has finished we are dropping the elements.
self = .init(state: .finished(finished))
return .throwFinishedError
}
}
/// Actions returned by `enqueueProducer()`.
@usableFromInline
enum EnqueueProducerAction {
/// Indicates that the producer should be notified to produce more.
case resumeProducer((Result<Void, Error>) -> Void)
/// Indicates that the producer should be notified about an error.
case resumeProducerWithError((Result<Void, Error>) -> Void, Error)
}
//@inlinable
mutating func enqueueProducer(
callbackToken: UInt64,
onProduceMore: sending @escaping (Result<Void, Error>) -> Void
) -> EnqueueProducerAction? {
switch (consume self)._state {
case .channeling(var channeling):
if let index = channeling.cancelledAsyncProducers.firstIndex(of: callbackToken) {
// Our producer got marked as cancelled.
channeling.cancelledAsyncProducers.remove(at: index)
self = .init(state: .channeling(channeling))
return .resumeProducerWithError(onProduceMore, CancellationError())
} else if channeling.hasOutstandingDemand {
// We hit an edge case here where we wrote but the consuming thread got interleaved
self = .init(state: .channeling(channeling))
return .resumeProducer(onProduceMore)
} else {
channeling.suspendedProducers.append((callbackToken, .closure(onProduceMore)))
self = .init(state: .channeling(channeling))
return .none
}
case .sourceFinished(let sourceFinished):
// Since we are unlocking between sending elements and suspending the send
// It can happen that the source got finished or the consumption fully finishes.
self = .init(state: .sourceFinished(sourceFinished))
return .resumeProducerWithError(onProduceMore, MultiProducerSingleConsumerChannelAlreadyFinishedError())
case .finished(let finished):
// Since we are unlocking between sending elements and suspending the send
// It can happen that the source got finished or the consumption fully finishes.
self = .init(state: .finished(finished))
return .resumeProducerWithError(onProduceMore, MultiProducerSingleConsumerChannelAlreadyFinishedError())
}
}
/// Actions returned by `enqueueContinuation()`.
@usableFromInline
enum EnqueueContinuationAction {
/// Indicates that the producer should be notified to produce more.
case resumeProducer(UnsafeContinuation<Void, any Error>)
/// Indicates that the producer should be notified about an error.
case resumeProducerWithError(UnsafeContinuation<Void, any Error>, Error)
}
//@inlinable
mutating func enqueueContinuation(
callbackToken: UInt64,
continuation: UnsafeContinuation<Void, any Error>
) -> EnqueueContinuationAction? {
switch (consume self)._state {
case .channeling(var channeling):
if let index = channeling.cancelledAsyncProducers.firstIndex(of: callbackToken) {
// Our producer got marked as cancelled.
channeling.cancelledAsyncProducers.remove(at: index)
self = .init(state: .channeling(channeling))
return .resumeProducerWithError(continuation, CancellationError())
} else if channeling.hasOutstandingDemand {
// We hit an edge case here where we wrote but the consuming thread got interleaved
self = .init(state: .channeling(channeling))
return .resumeProducer(continuation)
} else {
channeling.suspendedProducers.append((callbackToken, .continuation(continuation)))
self = .init(state: .channeling(channeling))
return .none
}
case .sourceFinished(let sourceFinished):
// Since we are unlocking between sending elements and suspending the send
// It can happen that the source got finished or the consumption fully finishes.
self = .init(state: .sourceFinished(sourceFinished))
return .resumeProducerWithError(continuation, MultiProducerSingleConsumerChannelAlreadyFinishedError())
case .finished(let finished):
// Since we are unlocking between sending elements and suspending the send
// It can happen that the source got finished or the consumption fully finishes.
self = .init(state: .finished(finished))
return .resumeProducerWithError(continuation, MultiProducerSingleConsumerChannelAlreadyFinishedError())
}
}
/// Actions returned by `cancelProducer()`.
@usableFromInline
enum CancelProducerAction {
/// Indicates that the producer should be notified about cancellation.
case resumeProducerWithCancellationError(_MultiProducerSingleConsumerSuspendedProducer)
}
//@inlinable
mutating func cancelProducer(
callbackToken: UInt64
) -> CancelProducerAction? {
switch (consume self)._state {
case .channeling(var channeling):
guard let index = channeling.suspendedProducers.firstIndex(where: { $0.0 == callbackToken }) else {
// The task that sends was cancelled before sending elements so the cancellation handler
// got invoked right away
channeling.cancelledAsyncProducers.append(callbackToken)
self = .init(state: .channeling(channeling))
return .none
}
// We have an enqueued producer that we need to resume now
let continuation = channeling.suspendedProducers.remove(at: index).1
self = .init(state: .channeling(channeling))
return .resumeProducerWithCancellationError(continuation)
case .sourceFinished(let sourceFinished):
// Since we are unlocking between sending elements and suspending the send
// It can happen that the source got finished or the consumption fully finishes.
self = .init(state: .sourceFinished(sourceFinished))
return .none
case .finished(let finished):
// Since we are unlocking between sending elements and suspending the send
// It can happen that the source got finished or the consumption fully finishes.
self = .init(state: .finished(finished))
return .none
}
}
/// Actions returned by `finish()`.
@usableFromInline
enum FinishAction {
/// Indicates that `onTermination` should be called.
case callOnTermination((() -> Void)?)
/// Indicates that the consumer should be resumed with the failure, the producers
/// should be resumed with an error and `onTermination` should be called.
case resumeConsumerAndCallOnTermination(
consumerContinuation: UnsafeContinuation<Element?, Error>,
failure: Failure?,
onTermination: (() -> Void)?
)
/// Indicates that the producers should be resumed with an error.
case resumeProducers(
producerContinuations: _TinyArray<_MultiProducerSingleConsumerSuspendedProducer>
)
}