-
Notifications
You must be signed in to change notification settings - Fork 23
/
BufferedStream.swift
1973 lines (1736 loc) · 79.9 KB
/
BufferedStream.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 SwiftOpenAPIGenerator open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// swift-format-ignore-file
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020-2021 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import DequeModule
/// An asynchronous sequence generated from an error-throwing closure that
/// calls a continuation to produce new elements.
///
/// `BufferedStream` conforms to `AsyncSequence`, providing a convenient
/// way to create an asynchronous sequence without manually implementing an
/// asynchronous iterator. In particular, an asynchronous stream is well-suited
/// to adapt callback- or delegation-based APIs to participate with
/// `async`-`await`.
///
/// In contrast to `AsyncStream`, this type can throw an error from the awaited
/// `next()`, which terminates the stream with the thrown error.
///
/// You initialize an `BufferedStream` with a closure that receives an
/// `BufferedStream.Continuation`. Produce elements in this closure, then
/// provide them to the stream by calling the continuation's `yield(_:)` method.
/// When there are no further elements to produce, call the continuation's
/// `finish()` method. This causes the sequence iterator to produce a `nil`,
/// which terminates the sequence. If an error occurs, call the continuation's
/// `finish(throwing:)` method, which causes the iterator's `next()` method to
/// throw the error to the awaiting call point. The continuation is `Sendable`,
/// which permits calling it from concurrent contexts external to the iteration
/// of the `BufferedStream`.
///
/// An arbitrary source of elements can produce elements faster than they are
/// consumed by a caller iterating over them. Because of this, `BufferedStream`
/// defines a buffering behavior, allowing the stream to buffer a specific
/// number of oldest or newest elements. By default, the buffer limit is
/// `Int.max`, which means it's unbounded.
///
/// ### Adapting Existing Code to Use Streams
///
/// To adapt existing callback code to use `async`-`await`, use the callbacks
/// to provide values to the stream, by using the continuation's `yield(_:)`
/// method.
///
/// Consider a hypothetical `QuakeMonitor` type that provides callers with
/// `Quake` instances every time it detects an earthquake. To receive callbacks,
/// callers set a custom closure as the value of the monitor's
/// `quakeHandler` property, which the monitor calls back as necessary. Callers
/// can also set an `errorHandler` to receive asynchronous error notifications,
/// such as the monitor service suddenly becoming unavailable.
///
/// class QuakeMonitor {
/// var quakeHandler: ((Quake) -> Void)?
/// var errorHandler: ((Error) -> Void)?
///
/// func startMonitoring() {…}
/// func stopMonitoring() {…}
/// }
///
/// To adapt this to use `async`-`await`, extend the `QuakeMonitor` to add a
/// `quakes` property, of type `BufferedStream<Quake>`. In the getter for
/// this property, return an `BufferedStream`, whose `build` closure --
/// called at runtime to create the stream -- uses the continuation to
/// perform the following steps:
///
/// 1. Creates a `QuakeMonitor` instance.
/// 2. Sets the monitor's `quakeHandler` property to a closure that receives
/// each `Quake` instance and forwards it to the stream by calling the
/// continuation's `yield(_:)` method.
/// 3. Sets the monitor's `errorHandler` property to a closure that receives
/// any error from the monitor and forwards it to the stream by calling the
/// continuation's `finish(throwing:)` method. This causes the stream's
/// iterator to throw the error and terminate the stream.
/// 4. Sets the continuation's `onTermination` property to a closure that
/// calls `stopMonitoring()` on the monitor.
/// 5. Calls `startMonitoring` on the `QuakeMonitor`.
///
/// ```
/// extension QuakeMonitor {
///
/// static var throwingQuakes: BufferedStream<Quake, Error> {
/// BufferedStream { continuation in
/// let monitor = QuakeMonitor()
/// monitor.quakeHandler = { quake in
/// continuation.yield(quake)
/// }
/// monitor.errorHandler = { error in
/// continuation.finish(throwing: error)
/// }
/// continuation.onTermination = { @Sendable _ in
/// monitor.stopMonitoring()
/// }
/// monitor.startMonitoring()
/// }
/// }
/// }
/// ```
///
///
/// Because the stream is an `AsyncSequence`, the call point uses the
/// `for`-`await`-`in` syntax to process each `Quake` instance as produced by the stream:
///
/// do {
/// for try await quake in quakeStream {
/// print("Quake: \(quake.date)")
/// }
/// print("Stream done.")
/// } catch {
/// print("Error: \(error)")
/// }
///
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
@usableFromInline
internal struct BufferedStream<Element> {
@usableFromInline
final class _Backing: Sendable {
@usableFromInline
let storage: _BackPressuredStorage
@usableFromInline
init(storage: _BackPressuredStorage) {
self.storage = storage
}
deinit {
self.storage.sequenceDeinitialized()
}
}
@usableFromInline
enum _Implementation: Sendable {
/// This is the implementation with backpressure based on the Source
case backpressured(_Backing)
}
@usableFromInline
let implementation: _Implementation
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension BufferedStream: AsyncSequence {
/// The asynchronous iterator for iterating an asynchronous stream.
///
/// This type is not `Sendable`. Don't use it from multiple
/// concurrent contexts. It is a programmer error to invoke `next()` from a
/// concurrent context that contends with another such call, which
/// results in a call to `fatalError()`.
@usableFromInline
internal struct Iterator: AsyncIteratorProtocol {
@usableFromInline
final class _Backing {
@usableFromInline
let storage: _BackPressuredStorage
@usableFromInline
init(storage: _BackPressuredStorage) {
self.storage = storage
self.storage.iteratorInitialized()
}
deinit {
self.storage.iteratorDeinitialized()
}
}
@usableFromInline
enum _Implementation {
/// This is the implementation with backpressure based on the Source
case backpressured(_Backing)
}
@usableFromInline
var implementation: _Implementation
@usableFromInline
init(implementation: _Implementation) {
self.implementation = implementation
}
/// The next value from the asynchronous stream.
///
/// When `next()` returns `nil`, this signifies the end of the
/// `BufferedStream`.
///
/// It is a programmer error to invoke `next()` from a concurrent context
/// that contends with another such call, which results in a call to
/// `fatalError()`.
///
/// If you cancel the task this iterator is running in while `next()` is
/// awaiting a value, the `BufferedStream` terminates. In this case,
/// `next()` may return `nil` immediately, or else return `nil` on
/// subsequent calls.
@inlinable
internal mutating func next() async throws -> Element? {
switch self.implementation {
case .backpressured(let backing):
return try await backing.storage.next()
}
}
}
/// Creates the asynchronous iterator that produces elements of this
/// asynchronous sequence.
@inlinable
internal func makeAsyncIterator() -> Iterator {
switch self.implementation {
case .backpressured(let backing):
return Iterator(implementation: .backpressured(.init(storage: backing.storage)))
}
}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension BufferedStream: Sendable where Element: Sendable {}
@usableFromInline
internal struct _ManagedCriticalState<State>: @unchecked Sendable {
@usableFromInline
let lock: LockedValueBox<State>
@usableFromInline
internal init(_ initial: State) {
self.lock = .init(initial)
}
@inlinable
internal func withCriticalRegion<R>(
_ critical: (inout State) throws -> R
) rethrows -> R {
try self.lock.withLockedValue(critical)
}
}
@usableFromInline
internal struct AlreadyFinishedError: Error {
@usableFromInline
init() {}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension BufferedStream {
/// A mechanism to interface between producer code and an asynchronous stream.
///
/// Use this source to provide elements to the stream by calling one of the `write` methods, then terminate the stream normally
/// by calling the `finish()` method. You can also use the source's `finish(throwing:)` method to terminate the stream by
/// throwing an error.
@usableFromInline
internal struct Source: Sendable {
/// A strategy that handles the backpressure of the asynchronous stream.
@usableFromInline
internal struct BackPressureStrategy: Sendable {
/// When the high watermark is reached producers will be suspended. All producers will be resumed again once
/// the low watermark is reached. The current watermark is the number of elements in the buffer.
@inlinable
internal static func watermark(low: Int, high: Int) -> BackPressureStrategy {
BackPressureStrategy(
internalBackPressureStrategy: .watermark(.init(low: low, high: high))
)
}
/// When the high watermark is reached producers will be suspended. All producers will be resumed again once
/// the low watermark is reached. The current watermark is computed using the given closure.
static func customWatermark(
low: Int,
high: Int,
waterLevelForElement: @escaping @Sendable (Element) -> Int
) -> BackPressureStrategy where Element: RandomAccessCollection {
BackPressureStrategy(
internalBackPressureStrategy: .watermark(.init(low: low, high: high, waterLevelForElement: waterLevelForElement))
)
}
@usableFromInline
init(internalBackPressureStrategy: _InternalBackPressureStrategy) {
self._internalBackPressureStrategy = internalBackPressureStrategy
}
@usableFromInline
let _internalBackPressureStrategy: _InternalBackPressureStrategy
}
/// A type that indicates the result of writing elements to the source.
@frozen
@usableFromInline
internal enum WriteResult: Sendable {
/// A token that is returned when the asynchronous stream's backpressure strategy indicated that production should
/// be suspended. Use this token to enqueue a callback by calling the ``enqueueCallback(_:)`` method.
@usableFromInline
internal struct CallbackToken: Sendable {
@usableFromInline
let id: UInt
@usableFromInline
init(id: UInt) {
self.id = id
}
}
/// Indicates that more elements should be produced and written to the source.
case produceMore
/// Indicates that a callback should be enqueued.
///
/// The associated token should be passed to the ``enqueueCallback(_:)`` method.
case enqueueCallback(CallbackToken)
}
/// Backing class for the source used to hook a deinit.
@usableFromInline
final class _Backing: Sendable {
@usableFromInline
let storage: _BackPressuredStorage
@usableFromInline
init(storage: _BackPressuredStorage) {
self.storage = storage
}
deinit {
self.storage.sourceDeinitialized()
}
}
/// A callback to invoke when the stream finished.
///
/// The stream finishes and calls this closure in the following cases:
/// - No iterator was created and the sequence was deinited
/// - An iterator was created and deinited
/// - After ``finish(throwing:)`` was called and all elements have been consumed
/// - The consuming task got cancelled
@inlinable
internal var onTermination: (@Sendable () -> Void)? {
set {
self._backing.storage.onTermination = newValue
}
get {
self._backing.storage.onTermination
}
}
@usableFromInline
var _backing: _Backing
@usableFromInline
internal init(storage: _BackPressuredStorage) {
self._backing = .init(storage: storage)
}
/// Writes new elements to the asynchronous stream.
///
/// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the
/// first element of the provided sequence. If the asynchronous stream already terminated then this method will throw an error
/// indicating the failure.
///
/// - Parameter sequence: The elements to write to the asynchronous stream.
/// - Returns: The result that indicates if more elements should be produced at this time.
@inlinable
internal func write<S>(contentsOf sequence: S) throws -> WriteResult
where Element == S.Element, S: Sequence {
try self._backing.storage.write(contentsOf: sequence)
}
/// Write the element to the asynchronous stream.
///
/// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the
/// provided element. If the asynchronous stream already terminated then this method will throw an error
/// indicating the failure.
///
/// - Parameter element: The element to write to the asynchronous stream.
/// - Returns: The result that indicates if more elements should be produced at this time.
@inlinable
internal func write(_ element: Element) throws -> WriteResult {
try self._backing.storage.write(contentsOf: CollectionOfOne(element))
}
/// Enqueues a callback that will be invoked once more elements should be produced.
///
/// Call this method after ``write(contentsOf:)`` or ``write(:)`` returned ``WriteResult/enqueueCallback(_:)``.
///
/// - Important: Enqueueing the same token multiple times is not allowed.
///
/// - Parameters:
/// - callbackToken: The callback token.
/// - onProduceMore: The callback which gets invoked once more elements should be produced.
@inlinable
internal func enqueueCallback(
callbackToken: WriteResult.CallbackToken,
onProduceMore: @escaping @Sendable (Result<Void, any Error>) -> Void
) {
self._backing.storage.enqueueProducer(
callbackToken: callbackToken,
onProduceMore: onProduceMore
)
}
/// Cancel an enqueued callback.
///
/// Call this method to cancel a callback enqueued by the ``enqueueCallback(callbackToken:onProduceMore:)`` method.
///
/// - Note: This methods supports being called before ``enqueueCallback(callbackToken:onProduceMore:)`` is called and
/// will mark the passed `callbackToken` as cancelled.
///
/// - Parameter callbackToken: The callback token.
@inlinable
internal func cancelCallback(callbackToken: WriteResult.CallbackToken) {
self._backing.storage.cancelProducer(callbackToken: callbackToken)
}
/// Write new elements to the asynchronous stream and provide a callback which will be invoked once more elements should be produced.
///
/// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the
/// first element of the provided sequence. If the asynchronous stream already terminated then `onProduceMore` will be invoked with
/// a `Result.failure`.
///
/// - Parameters:
/// - sequence: The elements to write to the asynchronous stream.
/// - onProduceMore: The callback which gets invoked once more elements should be produced. This callback might be
/// invoked during the call to ``write(contentsOf:onProduceMore:)``.
@inlinable
internal func write<S>(
contentsOf sequence: S,
onProduceMore: @escaping @Sendable (Result<Void, any Error>) -> Void
) where Element == S.Element, S: Sequence {
do {
let writeResult = try self.write(contentsOf: sequence)
switch writeResult {
case .produceMore:
onProduceMore(Result<Void, any Error>.success(()))
case .enqueueCallback(let callbackToken):
self.enqueueCallback(callbackToken: callbackToken, onProduceMore: onProduceMore)
}
} catch {
onProduceMore(.failure(error))
}
}
/// Writes the element to the asynchronous stream.
///
/// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the
/// provided element. If the asynchronous stream already terminated then `onProduceMore` will be invoked with
/// a `Result.failure`.
///
/// - Parameters:
/// - sequence: The element to write to the asynchronous stream.
/// - onProduceMore: The callback which gets invoked once more elements should be produced. This callback might be
/// invoked during the call to ``write(_:onProduceMore:)``.
@inlinable
internal func write(
_ element: Element,
onProduceMore: @escaping @Sendable (Result<Void, any Error>) -> Void
) {
self.write(contentsOf: CollectionOfOne(element), onProduceMore: onProduceMore)
}
/// Write new elements to the asynchronous stream.
///
/// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the
/// first element of the provided sequence. If the asynchronous stream already terminated then this method will throw an error
/// indicating the failure.
///
/// This method returns once more elements should be produced.
///
/// - Parameters:
/// - sequence: The elements to write to the asynchronous stream.
@inlinable
internal func write<S>(contentsOf sequence: S) async throws
where Element == S.Element, S: Sequence {
let writeResult = try { try self.write(contentsOf: sequence) }()
switch writeResult {
case .produceMore:
return
case .enqueueCallback(let callbackToken):
try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
self.enqueueCallback(
callbackToken: callbackToken,
onProduceMore: { result in
switch result {
case .success():
continuation.resume(returning: ())
case .failure(let error):
continuation.resume(throwing: error)
}
}
)
}
} onCancel: {
self.cancelCallback(callbackToken: callbackToken)
}
}
}
/// Write new element to the asynchronous stream.
///
/// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the
/// provided element. If the asynchronous stream already terminated then this method will throw an error
/// indicating the failure.
///
/// This method returns once more elements should be produced.
///
/// - Parameters:
/// - sequence: The element to write to the asynchronous stream.
@inlinable
internal func write(_ element: Element) async throws {
try await self.write(contentsOf: CollectionOfOne(element))
}
/// Write the elements of the asynchronous sequence to the asynchronous stream.
///
/// This method returns once the provided asynchronous sequence or the the asynchronous stream finished.
///
/// - Important: This method does not finish the source if consuming the upstream sequence terminated.
///
/// - Parameters:
/// - sequence: The elements to write to the asynchronous stream.
@inlinable
internal func write<S>(contentsOf sequence: S) async throws
where Element == S.Element, S: AsyncSequence {
for try await element in sequence {
try await self.write(contentsOf: CollectionOfOne(element))
}
}
/// Indicates that the production terminated.
///
/// After all buffered elements are consumed the next iteration point will return `nil` or throw an error.
///
/// Calling this function more than once has no effect. After calling finish, the stream enters a terminal state and doesn't accept
/// new elements.
///
/// - Parameters:
/// - error: The error to throw, or `nil`, to finish normally.
@inlinable
internal func finish(throwing error: (any Error)?) {
self._backing.storage.finish(error)
}
}
/// Initializes a new ``BufferedStream`` and an ``BufferedStream/Source``.
///
/// - Parameters:
/// - elementType: The element type of the stream.
/// - failureType: The failure type of the stream.
/// - backPressureStrategy: The backpressure strategy that the stream should use.
/// - Returns: A tuple containing the stream and its source. The source should be passed to the
/// producer while the stream should be passed to the consumer.
@inlinable
internal static func makeStream(
of elementType: Element.Type = Element.self,
throwing failureType: any Error.Type = (any Error).self,
backPressureStrategy: Source.BackPressureStrategy
) -> (`Self`, Source) where any Error == any Error {
let storage = _BackPressuredStorage(
backPressureStrategy: backPressureStrategy._internalBackPressureStrategy
)
let source = Source(storage: storage)
return (.init(storage: storage), source)
}
@usableFromInline
init(storage: _BackPressuredStorage) {
self.implementation = .backpressured(.init(storage: storage))
}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension BufferedStream {
@usableFromInline
struct _WatermarkBackPressureStrategy: Sendable {
/// 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.
@usableFromInline
private(set) var _current: Int
/// Function to compute the contribution to the water level for a given element.
@usableFromInline
let _waterLevelForElement: (@Sendable (Element) -> Int)?
/// Initializes a new ``_WatermarkBackPressureStrategy``.
///
/// - Parameters:
/// - low: The low watermark where demand should start.
/// - high: The high watermark where demand should be stopped.
/// - waterLevelForElement: Function to compute the contribution to the water level for a given element.
@usableFromInline
init(low: Int, high: Int, waterLevelForElement: (@Sendable (Element) -> Int)? = nil) {
precondition(low <= high)
self._low = low
self._high = high
self._current = 0
self._waterLevelForElement = waterLevelForElement
}
@usableFromInline
mutating func didYield(elements: Deque<Element>.SubSequence) -> Bool {
if let waterLevelForElement = self._waterLevelForElement {
self._current += elements.reduce(0) { $0 + waterLevelForElement($1) }
} else {
self._current += elements.count
}
precondition(self._current >= 0, "Watermark below zero")
// We are demanding more until we reach the high watermark
return self._current < self._high
}
@usableFromInline
mutating func didConsume(elements: Deque<Element>.SubSequence) -> Bool {
if let waterLevelForElement = self._waterLevelForElement {
self._current -= elements.reduce(0) { $0 + waterLevelForElement($1) }
} else {
self._current -= elements.count
}
precondition(self._current >= 0, "Watermark below zero")
// We start demanding again once we are below the low watermark
return self._current < self._low
}
@usableFromInline
mutating func didConsume(element: Element) -> Bool {
if let waterLevelForElement = self._waterLevelForElement {
self._current -= waterLevelForElement(element)
} else {
self._current -= 1
}
precondition(self._current >= 0, "Watermark below zero")
// We start demanding again once we are below the low watermark
return self._current < self._low
}
}
@usableFromInline
enum _InternalBackPressureStrategy: Sendable {
case watermark(_WatermarkBackPressureStrategy)
@inlinable
mutating func didYield(elements: Deque<Element>.SubSequence) -> Bool {
switch self {
case .watermark(var strategy):
let result = strategy.didYield(elements: elements)
self = .watermark(strategy)
return result
}
}
@usableFromInline
mutating func didConsume(elements: Deque<Element>.SubSequence) -> Bool {
switch self {
case .watermark(var strategy):
let result = strategy.didConsume(elements: elements)
self = .watermark(strategy)
return result
}
}
@usableFromInline
mutating func didConsume(element: Element) -> Bool {
switch self {
case .watermark(var strategy):
let result = strategy.didConsume(element: element)
self = .watermark(strategy)
return result
}
}
}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension BufferedStream {
// We are unchecked Sendable since we are protecting our state with a lock.
@usableFromInline
final class _BackPressuredStorage: Sendable {
/// The state machine
@usableFromInline
let _stateMachine: _ManagedCriticalState<_StateMachine>
@usableFromInline
var onTermination: (@Sendable () -> Void)? {
set {
self._stateMachine.withCriticalRegion {
$0._onTermination = newValue
}
}
get {
self._stateMachine.withCriticalRegion {
$0._onTermination
}
}
}
@usableFromInline
init(
backPressureStrategy: _InternalBackPressureStrategy
) {
self._stateMachine = .init(.init(backPressureStrategy: backPressureStrategy))
}
@inlinable
func sequenceDeinitialized() {
let action = self._stateMachine.withCriticalRegion {
$0.sequenceDeinitialized()
}
switch action {
case .callOnTermination(let onTermination):
onTermination?()
case .failProducersAndCallOnTermination(let producerContinuations, let onTermination):
for producerContinuation in producerContinuations {
producerContinuation(.failure(AlreadyFinishedError()))
}
onTermination?()
case .none:
break
}
}
@inlinable
func iteratorInitialized() {
self._stateMachine.withCriticalRegion {
$0.iteratorInitialized()
}
}
@inlinable
func iteratorDeinitialized() {
let action = self._stateMachine.withCriticalRegion {
$0.iteratorDeinitialized()
}
switch action {
case .callOnTermination(let onTermination):
onTermination?()
case .failProducersAndCallOnTermination(let producerContinuations, let onTermination):
for producerContinuation in producerContinuations {
producerContinuation(.failure(AlreadyFinishedError()))
}
onTermination?()
case .none:
break
}
}
@inlinable
func sourceDeinitialized() {
let action = self._stateMachine.withCriticalRegion {
$0.sourceDeinitialized()
}
switch action {
case .callOnTermination(let onTermination):
onTermination?()
case .failProducersAndCallOnTermination(
let consumer,
let producerContinuations,
let onTermination
):
consumer?.resume(returning: nil)
for producerContinuation in producerContinuations {
producerContinuation(.failure(AlreadyFinishedError()))
}
onTermination?()
case .failProducers(let producerContinuations):
for producerContinuation in producerContinuations {
producerContinuation(.failure(AlreadyFinishedError()))
}
case .none:
break
}
}
@inlinable
func write(
contentsOf sequence: some Sequence<Element>
) throws -> Source.WriteResult {
let action = self._stateMachine.withCriticalRegion {
return $0.write(sequence)
}
switch action {
case .returnProduceMore:
return .produceMore
case .returnEnqueue(let callbackToken):
return .enqueueCallback(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(callbackToken)
case .throwFinishedError:
throw AlreadyFinishedError()
}
}
@inlinable
func enqueueProducer(
callbackToken: Source.WriteResult.CallbackToken,
onProduceMore: @escaping @Sendable (Result<Void, any Error>) -> Void
) {
let action = self._stateMachine.withCriticalRegion {
$0.enqueueProducer(callbackToken: callbackToken, onProduceMore: onProduceMore)
}
switch action {
case .resumeProducer(let onProduceMore):
onProduceMore(Result<Void, any Error>.success(()))
case .resumeProducerWithError(let onProduceMore, let error):
onProduceMore(Result<Void, any Error>.failure(error))
case .none:
break
}
}
@inlinable
func cancelProducer(callbackToken: Source.WriteResult.CallbackToken) {
let action = self._stateMachine.withCriticalRegion {
$0.cancelProducer(callbackToken: callbackToken)
}
switch action {
case .resumeProducerWithCancellationError(let onProduceMore):
onProduceMore(Result<Void, any Error>.failure(CancellationError()))
case .none:
break
}
}
@inlinable
func finish(_ failure: (any Error)?) {
let action = self._stateMachine.withCriticalRegion {
$0.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 {
producerContinuation(.failure(AlreadyFinishedError()))
}
case .none:
break
}
}
@inlinable
func next() async throws -> Element? {
let action = self._stateMachine.withCriticalRegion {
$0.next()
}
switch action {
case .returnElement(let element):
return element
case .returnElementAndResumeProducers(let element, let producerContinuations):
for producerContinuation in producerContinuations {
producerContinuation(Result<Void, any Error>.success(()))
}
return element
case .returnErrorAndCallOnTermination(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()
}
}
@inlinable
func suspendNext() async throws -> Element? {
return try await withTaskCancellationHandler {
return try await withCheckedThrowingContinuation { continuation in
let action = self._stateMachine.withCriticalRegion {
$0.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 {
producerContinuation(Result<Void, any Error>.success(()))
}
case .resumeConsumerWithErrorAndCallOnTermination(
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._stateMachine.withCriticalRegion {
$0.cancelNext()
}
switch action {
case .resumeConsumerWithCancellationErrorAndCallOnTermination(
let continuation,
let onTermination
):
continuation.resume(throwing: CancellationError())
onTermination?()
case .failProducersAndCallOnTermination(
let producerContinuations,
let onTermination
):
for producerContinuation in producerContinuations {
producerContinuation(.failure(AlreadyFinishedError()))
}
onTermination?()