File: BufferedStream.swift

package info (click to toggle)
swiftlang 6.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,532 kB
  • sloc: cpp: 9,901,743; ansic: 2,201,431; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (1736 lines) | stat: -rw-r--r-- 72,901 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2023 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
//
//===----------------------------------------------------------------------===//

#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Linux) || os(Android)
import DequeModule
import NIOConcurrencyHelpers

/// 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.0, watchOS 6.0, tvOS 13.0, *)
internal struct BufferedStream<Element> {
    final class _Backing: Sendable {
        let storage: _BackPressuredStorage

        init(storage: _BackPressuredStorage) {
            self.storage = storage
        }

        deinit {
            self.storage.sequenceDeinitialized()
        }
    }

    enum _Implementation: Sendable {
        /// This is the implementation with backpressure based on the Source
        case backpressured(_Backing)
    }

    let implementation: _Implementation
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
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()`.
    internal struct Iterator: AsyncIteratorProtocol {
        final class _Backing {
            let storage: _BackPressuredStorage

            init(storage: _BackPressuredStorage) {
                self.storage = storage
                self.storage.iteratorInitialized()
            }

            deinit {
                self.storage.iteratorDeinitialized()
            }
        }
        enum _Implementation {
            /// This is the implementation with backpressure based on the Source
            case backpressured(_Backing)
        }

        var 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.
        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.
    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.0, watchOS 6.0, tvOS 13.0, *)
extension BufferedStream: Sendable where Element: Sendable {}

internal struct _ManagedCriticalState<State>: @unchecked Sendable {
    let lock: NIOLockedValueBox<State>

    internal init(_ initial: State) {
        self.lock = .init(initial)
    }

    internal func withCriticalRegion<R>(
        _ critical: (inout State) throws -> R
    ) rethrows -> R {
        try self.lock.withLockedValue(critical)
    }
}

internal struct AlreadyFinishedError: Error {}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
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.
    internal struct Source: Sendable {
        /// A strategy that handles the backpressure of the asynchronous stream.
        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.
            internal static func watermark(low: Int, high: Int) -> BackPressureStrategy {
                BackPressureStrategy(
                    internalBackPressureStrategy: .watermark(.init(low: low, high: high))
                )
            }

            private init(internalBackPressureStrategy: _InternalBackPressureStrategy) {
                self._internalBackPressureStrategy = internalBackPressureStrategy
            }

            fileprivate let _internalBackPressureStrategy: _InternalBackPressureStrategy
        }

        /// A type that indicates the result of writing elements to the source.
        @frozen
        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.
            internal struct CallbackToken: Sendable {
                let id: UInt
            }

            /// 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.
        final class _Backing: Sendable {
            let storage: _BackPressuredStorage

            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
        internal var onTermination: (@Sendable () -> Void)? {
            set {
                self._backing.storage.onTermination = newValue
            }
            get {
                self._backing.storage.onTermination
            }
        }

        private var _backing: _Backing

        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.
        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.
        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.
        internal func enqueueCallback(
            callbackToken: WriteResult.CallbackToken,
            onProduceMore: @escaping @Sendable (Result<Void, 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.
        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:)``.
        internal func write<S>(
            contentsOf sequence: S,
            onProduceMore: @escaping @Sendable (Result<Void, Error>) -> Void
        ) where Element == S.Element, S: Sequence {
            do {
                let writeResult = try self.write(contentsOf: sequence)

                switch writeResult {
                case .produceMore:
                    onProduceMore(Result<Void, 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:)``.
        internal func write(
            _ element: Element,
            onProduceMore: @escaping @Sendable (Result<Void, 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.
        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.
        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.
        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.
        internal func finish(throwing error: 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.
    internal static func makeStream(
        of elementType: Element.Type = Element.self,
        throwing failureType: Error.Type = Error.self,
        backPressureStrategy: Source.BackPressureStrategy
    ) -> (`Self`, Source) where Error == Error {
        let storage = _BackPressuredStorage(
            backPressureStrategy: backPressureStrategy._internalBackPressureStrategy
        )
        let source = Source(storage: storage)

        return (.init(storage: storage), source)
    }

    init(storage: _BackPressuredStorage) {
        self.implementation = .backpressured(.init(storage: storage))
    }
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension BufferedStream {
    struct _WatermarkBackPressureStrategy {
        /// The low watermark where demand should start.
        private let _low: Int
        /// The high watermark where demand should be stopped.
        private let _high: Int

        /// Initializes a new ``_WatermarkBackPressureStrategy``.
        ///
        /// - Parameters:
        ///   - low: The low watermark where demand should start.
        ///   - high: The high watermark where demand should be stopped.
        init(low: Int, high: Int) {
            precondition(low <= high)
            self._low = low
            self._high = high
        }

        func didYield(bufferDepth: Int) -> Bool {
            // We are demanding more until we reach the high watermark
            return bufferDepth < self._high
        }

        func didConsume(bufferDepth: Int) -> Bool {
            // We start demanding again once we are below the low watermark
            return bufferDepth < self._low
        }
    }

    enum _InternalBackPressureStrategy {
        case watermark(_WatermarkBackPressureStrategy)

        mutating func didYield(bufferDepth: Int) -> Bool {
            switch self {
            case .watermark(let strategy):
                return strategy.didYield(bufferDepth: bufferDepth)
            }
        }

        mutating func didConsume(bufferDepth: Int) -> Bool {
            switch self {
            case .watermark(let strategy):
                return strategy.didConsume(bufferDepth: bufferDepth)
            }
        }
    }
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension BufferedStream {
    // We are unchecked Sendable since we are protecting our state with a lock.
    final class _BackPressuredStorage: Sendable {
        /// The state machine
        let _stateMachine: _ManagedCriticalState<_StateMachine>

        var onTermination: (@Sendable () -> Void)? {
            set {
                self._stateMachine.withCriticalRegion {
                    $0._onTermination = newValue
                }
            }
            get {
                self._stateMachine.withCriticalRegion {
                    $0._onTermination
                }
            }
        }

        init(
            backPressureStrategy: _InternalBackPressureStrategy
        ) {
            self._stateMachine = .init(.init(backPressureStrategy: backPressureStrategy))
        }

        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
            }
        }

        func iteratorInitialized() {
            self._stateMachine.withCriticalRegion {
                $0.iteratorInitialized()
            }
        }

        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
            }
        }

        func sourceDeinitialized() {
            let action = self._stateMachine.withCriticalRegion {
                $0.sourceDeinitialized()
            }

            switch action {
            case .callOnTermination(let onTermination):
                onTermination?()

            case .failProducersAndCallOnTermination(let producerContinuations, let onTermination):
                for producerContinuation in producerContinuations {
                    producerContinuation(.failure(AlreadyFinishedError()))
                }
                onTermination?()

            case .failProducers(let producerContinuations):
                for producerContinuation in producerContinuations {
                    producerContinuation(.failure(AlreadyFinishedError()))
                }

            case .none:
                break
            }
        }

        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()
            }
        }

        func enqueueProducer(
            callbackToken: Source.WriteResult.CallbackToken,
            onProduceMore: @escaping @Sendable (Result<Void, Error>) -> Void
        ) {
            let action = self._stateMachine.withCriticalRegion {
                $0.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
            }
        }

        func cancelProducer(callbackToken: Source.WriteResult.CallbackToken) {
            let action = self._stateMachine.withCriticalRegion {
                $0.cancelProducer(callbackToken: callbackToken)
            }

            switch action {
            case .resumeProducerWithCancellationError(let onProduceMore):
                onProduceMore(Result<Void, Error>.failure(CancellationError()))

            case .none:
                break
            }
        }

        func finish(_ failure: 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
            }
        }

        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, 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()
            }
        }

        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, 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?()

                case .none:
                    break
                }
            }
        }
    }
}

@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension BufferedStream {
    /// The state machine of the backpressured async stream.
    struct _StateMachine {
        enum _State {
            struct Initial {
                /// The backpressure strategy.
                var backPressureStrategy: _InternalBackPressureStrategy
                /// Indicates if the iterator was initialized.
                var iteratorInitialized: Bool
                /// The onTermination callback.
                var onTermination: (@Sendable () -> Void)?
            }

            struct Streaming {
                /// The backpressure strategy.
                var backPressureStrategy: _InternalBackPressureStrategy
                /// Indicates if the iterator was initialized.
                var iteratorInitialized: Bool
                /// The onTermination callback.
                var onTermination: (@Sendable () -> Void)?
                /// The buffer of elements.
                var buffer: Deque<Element>
                /// The optional consumer continuation.
                var consumerContinuation: CheckedContinuation<Element?, Error>?
                /// The producer continuations.
                var producerContinuations: Deque<(UInt, (Result<Void, Error>) -> Void)>
                /// The producers that have been cancelled.
                var cancelledAsyncProducers: Deque<UInt>
                /// Indicates if we currently have outstanding demand.
                var hasOutstandingDemand: Bool
            }

            struct SourceFinished {
                /// Indicates if the iterator was initialized.
                var iteratorInitialized: Bool
                /// The buffer of elements.
                var buffer: Deque<Element>
                /// The failure that should be thrown after the last element has been consumed.
                var failure: Error?
                /// The onTermination callback.
                var onTermination: (@Sendable () -> Void)?
            }

            case initial(Initial)
            /// The state once either any element was yielded or `next()` was called.
            case streaming(Streaming)
            /// The state once the underlying source signalled that it is finished.
            case sourceFinished(SourceFinished)

            /// The state once there can be no outstanding demand. This can happen if:
            /// 1. The iterator was deinited
            /// 2. The underlying source finished and all buffered elements have been consumed
            case finished(iteratorInitialized: Bool)

            /// An intermediate state to avoid CoWs.
            case modify
        }

        /// The state machine's current state.
        var _state: _State

        // The ID used for the next CallbackToken.
        var nextCallbackTokenID: UInt = 0

        var _onTermination: (@Sendable () -> Void)? {
            set {
                switch self._state {
                case .initial(var initial):
                    initial.onTermination = newValue
                    self._state = .initial(initial)

                case .streaming(var streaming):
                    streaming.onTermination = newValue
                    self._state = .streaming(streaming)

                case .sourceFinished(var sourceFinished):
                    sourceFinished.onTermination = newValue
                    self._state = .sourceFinished(sourceFinished)

                case .finished:
                    break

                case .modify:
                    fatalError("AsyncStream internal inconsistency")
                }
            }
            get {
                switch self._state {
                case .initial(let initial):
                    return initial.onTermination

                case .streaming(let streaming):
                    return streaming.onTermination

                case .sourceFinished(let sourceFinished):
                    return sourceFinished.onTermination

                case .finished:
                    return nil

                case .modify:
                    fatalError("AsyncStream internal inconsistency")
                }
            }
        }

        /// Initializes a new `StateMachine`.
        ///
        /// We are passing and holding the back-pressure strategy here because
        /// it is a customizable extension of the state machine.
        ///
        /// - Parameter backPressureStrategy: The back-pressure strategy.
        init(
            backPressureStrategy: _InternalBackPressureStrategy
        ) {
            self._state = .initial(
                .init(
                    backPressureStrategy: backPressureStrategy,
                    iteratorInitialized: false,
                    onTermination: nil
                )
            )
        }

        /// Generates the next callback token.
        mutating func nextCallbackToken() -> Source.WriteResult.CallbackToken {
            let id = self.nextCallbackTokenID
            self.nextCallbackTokenID += 1
            return .init(id: id)
        }

        /// Actions returned by `sequenceDeinitialized()`.
        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(
                [(Result<Void, Error>) -> Void],
                (@Sendable () -> Void)?
            )
        }

        mutating func sequenceDeinitialized() -> SequenceDeinitializedAction? {
            switch self._state {
            case .initial(let initial):
                if initial.iteratorInitialized {
                    // An iterator was created and we deinited the sequence.
                    // This is an expected pattern and we just continue on normal.
                    return .none
                } else {
                    // No iterator was created so we can transition to finished right away.
                    self._state = .finished(iteratorInitialized: false)

                    return .callOnTermination(initial.onTermination)
                }

            case .streaming(let streaming):
                if streaming.iteratorInitialized {
                    // An iterator was created and we deinited the sequence.
                    // This is an expected pattern and we just continue on normal.
                    return .none
                } else {
                    // No iterator was created so we can transition to finished right away.
                    self._state = .finished(iteratorInitialized: false)

                    return .failProducersAndCallOnTermination(
                        Array(streaming.producerContinuations.map { $0.1 }),
                        streaming.onTermination
                    )
                }

            case .sourceFinished(let sourceFinished):
                if sourceFinished.iteratorInitialized {
                    // An iterator was created and we deinited the sequence.
                    // This is an expected pattern and we just continue on normal.
                    return .none
                } else {
                    // No iterator was created so we can transition to finished right away.
                    self._state = .finished(iteratorInitialized: false)

                    return .callOnTermination(sourceFinished.onTermination)
                }

            case .finished:
                // We are already finished so there is nothing left to clean up.
                // This is just the references dropping afterwards.
                return .none

            case .modify:
                fatalError("AsyncStream internal inconsistency")
            }
        }

        mutating func iteratorInitialized() {
            switch self._state {
            case .initial(var initial):
                if initial.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.
                    initial.iteratorInitialized = true
                    self._state = .initial(initial)
                }

            case .streaming(var streaming):
                if streaming.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.
                    streaming.iteratorInitialized = true
                    self._state = .streaming(streaming)
                }

            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._state = .sourceFinished(sourceFinished)
                }

            case .finished(iteratorInitialized: true):
                // Our sequence is a unicast sequence and does not support multiple AsyncIterator's
                fatalError("Only a single AsyncIterator can be created")

            case .finished(iteratorInitialized: false):
                // It is strange that an iterator is created after we are finished
                // but it can definitely happen, e.g.
                // Sequence.init -> source.finish -> sequence.makeAsyncIterator
                self._state = .finished(iteratorInitialized: true)

            case .modify:
                fatalError("AsyncStream internal inconsistency")
            }
        }

        /// Actions returned by `iteratorDeinitialized()`.
        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(
                [(Result<Void, Error>) -> Void],
                (@Sendable () -> Void)?
            )
        }

        mutating func iteratorDeinitialized() -> IteratorDeinitializedAction? {
            switch self._state {
            case .initial(let initial):
                if initial.iteratorInitialized {
                    // An iterator was created and deinited. Since we only support
                    // a single iterator we can now transition to finish.
                    self._state = .finished(iteratorInitialized: true)
                    return .callOnTermination(initial.onTermination)
                } else {
                    // An iterator needs to be initialized before it can be deinitialized.
                    fatalError("AsyncStream internal inconsistency")
                }

            case .streaming(let streaming):
                if streaming.iteratorInitialized {
                    // An iterator was created and deinited. Since we only support
                    // a single iterator we can now transition to finish.
                    self._state = .finished(iteratorInitialized: true)

                    return .failProducersAndCallOnTermination(
                        Array(streaming.producerContinuations.map { $0.1 }),
                        streaming.onTermination
                    )
                } else {
                    // An iterator needs to be initialized before it can be deinitialized.
                    fatalError("AsyncStream 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._state = .finished(iteratorInitialized: true)
                    return .callOnTermination(sourceFinished.onTermination)
                } else {
                    // An iterator needs to be initialized before it can be deinitialized.
                    fatalError("AsyncStream internal inconsistency")
                }

            case .finished:
                // We are already finished so there is nothing left to clean up.
                // This is just the references dropping afterwards.
                return .none

            case .modify:
                fatalError("AsyncStream internal inconsistency")
            }
        }

        /// Actions returned by `sourceDeinitialized()`.
        enum SourceDeinitializedAction {
            /// Indicates that `onTermination` should be called.
            case callOnTermination((() -> Void)?)
            /// Indicates that  all producers should be failed and `onTermination` should be called.
            case failProducersAndCallOnTermination(
                [(Result<Void, Error>) -> Void],
                (@Sendable () -> Void)?
            )
            /// Indicates that all producers should be failed.
            case failProducers([(Result<Void, Error>) -> Void])
        }

        mutating func sourceDeinitialized() -> SourceDeinitializedAction? {
            switch self._state {
            case .initial(let initial):
                // The source got deinited before anything was written
                self._state = .finished(iteratorInitialized: initial.iteratorInitialized)
                return .callOnTermination(initial.onTermination)

            case .streaming(let streaming):
                if streaming.buffer.isEmpty {
                    // We can transition to finished right away since the buffer is empty now
                    self._state = .finished(iteratorInitialized: streaming.iteratorInitialized)

                    return .failProducersAndCallOnTermination(
                        Array(streaming.producerContinuations.map { $0.1 }),
                        streaming.onTermination
                    )
                } else {
                    // The continuation must be `nil` if the buffer has elements
                    precondition(streaming.consumerContinuation == nil)

                    self._state = .sourceFinished(
                        .init(
                            iteratorInitialized: streaming.iteratorInitialized,
                            buffer: streaming.buffer,
                            failure: nil,
                            onTermination: streaming.onTermination
                        )
                    )

                    return .failProducers(
                        Array(streaming.producerContinuations.map { $0.1 })
                    )
                }

            case .sourceFinished, .finished:
                // This is normal and we just have to tolerate it
                return .none

            case .modify:
                fatalError("AsyncStream internal inconsistency")
            }
        }

        /// Actions returned by `write()`.
        enum WriteAction {
            /// 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: Source.WriteResult.CallbackToken
            )
            /// Indicates that the consumer should be resumed and the producer should be notified to produce more.
            case resumeConsumerAndReturnProduceMore(
                continuation: CheckedContinuation<Element?, Error>,
                element: Element
            )
            /// Indicates that the consumer should be resumed and the producer should be suspended.
            case resumeConsumerAndReturnEnqueue(
                continuation: CheckedContinuation<Element?, Error>,
                element: Element,
                callbackToken: Source.WriteResult.CallbackToken
            )
            /// Indicates that the producer has been finished.
            case throwFinishedError

            init(
                callbackToken: Source.WriteResult.CallbackToken?,
                continuationAndElement: (CheckedContinuation<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
                    )
                }
            }
        }

        mutating func write(_ sequence: some Sequence<Element>) -> WriteAction {
            switch self._state {
            case .initial(var initial):
                var buffer = Deque<Element>()
                buffer.append(contentsOf: sequence)

                let shouldProduceMore = initial.backPressureStrategy.didYield(
                    bufferDepth: buffer.count
                )
                let callbackToken = shouldProduceMore ? nil : self.nextCallbackToken()

                self._state = .streaming(
                    .init(
                        backPressureStrategy: initial.backPressureStrategy,
                        iteratorInitialized: initial.iteratorInitialized,
                        onTermination: initial.onTermination,
                        buffer: buffer,
                        consumerContinuation: nil,
                        producerContinuations: .init(),
                        cancelledAsyncProducers: .init(),
                        hasOutstandingDemand: shouldProduceMore
                    )
                )

                return .init(callbackToken: callbackToken)

            case .streaming(var streaming):
                self._state = .modify

                streaming.buffer.append(contentsOf: sequence)

                // We have an element and can resume the continuation
                let shouldProduceMore = streaming.backPressureStrategy.didYield(
                    bufferDepth: streaming.buffer.count
                )
                streaming.hasOutstandingDemand = shouldProduceMore
                let callbackToken = shouldProduceMore ? nil : self.nextCallbackToken()

                if let consumerContinuation = streaming.consumerContinuation {
                    guard let element = streaming.buffer.popFirst() else {
                        // We got a yield of an empty sequence. We just tolerate this.
                        self._state = .streaming(streaming)

                        return .init(callbackToken: callbackToken)
                    }

                    // We got a consumer continuation and an element. We can resume the consumer now
                    streaming.consumerContinuation = nil
                    self._state = .streaming(streaming)
                    return .init(
                        callbackToken: callbackToken,
                        continuationAndElement: (consumerContinuation, element)
                    )
                } else {
                    // We don't have a suspended consumer so we just buffer the elements
                    self._state = .streaming(streaming)
                    return .init(
                        callbackToken: callbackToken
                    )
                }

            case .sourceFinished, .finished:
                // If the source has finished we are dropping the elements.
                return .throwFinishedError

            case .modify:
                fatalError("AsyncStream internal inconsistency")
            }
        }

        /// Actions returned by `enqueueProducer()`.
        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)
        }

        mutating func enqueueProducer(
            callbackToken: Source.WriteResult.CallbackToken,
            onProduceMore: @Sendable @escaping (Result<Void, Error>) -> Void
        ) -> EnqueueProducerAction? {
            switch self._state {
            case .initial:
                // We need to transition to streaming before we can suspend
                // This is enforced because the CallbackToken has no internal init so
                // one must create it by calling `write` first.
                fatalError("AsyncStream internal inconsistency")

            case .streaming(var streaming):
                if let index = streaming.cancelledAsyncProducers.firstIndex(of: callbackToken.id) {
                    // Our producer got marked as cancelled.
                    self._state = .modify
                    streaming.cancelledAsyncProducers.remove(at: index)
                    self._state = .streaming(streaming)

                    return .resumeProducerWithError(onProduceMore, CancellationError())
                } else if streaming.hasOutstandingDemand {
                    // We hit an edge case here where we wrote but the consuming thread got interleaved
                    return .resumeProducer(onProduceMore)
                } else {
                    self._state = .modify
                    streaming.producerContinuations.append((callbackToken.id, onProduceMore))

                    self._state = .streaming(streaming)
                    return .none
                }

            case .sourceFinished, .finished:
                // Since we are unlocking between yielding and suspending the yield
                // It can happen that the source got finished or the consumption fully finishes.
                return .resumeProducerWithError(onProduceMore, AlreadyFinishedError())

            case .modify:
                fatalError("AsyncStream internal inconsistency")
            }
        }

        /// Actions returned by `cancelProducer()`.
        enum CancelProducerAction {
            /// Indicates that the producer should be notified about cancellation.
            case resumeProducerWithCancellationError((Result<Void, Error>) -> Void)
        }

        mutating func cancelProducer(
            callbackToken: Source.WriteResult.CallbackToken
        ) -> CancelProducerAction? {
            switch self._state {
            case .initial:
                // We need to transition to streaming before we can suspend
                fatalError("AsyncStream internal inconsistency")

            case .streaming(var streaming):
                if let index = streaming.producerContinuations.firstIndex(where: {
                    $0.0 == callbackToken.id
                }) {
                    // We have an enqueued producer that we need to resume now
                    self._state = .modify
                    let continuation = streaming.producerContinuations.remove(at: index).1
                    self._state = .streaming(streaming)

                    return .resumeProducerWithCancellationError(continuation)
                } else {
                    // The task that yields was cancelled before yielding so the cancellation handler
                    // got invoked right away
                    self._state = .modify
                    streaming.cancelledAsyncProducers.append(callbackToken.id)
                    self._state = .streaming(streaming)

                    return .none
                }

            case .sourceFinished, .finished:
                // Since we are unlocking between yielding and suspending the yield
                // It can happen that the source got finished or the consumption fully finishes.
                return .none

            case .modify:
                fatalError("AsyncStream internal inconsistency")
            }
        }

        /// Actions returned by `finish()`.
        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: CheckedContinuation<Element?, Error>,
                failure: Error?,
                onTermination: (() -> Void)?
            )
            /// Indicates that the producers should be resumed with an error.
            case resumeProducers(
                producerContinuations: [(Result<Void, Error>) -> Void]
            )
        }

        @inlinable
        mutating func finish(_ failure: Error?) -> FinishAction? {
            switch self._state {
            case .initial(let initial):
                // Nothing was yielded nor did anybody call next
                // This means we can transition to sourceFinished and store the failure
                self._state = .sourceFinished(
                    .init(
                        iteratorInitialized: initial.iteratorInitialized,
                        buffer: .init(),
                        failure: failure,
                        onTermination: initial.onTermination
                    )
                )

                return .callOnTermination(initial.onTermination)

            case .streaming(let streaming):
                if let consumerContinuation = streaming.consumerContinuation {
                    // We have a continuation, this means our buffer must be empty
                    // Furthermore, we can now transition to finished
                    // and resume the continuation with the failure
                    precondition(streaming.buffer.isEmpty, "Expected an empty buffer")
                    precondition(
                        streaming.producerContinuations.isEmpty,
                        "Expected no suspended producers"
                    )

                    self._state = .finished(iteratorInitialized: streaming.iteratorInitialized)

                    return .resumeConsumerAndCallOnTermination(
                        consumerContinuation: consumerContinuation,
                        failure: failure,
                        onTermination: streaming.onTermination
                    )
                } else {
                    self._state = .sourceFinished(
                        .init(
                            iteratorInitialized: streaming.iteratorInitialized,
                            buffer: streaming.buffer,
                            failure: failure,
                            onTermination: streaming.onTermination
                        )
                    )

                    return .resumeProducers(
                        producerContinuations: Array(streaming.producerContinuations.map { $0.1 })
                    )
                }

            case .sourceFinished, .finished:
                // If the source has finished, finishing again has no effect.
                return .none

            case .modify:
                fatalError("AsyncStream internal inconsistency")
            }
        }

        /// Actions returned by `next()`.
        enum NextAction {
            /// Indicates that the element should be returned to the caller.
            case returnElement(Element)
            /// Indicates that the element should be returned to the caller and that all producers should be called.
            case returnElementAndResumeProducers(Element, [(Result<Void, Error>) -> Void])
            /// Indicates that the `Error` should be returned to the caller and that `onTermination` should be called.
            case returnErrorAndCallOnTermination(Error?, (() -> Void)?)
            /// Indicates that the `nil` should be returned to the caller.
            case returnNil
            /// Indicates that the `Task` of the caller should be suspended.
            case suspendTask
        }

        mutating func next() -> NextAction {
            switch self._state {
            case .initial(let initial):
                // We are not interacting with the back-pressure strategy here because
                // we are doing this inside `next(:)`
                self._state = .streaming(
                    .init(
                        backPressureStrategy: initial.backPressureStrategy,
                        iteratorInitialized: initial.iteratorInitialized,
                        onTermination: initial.onTermination,
                        buffer: Deque<Element>(),
                        consumerContinuation: nil,
                        producerContinuations: .init(),
                        cancelledAsyncProducers: .init(),
                        hasOutstandingDemand: false
                    )
                )

                return .suspendTask
            case .streaming(var streaming):
                guard streaming.consumerContinuation == nil else {
                    // We have multiple AsyncIterators iterating the sequence
                    fatalError("AsyncStream internal inconsistency")
                }

                self._state = .modify

                if let element = streaming.buffer.popFirst() {
                    // We have an element to fulfil the demand right away.
                    let shouldProduceMore = streaming.backPressureStrategy.didConsume(
                        bufferDepth: streaming.buffer.count
                    )
                    streaming.hasOutstandingDemand = shouldProduceMore

                    if shouldProduceMore {
                        // There is demand and we have to resume our producers
                        let producers = Array(streaming.producerContinuations.map { $0.1 })
                        streaming.producerContinuations.removeAll()
                        self._state = .streaming(streaming)
                        return .returnElementAndResumeProducers(element, producers)
                    } else {
                        // We don't have any new demand, so we can just return the element.
                        self._state = .streaming(streaming)
                        return .returnElement(element)
                    }
                } else {
                    // There is nothing in the buffer to fulfil the demand so we need to suspend.
                    // We are not interacting with the back-pressure strategy here because
                    // we are doing this inside `suspendNext`
                    self._state = .streaming(streaming)

                    return .suspendTask
                }

            case .sourceFinished(var sourceFinished):
                // Check if we have an element left in the buffer and return it
                self._state = .modify

                if let element = sourceFinished.buffer.popFirst() {
                    self._state = .sourceFinished(sourceFinished)

                    return .returnElement(element)
                } else {
                    // We are returning the queued failure now and can transition to finished
                    self._state = .finished(iteratorInitialized: sourceFinished.iteratorInitialized)

                    return .returnErrorAndCallOnTermination(
                        sourceFinished.failure,
                        sourceFinished.onTermination
                    )
                }

            case .finished:
                return .returnNil

            case .modify:
                fatalError("AsyncStream internal inconsistency")
            }
        }

        /// Actions returned by `suspendNext()`.
        enum SuspendNextAction {
            /// Indicates that the consumer should be resumed.
            case resumeConsumerWithElement(CheckedContinuation<Element?, Error>, Element)
            /// Indicates that the consumer and all producers should be resumed.
            case resumeConsumerWithElementAndProducers(
                CheckedContinuation<Element?, Error>,
                Element,
                [(Result<Void, Error>) -> Void]
            )
            /// Indicates that the consumer should be resumed with the failure and that `onTermination` should be called.
            case resumeConsumerWithErrorAndCallOnTermination(
                CheckedContinuation<Element?, Error>,
                Error?,
                (() -> Void)?
            )
            /// Indicates that the consumer should be resumed with `nil`.
            case resumeConsumerWithNil(CheckedContinuation<Element?, Error>)
        }

        mutating func suspendNext(
            continuation: CheckedContinuation<Element?, Error>
        ) -> SuspendNextAction? {
            switch self._state {
            case .initial:
                // We need to transition to streaming before we can suspend
                preconditionFailure("AsyncStream internal inconsistency")

            case .streaming(var streaming):
                guard streaming.consumerContinuation == nil else {
                    // We have multiple AsyncIterators iterating the sequence
                    fatalError(
                        "This should never happen since we only allow a single Iterator to be created"
                    )
                }

                self._state = .modify

                // We have to check here again since we might have a producer interleave next and suspendNext
                if let element = streaming.buffer.popFirst() {
                    // We have an element to fulfil the demand right away.

                    let shouldProduceMore = streaming.backPressureStrategy.didConsume(
                        bufferDepth: streaming.buffer.count
                    )
                    streaming.hasOutstandingDemand = shouldProduceMore

                    if shouldProduceMore {
                        // There is demand and we have to resume our producers
                        let producers = Array(streaming.producerContinuations.map { $0.1 })
                        streaming.producerContinuations.removeAll()
                        self._state = .streaming(streaming)
                        return .resumeConsumerWithElementAndProducers(
                            continuation,
                            element,
                            producers
                        )
                    } else {
                        // We don't have any new demand, so we can just return the element.
                        self._state = .streaming(streaming)
                        return .resumeConsumerWithElement(continuation, element)
                    }
                } else {
                    // There is nothing in the buffer to fulfil the demand so we to store the continuation.
                    streaming.consumerContinuation = continuation
                    self._state = .streaming(streaming)

                    return .none
                }

            case .sourceFinished(var sourceFinished):
                // Check if we have an element left in the buffer and return it
                self._state = .modify

                if let element = sourceFinished.buffer.popFirst() {
                    self._state = .sourceFinished(sourceFinished)

                    return .resumeConsumerWithElement(continuation, element)
                } else {
                    // We are returning the queued failure now and can transition to finished
                    self._state = .finished(iteratorInitialized: sourceFinished.iteratorInitialized)

                    return .resumeConsumerWithErrorAndCallOnTermination(
                        continuation,
                        sourceFinished.failure,
                        sourceFinished.onTermination
                    )
                }

            case .finished:
                return .resumeConsumerWithNil(continuation)

            case .modify:
                fatalError("AsyncStream internal inconsistency")
            }
        }

        /// Actions returned by `cancelNext()`.
        enum CancelNextAction {
            /// Indicates that the continuation should be resumed with a cancellation error, the producers should be finished and call onTermination.
            case resumeConsumerWithCancellationErrorAndCallOnTermination(
                CheckedContinuation<Element?, Error>,
                (() -> Void)?
            )
            /// Indicates that the producers should be finished and call onTermination.
            case failProducersAndCallOnTermination([(Result<Void, Error>) -> Void], (() -> Void)?)
        }

        mutating func cancelNext() -> CancelNextAction? {
            switch self._state {
            case .initial:
                // We need to transition to streaming before we can suspend
                fatalError("AsyncStream internal inconsistency")

            case .streaming(let streaming):
                self._state = .finished(iteratorInitialized: streaming.iteratorInitialized)

                if let consumerContinuation = streaming.consumerContinuation {
                    precondition(
                        streaming.producerContinuations.isEmpty,
                        "Internal inconsistency. Unexpected producer continuations."
                    )
                    return .resumeConsumerWithCancellationErrorAndCallOnTermination(
                        consumerContinuation,
                        streaming.onTermination
                    )
                } else {
                    return .failProducersAndCallOnTermination(
                        Array(streaming.producerContinuations.map { $0.1 }),
                        streaming.onTermination
                    )
                }

            case .sourceFinished, .finished:
                return .none

            case .modify:
                fatalError("AsyncStream internal inconsistency")
            }
        }
    }
}

#endif