BufferedStream.swift 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934
  1. /*
  2. * Copyright 2021, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. //===----------------------------------------------------------------------===//
  17. //
  18. // This source file is part of the Swift.org open source project
  19. //
  20. // Copyright (c) 2020-2021 Apple Inc. and the Swift project authors
  21. // Licensed under Apache License v2.0 with Runtime Library Exception
  22. //
  23. // See https://swift.org/LICENSE.txt for license information
  24. // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
  25. //
  26. //===----------------------------------------------------------------------===//
  27. import DequeModule
  28. /// An asynchronous sequence generated from an error-throwing closure that
  29. /// calls a continuation to produce new elements.
  30. ///
  31. /// `BufferedStream` conforms to `AsyncSequence`, providing a convenient
  32. /// way to create an asynchronous sequence without manually implementing an
  33. /// asynchronous iterator. In particular, an asynchronous stream is well-suited
  34. /// to adapt callback- or delegation-based APIs to participate with
  35. /// `async`-`await`.
  36. ///
  37. /// In contrast to `AsyncStream`, this type can throw an error from the awaited
  38. /// `next()`, which terminates the stream with the thrown error.
  39. ///
  40. /// You initialize an `BufferedStream` with a closure that receives an
  41. /// `BufferedStream.Continuation`. Produce elements in this closure, then
  42. /// provide them to the stream by calling the continuation's `yield(_:)` method.
  43. /// When there are no further elements to produce, call the continuation's
  44. /// `finish()` method. This causes the sequence iterator to produce a `nil`,
  45. /// which terminates the sequence. If an error occurs, call the continuation's
  46. /// `finish(throwing:)` method, which causes the iterator's `next()` method to
  47. /// throw the error to the awaiting call point. The continuation is `Sendable`,
  48. /// which permits calling it from concurrent contexts external to the iteration
  49. /// of the `BufferedStream`.
  50. ///
  51. /// An arbitrary source of elements can produce elements faster than they are
  52. /// consumed by a caller iterating over them. Because of this, `BufferedStream`
  53. /// defines a buffering behavior, allowing the stream to buffer a specific
  54. /// number of oldest or newest elements. By default, the buffer limit is
  55. /// `Int.max`, which means it's unbounded.
  56. ///
  57. /// ### Adapting Existing Code to Use Streams
  58. ///
  59. /// To adapt existing callback code to use `async`-`await`, use the callbacks
  60. /// to provide values to the stream, by using the continuation's `yield(_:)`
  61. /// method.
  62. ///
  63. /// Consider a hypothetical `QuakeMonitor` type that provides callers with
  64. /// `Quake` instances every time it detects an earthquake. To receive callbacks,
  65. /// callers set a custom closure as the value of the monitor's
  66. /// `quakeHandler` property, which the monitor calls back as necessary. Callers
  67. /// can also set an `errorHandler` to receive asynchronous error notifications,
  68. /// such as the monitor service suddenly becoming unavailable.
  69. ///
  70. /// class QuakeMonitor {
  71. /// var quakeHandler: ((Quake) -> Void)?
  72. /// var errorHandler: ((Error) -> Void)?
  73. ///
  74. /// func startMonitoring() {…}
  75. /// func stopMonitoring() {…}
  76. /// }
  77. ///
  78. /// To adapt this to use `async`-`await`, extend the `QuakeMonitor` to add a
  79. /// `quakes` property, of type `BufferedStream<Quake>`. In the getter for
  80. /// this property, return an `BufferedStream`, whose `build` closure --
  81. /// called at runtime to create the stream -- uses the continuation to
  82. /// perform the following steps:
  83. ///
  84. /// 1. Creates a `QuakeMonitor` instance.
  85. /// 2. Sets the monitor's `quakeHandler` property to a closure that receives
  86. /// each `Quake` instance and forwards it to the stream by calling the
  87. /// continuation's `yield(_:)` method.
  88. /// 3. Sets the monitor's `errorHandler` property to a closure that receives
  89. /// any error from the monitor and forwards it to the stream by calling the
  90. /// continuation's `finish(throwing:)` method. This causes the stream's
  91. /// iterator to throw the error and terminate the stream.
  92. /// 4. Sets the continuation's `onTermination` property to a closure that
  93. /// calls `stopMonitoring()` on the monitor.
  94. /// 5. Calls `startMonitoring` on the `QuakeMonitor`.
  95. ///
  96. /// ```
  97. /// extension QuakeMonitor {
  98. ///
  99. /// static var throwingQuakes: BufferedStream<Quake, any Error> {
  100. /// BufferedStream { continuation in
  101. /// let monitor = QuakeMonitor()
  102. /// monitor.quakeHandler = { quake in
  103. /// continuation.yield(quake)
  104. /// }
  105. /// monitor.errorHandler = { error in
  106. /// continuation.finish(throwing: error)
  107. /// }
  108. /// continuation.onTermination = { @Sendable _ in
  109. /// monitor.stopMonitoring()
  110. /// }
  111. /// monitor.startMonitoring()
  112. /// }
  113. /// }
  114. /// }
  115. /// ```
  116. ///
  117. ///
  118. /// Because the stream is an `AsyncSequence`, the call point uses the
  119. /// `for`-`await`-`in` syntax to process each `Quake` instance as produced by the stream:
  120. ///
  121. /// do {
  122. /// for try await quake in quakeStream {
  123. /// print("Quake: \(quake.date)")
  124. /// }
  125. /// print("Stream done.")
  126. /// } catch {
  127. /// print("Error: \(error)")
  128. /// }
  129. ///
  130. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  131. @usableFromInline
  132. internal struct BufferedStream<Element> {
  133. @usableFromInline
  134. final class _Backing: Sendable {
  135. @usableFromInline
  136. let storage: _BackPressuredStorage
  137. @inlinable
  138. init(storage: _BackPressuredStorage) {
  139. self.storage = storage
  140. }
  141. deinit {
  142. self.storage.sequenceDeinitialized()
  143. }
  144. }
  145. @usableFromInline
  146. enum _Implementation: Sendable {
  147. /// This is the implementation with backpressure based on the Source
  148. case backpressured(_Backing)
  149. }
  150. @usableFromInline
  151. let implementation: _Implementation
  152. }
  153. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  154. extension BufferedStream: AsyncSequence {
  155. /// The asynchronous iterator for iterating an asynchronous stream.
  156. ///
  157. /// This type is not `Sendable`. Don't use it from multiple
  158. /// concurrent contexts. It is a programmer error to invoke `next()` from a
  159. /// concurrent context that contends with another such call, which
  160. /// results in a call to `fatalError()`.
  161. @usableFromInline
  162. internal struct Iterator: AsyncIteratorProtocol {
  163. @usableFromInline
  164. final class _Backing {
  165. @usableFromInline
  166. let storage: _BackPressuredStorage
  167. @inlinable
  168. init(storage: _BackPressuredStorage) {
  169. self.storage = storage
  170. self.storage.iteratorInitialized()
  171. }
  172. deinit {
  173. self.storage.iteratorDeinitialized()
  174. }
  175. }
  176. @usableFromInline
  177. enum _Implementation {
  178. /// This is the implementation with backpressure based on the Source
  179. case backpressured(_Backing)
  180. }
  181. @usableFromInline
  182. var implementation: _Implementation
  183. @inlinable
  184. init(implementation: _Implementation) {
  185. self.implementation = implementation
  186. }
  187. /// The next value from the asynchronous stream.
  188. ///
  189. /// When `next()` returns `nil`, this signifies the end of the
  190. /// `BufferedStream`.
  191. ///
  192. /// It is a programmer error to invoke `next()` from a concurrent context
  193. /// that contends with another such call, which results in a call to
  194. /// `fatalError()`.
  195. ///
  196. /// If you cancel the task this iterator is running in while `next()` is
  197. /// awaiting a value, the `BufferedStream` terminates. In this case,
  198. /// `next()` may return `nil` immediately, or else return `nil` on
  199. /// subsequent calls.
  200. @inlinable
  201. internal mutating func next() async throws -> Element? {
  202. switch self.implementation {
  203. case .backpressured(let backing):
  204. return try await backing.storage.next()
  205. }
  206. }
  207. }
  208. /// Creates the asynchronous iterator that produces elements of this
  209. /// asynchronous sequence.
  210. @inlinable
  211. internal func makeAsyncIterator() -> Iterator {
  212. switch self.implementation {
  213. case .backpressured(let backing):
  214. return Iterator(implementation: .backpressured(.init(storage: backing.storage)))
  215. }
  216. }
  217. }
  218. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  219. extension BufferedStream: Sendable where Element: Sendable {}
  220. @usableFromInline
  221. internal struct _ManagedCriticalState<State>: @unchecked Sendable {
  222. @usableFromInline
  223. let lock: LockedValueBox<State>
  224. @inlinable
  225. internal init(_ initial: State) {
  226. self.lock = .init(initial)
  227. }
  228. @inlinable
  229. internal func withCriticalRegion<R>(
  230. _ critical: (inout State) throws -> R
  231. ) rethrows -> R {
  232. try self.lock.withLockedValue(critical)
  233. }
  234. }
  235. @usableFromInline
  236. internal struct AlreadyFinishedError: Error {
  237. @inlinable
  238. init() {}
  239. }
  240. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  241. extension BufferedStream {
  242. /// A mechanism to interface between producer code and an asynchronous stream.
  243. ///
  244. /// Use this source to provide elements to the stream by calling one of the `write` methods, then terminate the stream normally
  245. /// by calling the `finish()` method. You can also use the source's `finish(throwing:)` method to terminate the stream by
  246. /// throwing an error.
  247. @usableFromInline
  248. internal struct Source: Sendable {
  249. /// A strategy that handles the backpressure of the asynchronous stream.
  250. @usableFromInline
  251. internal struct BackPressureStrategy: Sendable {
  252. /// When the high watermark is reached producers will be suspended. All producers will be resumed again once
  253. /// the low watermark is reached.
  254. @inlinable
  255. internal static func watermark(low: Int, high: Int) -> BackPressureStrategy {
  256. BackPressureStrategy(
  257. internalBackPressureStrategy: .watermark(.init(low: low, high: high))
  258. )
  259. }
  260. @inlinable
  261. init(internalBackPressureStrategy: _InternalBackPressureStrategy) {
  262. self._internalBackPressureStrategy = internalBackPressureStrategy
  263. }
  264. @usableFromInline
  265. let _internalBackPressureStrategy: _InternalBackPressureStrategy
  266. }
  267. /// A type that indicates the result of writing elements to the source.
  268. @frozen
  269. @usableFromInline
  270. internal enum WriteResult: Sendable {
  271. /// A token that is returned when the asynchronous stream's backpressure strategy indicated that production should
  272. /// be suspended. Use this token to enqueue a callback by calling the ``enqueueCallback(_:)`` method.
  273. @usableFromInline
  274. internal struct CallbackToken: Sendable {
  275. @usableFromInline
  276. let id: UInt
  277. @usableFromInline
  278. init(id: UInt) {
  279. self.id = id
  280. }
  281. }
  282. /// Indicates that more elements should be produced and written to the source.
  283. case produceMore
  284. /// Indicates that a callback should be enqueued.
  285. ///
  286. /// The associated token should be passed to the ``enqueueCallback(_:)`` method.
  287. case enqueueCallback(CallbackToken)
  288. }
  289. /// Backing class for the source used to hook a deinit.
  290. @usableFromInline
  291. final class _Backing: Sendable {
  292. @usableFromInline
  293. let storage: _BackPressuredStorage
  294. @inlinable
  295. init(storage: _BackPressuredStorage) {
  296. self.storage = storage
  297. }
  298. deinit {
  299. self.storage.sourceDeinitialized()
  300. }
  301. }
  302. /// A callback to invoke when the stream finished.
  303. ///
  304. /// The stream finishes and calls this closure in the following cases:
  305. /// - No iterator was created and the sequence was deinited
  306. /// - An iterator was created and deinited
  307. /// - After ``finish(throwing:)`` was called and all elements have been consumed
  308. /// - The consuming task got cancelled
  309. @inlinable
  310. internal var onTermination: (@Sendable () -> Void)? {
  311. set {
  312. self._backing.storage.onTermination = newValue
  313. }
  314. get {
  315. self._backing.storage.onTermination
  316. }
  317. }
  318. @usableFromInline
  319. var _backing: _Backing
  320. @inlinable
  321. internal init(storage: _BackPressuredStorage) {
  322. self._backing = .init(storage: storage)
  323. }
  324. /// Writes new elements to the asynchronous stream.
  325. ///
  326. /// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the
  327. /// first element of the provided sequence. If the asynchronous stream already terminated then this method will throw an error
  328. /// indicating the failure.
  329. ///
  330. /// - Parameter sequence: The elements to write to the asynchronous stream.
  331. /// - Returns: The result that indicates if more elements should be produced at this time.
  332. @inlinable
  333. internal func write<S>(contentsOf sequence: S) throws -> WriteResult
  334. where Element == S.Element, S: Sequence {
  335. try self._backing.storage.write(contentsOf: sequence)
  336. }
  337. /// Write the element to the asynchronous stream.
  338. ///
  339. /// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the
  340. /// provided element. If the asynchronous stream already terminated then this method will throw an error
  341. /// indicating the failure.
  342. ///
  343. /// - Parameter element: The element to write to the asynchronous stream.
  344. /// - Returns: The result that indicates if more elements should be produced at this time.
  345. @inlinable
  346. internal func write(_ element: Element) throws -> WriteResult {
  347. try self._backing.storage.write(contentsOf: CollectionOfOne(element))
  348. }
  349. /// Enqueues a callback that will be invoked once more elements should be produced.
  350. ///
  351. /// Call this method after ``write(contentsOf:)`` or ``write(:)`` returned ``WriteResult/enqueueCallback(_:)``.
  352. ///
  353. /// - Important: Enqueueing the same token multiple times is not allowed.
  354. ///
  355. /// - Parameters:
  356. /// - callbackToken: The callback token.
  357. /// - onProduceMore: The callback which gets invoked once more elements should be produced.
  358. @inlinable
  359. internal func enqueueCallback(
  360. callbackToken: WriteResult.CallbackToken,
  361. onProduceMore: @escaping @Sendable (Result<Void, any Error>) -> Void
  362. ) {
  363. self._backing.storage.enqueueProducer(
  364. callbackToken: callbackToken,
  365. onProduceMore: onProduceMore
  366. )
  367. }
  368. /// Cancel an enqueued callback.
  369. ///
  370. /// Call this method to cancel a callback enqueued by the ``enqueueCallback(callbackToken:onProduceMore:)`` method.
  371. ///
  372. /// - Note: This methods supports being called before ``enqueueCallback(callbackToken:onProduceMore:)`` is called and
  373. /// will mark the passed `callbackToken` as cancelled.
  374. ///
  375. /// - Parameter callbackToken: The callback token.
  376. @inlinable
  377. internal func cancelCallback(callbackToken: WriteResult.CallbackToken) {
  378. self._backing.storage.cancelProducer(callbackToken: callbackToken)
  379. }
  380. /// Write new elements to the asynchronous stream and provide a callback which will be invoked once more elements should be produced.
  381. ///
  382. /// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the
  383. /// first element of the provided sequence. If the asynchronous stream already terminated then `onProduceMore` will be invoked with
  384. /// a `Result.failure`.
  385. ///
  386. /// - Parameters:
  387. /// - sequence: The elements to write to the asynchronous stream.
  388. /// - onProduceMore: The callback which gets invoked once more elements should be produced. This callback might be
  389. /// invoked during the call to ``write(contentsOf:onProduceMore:)``.
  390. @inlinable
  391. internal func write<S>(
  392. contentsOf sequence: S,
  393. onProduceMore: @escaping @Sendable (Result<Void, any Error>) -> Void
  394. ) where Element == S.Element, S: Sequence {
  395. do {
  396. let writeResult = try self.write(contentsOf: sequence)
  397. switch writeResult {
  398. case .produceMore:
  399. onProduceMore(Result<Void, any Error>.success(()))
  400. case .enqueueCallback(let callbackToken):
  401. self.enqueueCallback(callbackToken: callbackToken, onProduceMore: onProduceMore)
  402. }
  403. } catch {
  404. onProduceMore(.failure(error))
  405. }
  406. }
  407. /// Writes the element to the asynchronous stream.
  408. ///
  409. /// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the
  410. /// provided element. If the asynchronous stream already terminated then `onProduceMore` will be invoked with
  411. /// a `Result.failure`.
  412. ///
  413. /// - Parameters:
  414. /// - sequence: The element to write to the asynchronous stream.
  415. /// - onProduceMore: The callback which gets invoked once more elements should be produced. This callback might be
  416. /// invoked during the call to ``write(_:onProduceMore:)``.
  417. @inlinable
  418. internal func write(
  419. _ element: Element,
  420. onProduceMore: @escaping @Sendable (Result<Void, any Error>) -> Void
  421. ) {
  422. self.write(contentsOf: CollectionOfOne(element), onProduceMore: onProduceMore)
  423. }
  424. /// Write new elements to the asynchronous stream.
  425. ///
  426. /// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the
  427. /// first element of the provided sequence. If the asynchronous stream already terminated then this method will throw an error
  428. /// indicating the failure.
  429. ///
  430. /// This method returns once more elements should be produced.
  431. ///
  432. /// - Parameters:
  433. /// - sequence: The elements to write to the asynchronous stream.
  434. @inlinable
  435. internal func write<S>(contentsOf sequence: S) async throws
  436. where Element == S.Element, S: Sequence {
  437. let writeResult = try { try self.write(contentsOf: sequence) }()
  438. switch writeResult {
  439. case .produceMore:
  440. return
  441. case .enqueueCallback(let callbackToken):
  442. try await withTaskCancellationHandler {
  443. try await withCheckedThrowingContinuation { continuation in
  444. self.enqueueCallback(
  445. callbackToken: callbackToken,
  446. onProduceMore: { result in
  447. switch result {
  448. case .success():
  449. continuation.resume(returning: ())
  450. case .failure(let error):
  451. continuation.resume(throwing: error)
  452. }
  453. }
  454. )
  455. }
  456. } onCancel: {
  457. self.cancelCallback(callbackToken: callbackToken)
  458. }
  459. }
  460. }
  461. /// Write new element to the asynchronous stream.
  462. ///
  463. /// If there is a task consuming the stream and awaiting the next element then the task will get resumed with the
  464. /// provided element. If the asynchronous stream already terminated then this method will throw an error
  465. /// indicating the failure.
  466. ///
  467. /// This method returns once more elements should be produced.
  468. ///
  469. /// - Parameters:
  470. /// - sequence: The element to write to the asynchronous stream.
  471. @inlinable
  472. internal func write(_ element: Element) async throws {
  473. try await self.write(contentsOf: CollectionOfOne(element))
  474. }
  475. /// Write the elements of the asynchronous sequence to the asynchronous stream.
  476. ///
  477. /// This method returns once the provided asynchronous sequence or the the asynchronous stream finished.
  478. ///
  479. /// - Important: This method does not finish the source if consuming the upstream sequence terminated.
  480. ///
  481. /// - Parameters:
  482. /// - sequence: The elements to write to the asynchronous stream.
  483. @inlinable
  484. internal func write<S>(contentsOf sequence: S) async throws
  485. where Element == S.Element, S: AsyncSequence {
  486. for try await element in sequence {
  487. try await self.write(contentsOf: CollectionOfOne(element))
  488. }
  489. }
  490. /// Indicates that the production terminated.
  491. ///
  492. /// After all buffered elements are consumed the next iteration point will return `nil` or throw an error.
  493. ///
  494. /// Calling this function more than once has no effect. After calling finish, the stream enters a terminal state and doesn't accept
  495. /// new elements.
  496. ///
  497. /// - Parameters:
  498. /// - error: The error to throw, or `nil`, to finish normally.
  499. @inlinable
  500. internal func finish(throwing error: (any Error)?) {
  501. self._backing.storage.finish(error)
  502. }
  503. }
  504. /// Initializes a new ``BufferedStream`` and an ``BufferedStream/Source``.
  505. ///
  506. /// - Parameters:
  507. /// - elementType: The element type of the stream.
  508. /// - failureType: The failure type of the stream.
  509. /// - backPressureStrategy: The backpressure strategy that the stream should use.
  510. /// - Returns: A tuple containing the stream and its source. The source should be passed to the
  511. /// producer while the stream should be passed to the consumer.
  512. @inlinable
  513. internal static func makeStream(
  514. of elementType: Element.Type = Element.self,
  515. throwing failureType: (any Error).Type = (any Error).self,
  516. backPressureStrategy: Source.BackPressureStrategy
  517. ) -> (`Self`, Source) where any Error == any Error {
  518. let storage = _BackPressuredStorage(
  519. backPressureStrategy: backPressureStrategy._internalBackPressureStrategy
  520. )
  521. let source = Source(storage: storage)
  522. return (.init(storage: storage), source)
  523. }
  524. @inlinable
  525. init(storage: _BackPressuredStorage) {
  526. self.implementation = .backpressured(.init(storage: storage))
  527. }
  528. }
  529. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  530. extension BufferedStream {
  531. @usableFromInline
  532. struct _WatermarkBackPressureStrategy: Sendable {
  533. /// The low watermark where demand should start.
  534. @usableFromInline
  535. let _low: Int
  536. /// The high watermark where demand should be stopped.
  537. @usableFromInline
  538. let _high: Int
  539. /// Initializes a new ``_WatermarkBackPressureStrategy``.
  540. ///
  541. /// - Parameters:
  542. /// - low: The low watermark where demand should start.
  543. /// - high: The high watermark where demand should be stopped.
  544. @inlinable
  545. init(low: Int, high: Int) {
  546. precondition(low <= high)
  547. self._low = low
  548. self._high = high
  549. }
  550. @inlinable
  551. func didYield(bufferDepth: Int) -> Bool {
  552. // We are demanding more until we reach the high watermark
  553. return bufferDepth < self._high
  554. }
  555. @inlinable
  556. func didConsume(bufferDepth: Int) -> Bool {
  557. // We start demanding again once we are below the low watermark
  558. return bufferDepth < self._low
  559. }
  560. }
  561. @usableFromInline
  562. enum _InternalBackPressureStrategy: Sendable {
  563. case watermark(_WatermarkBackPressureStrategy)
  564. @inlinable
  565. mutating func didYield(bufferDepth: Int) -> Bool {
  566. switch self {
  567. case .watermark(let strategy):
  568. return strategy.didYield(bufferDepth: bufferDepth)
  569. }
  570. }
  571. @inlinable
  572. mutating func didConsume(bufferDepth: Int) -> Bool {
  573. switch self {
  574. case .watermark(let strategy):
  575. return strategy.didConsume(bufferDepth: bufferDepth)
  576. }
  577. }
  578. }
  579. }
  580. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  581. extension BufferedStream {
  582. @usableFromInline
  583. struct _BackPressuredStorage: Sendable {
  584. @usableFromInline
  585. let _stateMachine: _ManagedCriticalState<_StateMachine>
  586. @usableFromInline
  587. var onTermination: (@Sendable () -> Void)? {
  588. nonmutating set {
  589. self._stateMachine.withCriticalRegion {
  590. $0._onTermination = newValue
  591. }
  592. }
  593. get {
  594. self._stateMachine.withCriticalRegion {
  595. $0._onTermination
  596. }
  597. }
  598. }
  599. @inlinable
  600. init(
  601. backPressureStrategy: _InternalBackPressureStrategy
  602. ) {
  603. self._stateMachine = .init(.init(backPressureStrategy: backPressureStrategy))
  604. }
  605. @inlinable
  606. func sequenceDeinitialized() {
  607. let action = self._stateMachine.withCriticalRegion {
  608. $0.sequenceDeinitialized()
  609. }
  610. switch action {
  611. case .callOnTermination(let onTermination):
  612. onTermination?()
  613. case .failProducersAndCallOnTermination(let producerContinuations, let onTermination):
  614. for producerContinuation in producerContinuations {
  615. producerContinuation(.failure(AlreadyFinishedError()))
  616. }
  617. onTermination?()
  618. case .none:
  619. break
  620. }
  621. }
  622. @inlinable
  623. func iteratorInitialized() {
  624. self._stateMachine.withCriticalRegion {
  625. $0.iteratorInitialized()
  626. }
  627. }
  628. @inlinable
  629. func iteratorDeinitialized() {
  630. let action = self._stateMachine.withCriticalRegion {
  631. $0.iteratorDeinitialized()
  632. }
  633. switch action {
  634. case .callOnTermination(let onTermination):
  635. onTermination?()
  636. case .failProducersAndCallOnTermination(let producerContinuations, let onTermination):
  637. for producerContinuation in producerContinuations {
  638. producerContinuation(.failure(AlreadyFinishedError()))
  639. }
  640. onTermination?()
  641. case .none:
  642. break
  643. }
  644. }
  645. @inlinable
  646. func sourceDeinitialized() {
  647. let action = self._stateMachine.withCriticalRegion {
  648. $0.sourceDeinitialized()
  649. }
  650. switch action {
  651. case .callOnTermination(let onTermination):
  652. onTermination?()
  653. case .failProducersAndCallOnTermination(
  654. let consumer,
  655. let producerContinuations,
  656. let onTermination
  657. ):
  658. consumer?.resume(returning: nil)
  659. for producerContinuation in producerContinuations {
  660. producerContinuation(.failure(AlreadyFinishedError()))
  661. }
  662. onTermination?()
  663. case .failProducers(let producerContinuations):
  664. for producerContinuation in producerContinuations {
  665. producerContinuation(.failure(AlreadyFinishedError()))
  666. }
  667. case .none:
  668. break
  669. }
  670. }
  671. @inlinable
  672. func write(
  673. contentsOf sequence: some Sequence<Element>
  674. ) throws -> Source.WriteResult {
  675. let action = self._stateMachine.withCriticalRegion {
  676. return $0.write(sequence)
  677. }
  678. switch action {
  679. case .returnProduceMore:
  680. return .produceMore
  681. case .returnEnqueue(let callbackToken):
  682. return .enqueueCallback(callbackToken)
  683. case .resumeConsumerAndReturnProduceMore(let continuation, let element):
  684. continuation.resume(returning: element)
  685. return .produceMore
  686. case .resumeConsumerAndReturnEnqueue(let continuation, let element, let callbackToken):
  687. continuation.resume(returning: element)
  688. return .enqueueCallback(callbackToken)
  689. case .throwFinishedError:
  690. throw AlreadyFinishedError()
  691. }
  692. }
  693. @inlinable
  694. func enqueueProducer(
  695. callbackToken: Source.WriteResult.CallbackToken,
  696. onProduceMore: @escaping @Sendable (Result<Void, any Error>) -> Void
  697. ) {
  698. let action = self._stateMachine.withCriticalRegion {
  699. $0.enqueueProducer(callbackToken: callbackToken, onProduceMore: onProduceMore)
  700. }
  701. switch action {
  702. case .resumeProducer(let onProduceMore):
  703. onProduceMore(Result<Void, any Error>.success(()))
  704. case .resumeProducerWithError(let onProduceMore, let error):
  705. onProduceMore(Result<Void, any Error>.failure(error))
  706. case .none:
  707. break
  708. }
  709. }
  710. @inlinable
  711. func cancelProducer(callbackToken: Source.WriteResult.CallbackToken) {
  712. let action = self._stateMachine.withCriticalRegion {
  713. $0.cancelProducer(callbackToken: callbackToken)
  714. }
  715. switch action {
  716. case .resumeProducerWithCancellationError(let onProduceMore):
  717. onProduceMore(Result<Void, any Error>.failure(CancellationError()))
  718. case .none:
  719. break
  720. }
  721. }
  722. @inlinable
  723. func finish(_ failure: (any Error)?) {
  724. let action = self._stateMachine.withCriticalRegion {
  725. $0.finish(failure)
  726. }
  727. switch action {
  728. case .callOnTermination(let onTermination):
  729. onTermination?()
  730. case .resumeConsumerAndCallOnTermination(
  731. let consumerContinuation,
  732. let failure,
  733. let onTermination
  734. ):
  735. switch failure {
  736. case .some(let error):
  737. consumerContinuation.resume(throwing: error)
  738. case .none:
  739. consumerContinuation.resume(returning: nil)
  740. }
  741. onTermination?()
  742. case .resumeProducers(let producerContinuations):
  743. for producerContinuation in producerContinuations {
  744. producerContinuation(.failure(AlreadyFinishedError()))
  745. }
  746. case .none:
  747. break
  748. }
  749. }
  750. @inlinable
  751. func next() async throws -> Element? {
  752. let action = self._stateMachine.withCriticalRegion {
  753. $0.next()
  754. }
  755. switch action {
  756. case .returnElement(let element):
  757. return element
  758. case .returnElementAndResumeProducers(let element, let producerContinuations):
  759. for producerContinuation in producerContinuations {
  760. producerContinuation(Result<Void, any Error>.success(()))
  761. }
  762. return element
  763. case .returnErrorAndCallOnTermination(let failure, let onTermination):
  764. onTermination?()
  765. switch failure {
  766. case .some(let error):
  767. throw error
  768. case .none:
  769. return nil
  770. }
  771. case .returnNil:
  772. return nil
  773. case .suspendTask:
  774. return try await self.suspendNext()
  775. }
  776. }
  777. @inlinable
  778. func suspendNext() async throws -> Element? {
  779. return try await withTaskCancellationHandler {
  780. return try await withCheckedThrowingContinuation { continuation in
  781. let action = self._stateMachine.withCriticalRegion {
  782. $0.suspendNext(continuation: continuation)
  783. }
  784. switch action {
  785. case .resumeConsumerWithElement(let continuation, let element):
  786. continuation.resume(returning: element)
  787. case .resumeConsumerWithElementAndProducers(
  788. let continuation,
  789. let element,
  790. let producerContinuations
  791. ):
  792. continuation.resume(returning: element)
  793. for producerContinuation in producerContinuations {
  794. producerContinuation(Result<Void, any Error>.success(()))
  795. }
  796. case .resumeConsumerWithErrorAndCallOnTermination(
  797. let continuation,
  798. let failure,
  799. let onTermination
  800. ):
  801. switch failure {
  802. case .some(let error):
  803. continuation.resume(throwing: error)
  804. case .none:
  805. continuation.resume(returning: nil)
  806. }
  807. onTermination?()
  808. case .resumeConsumerWithNil(let continuation):
  809. continuation.resume(returning: nil)
  810. case .none:
  811. break
  812. }
  813. }
  814. } onCancel: {
  815. let action = self._stateMachine.withCriticalRegion {
  816. $0.cancelNext()
  817. }
  818. switch action {
  819. case .resumeConsumerWithCancellationErrorAndCallOnTermination(
  820. let continuation,
  821. let onTermination
  822. ):
  823. continuation.resume(throwing: CancellationError())
  824. onTermination?()
  825. case .failProducersAndCallOnTermination(
  826. let producerContinuations,
  827. let onTermination
  828. ):
  829. for producerContinuation in producerContinuations {
  830. producerContinuation(.failure(AlreadyFinishedError()))
  831. }
  832. onTermination?()
  833. case .none:
  834. break
  835. }
  836. }
  837. }
  838. }
  839. }
  840. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  841. extension BufferedStream {
  842. /// The state machine of the backpressured async stream.
  843. @usableFromInline
  844. struct _StateMachine {
  845. @usableFromInline
  846. enum _State {
  847. @usableFromInline
  848. struct Initial {
  849. /// The backpressure strategy.
  850. @usableFromInline
  851. var backPressureStrategy: _InternalBackPressureStrategy
  852. /// Indicates if the iterator was initialized.
  853. @usableFromInline
  854. var iteratorInitialized: Bool
  855. /// The onTermination callback.
  856. @usableFromInline
  857. var onTermination: (@Sendable () -> Void)?
  858. @inlinable
  859. init(
  860. backPressureStrategy: _InternalBackPressureStrategy,
  861. iteratorInitialized: Bool,
  862. onTermination: (@Sendable () -> Void)? = nil
  863. ) {
  864. self.backPressureStrategy = backPressureStrategy
  865. self.iteratorInitialized = iteratorInitialized
  866. self.onTermination = onTermination
  867. }
  868. }
  869. @usableFromInline
  870. struct Streaming {
  871. /// The backpressure strategy.
  872. @usableFromInline
  873. var backPressureStrategy: _InternalBackPressureStrategy
  874. /// Indicates if the iterator was initialized.
  875. @usableFromInline
  876. var iteratorInitialized: Bool
  877. /// The onTermination callback.
  878. @usableFromInline
  879. var onTermination: (@Sendable () -> Void)?
  880. /// The buffer of elements.
  881. @usableFromInline
  882. var buffer: Deque<Element>
  883. /// The optional consumer continuation.
  884. @usableFromInline
  885. var consumerContinuation: CheckedContinuation<Element?, any Error>?
  886. /// The producer continuations.
  887. @usableFromInline
  888. var producerContinuations: Deque<(UInt, (Result<Void, any Error>) -> Void)>
  889. /// The producers that have been cancelled.
  890. @usableFromInline
  891. var cancelledAsyncProducers: Deque<UInt>
  892. /// Indicates if we currently have outstanding demand.
  893. @usableFromInline
  894. var hasOutstandingDemand: Bool
  895. @inlinable
  896. init(
  897. backPressureStrategy: _InternalBackPressureStrategy,
  898. iteratorInitialized: Bool,
  899. onTermination: (@Sendable () -> Void)? = nil,
  900. buffer: Deque<Element>,
  901. consumerContinuation: CheckedContinuation<Element?, any Error>? = nil,
  902. producerContinuations: Deque<(UInt, (Result<Void, any Error>) -> Void)>,
  903. cancelledAsyncProducers: Deque<UInt>,
  904. hasOutstandingDemand: Bool
  905. ) {
  906. self.backPressureStrategy = backPressureStrategy
  907. self.iteratorInitialized = iteratorInitialized
  908. self.onTermination = onTermination
  909. self.buffer = buffer
  910. self.consumerContinuation = consumerContinuation
  911. self.producerContinuations = producerContinuations
  912. self.cancelledAsyncProducers = cancelledAsyncProducers
  913. self.hasOutstandingDemand = hasOutstandingDemand
  914. }
  915. }
  916. @usableFromInline
  917. struct SourceFinished {
  918. /// Indicates if the iterator was initialized.
  919. @usableFromInline
  920. var iteratorInitialized: Bool
  921. /// The buffer of elements.
  922. @usableFromInline
  923. var buffer: Deque<Element>
  924. /// The failure that should be thrown after the last element has been consumed.
  925. @usableFromInline
  926. var failure: (any Error)?
  927. /// The onTermination callback.
  928. @usableFromInline
  929. var onTermination: (@Sendable () -> Void)?
  930. @inlinable
  931. init(
  932. iteratorInitialized: Bool,
  933. buffer: Deque<Element>,
  934. failure: (any Error)? = nil,
  935. onTermination: (@Sendable () -> Void)?
  936. ) {
  937. self.iteratorInitialized = iteratorInitialized
  938. self.buffer = buffer
  939. self.failure = failure
  940. self.onTermination = onTermination
  941. }
  942. }
  943. case initial(Initial)
  944. /// The state once either any element was yielded or `next()` was called.
  945. case streaming(Streaming)
  946. /// The state once the underlying source signalled that it is finished.
  947. case sourceFinished(SourceFinished)
  948. /// The state once there can be no outstanding demand. This can happen if:
  949. /// 1. The iterator was deinited
  950. /// 2. The underlying source finished and all buffered elements have been consumed
  951. case finished(iteratorInitialized: Bool)
  952. /// An intermediate state to avoid CoWs.
  953. case modify
  954. }
  955. /// The state machine's current state.
  956. @usableFromInline
  957. var _state: _State
  958. // The ID used for the next CallbackToken.
  959. @usableFromInline
  960. var nextCallbackTokenID: UInt = 0
  961. @inlinable
  962. var _onTermination: (@Sendable () -> Void)? {
  963. set {
  964. switch self._state {
  965. case .initial(var initial):
  966. initial.onTermination = newValue
  967. self._state = .initial(initial)
  968. case .streaming(var streaming):
  969. streaming.onTermination = newValue
  970. self._state = .streaming(streaming)
  971. case .sourceFinished(var sourceFinished):
  972. sourceFinished.onTermination = newValue
  973. self._state = .sourceFinished(sourceFinished)
  974. case .finished:
  975. break
  976. case .modify:
  977. fatalError("AsyncStream internal inconsistency")
  978. }
  979. }
  980. get {
  981. switch self._state {
  982. case .initial(let initial):
  983. return initial.onTermination
  984. case .streaming(let streaming):
  985. return streaming.onTermination
  986. case .sourceFinished(let sourceFinished):
  987. return sourceFinished.onTermination
  988. case .finished:
  989. return nil
  990. case .modify:
  991. fatalError("AsyncStream internal inconsistency")
  992. }
  993. }
  994. }
  995. /// Initializes a new `StateMachine`.
  996. ///
  997. /// We are passing and holding the back-pressure strategy here because
  998. /// it is a customizable extension of the state machine.
  999. ///
  1000. /// - Parameter backPressureStrategy: The back-pressure strategy.
  1001. @inlinable
  1002. init(
  1003. backPressureStrategy: _InternalBackPressureStrategy
  1004. ) {
  1005. self._state = .initial(
  1006. .init(
  1007. backPressureStrategy: backPressureStrategy,
  1008. iteratorInitialized: false
  1009. )
  1010. )
  1011. }
  1012. /// Generates the next callback token.
  1013. @inlinable
  1014. mutating func nextCallbackToken() -> Source.WriteResult.CallbackToken {
  1015. let id = self.nextCallbackTokenID
  1016. self.nextCallbackTokenID += 1
  1017. return .init(id: id)
  1018. }
  1019. /// Actions returned by `sequenceDeinitialized()`.
  1020. @usableFromInline
  1021. enum SequenceDeinitializedAction {
  1022. /// Indicates that `onTermination` should be called.
  1023. case callOnTermination((@Sendable () -> Void)?)
  1024. /// Indicates that all producers should be failed and `onTermination` should be called.
  1025. case failProducersAndCallOnTermination(
  1026. [(Result<Void, any Error>) -> Void],
  1027. (@Sendable () -> Void)?
  1028. )
  1029. }
  1030. @inlinable
  1031. mutating func sequenceDeinitialized() -> SequenceDeinitializedAction? {
  1032. switch self._state {
  1033. case .initial(let initial):
  1034. if initial.iteratorInitialized {
  1035. // An iterator was created and we deinited the sequence.
  1036. // This is an expected pattern and we just continue on normal.
  1037. return .none
  1038. } else {
  1039. // No iterator was created so we can transition to finished right away.
  1040. self._state = .finished(iteratorInitialized: false)
  1041. return .callOnTermination(initial.onTermination)
  1042. }
  1043. case .streaming(let streaming):
  1044. if streaming.iteratorInitialized {
  1045. // An iterator was created and we deinited the sequence.
  1046. // This is an expected pattern and we just continue on normal.
  1047. return .none
  1048. } else {
  1049. // No iterator was created so we can transition to finished right away.
  1050. self._state = .finished(iteratorInitialized: false)
  1051. return .failProducersAndCallOnTermination(
  1052. Array(streaming.producerContinuations.map { $0.1 }),
  1053. streaming.onTermination
  1054. )
  1055. }
  1056. case .sourceFinished(let sourceFinished):
  1057. if sourceFinished.iteratorInitialized {
  1058. // An iterator was created and we deinited the sequence.
  1059. // This is an expected pattern and we just continue on normal.
  1060. return .none
  1061. } else {
  1062. // No iterator was created so we can transition to finished right away.
  1063. self._state = .finished(iteratorInitialized: false)
  1064. return .callOnTermination(sourceFinished.onTermination)
  1065. }
  1066. case .finished:
  1067. // We are already finished so there is nothing left to clean up.
  1068. // This is just the references dropping afterwards.
  1069. return .none
  1070. case .modify:
  1071. fatalError("AsyncStream internal inconsistency")
  1072. }
  1073. }
  1074. @inlinable
  1075. mutating func iteratorInitialized() {
  1076. switch self._state {
  1077. case .initial(var initial):
  1078. if initial.iteratorInitialized {
  1079. // Our sequence is a unicast sequence and does not support multiple AsyncIterator's
  1080. fatalError("Only a single AsyncIterator can be created")
  1081. } else {
  1082. // The first and only iterator was initialized.
  1083. initial.iteratorInitialized = true
  1084. self._state = .initial(initial)
  1085. }
  1086. case .streaming(var streaming):
  1087. if streaming.iteratorInitialized {
  1088. // Our sequence is a unicast sequence and does not support multiple AsyncIterator's
  1089. fatalError("Only a single AsyncIterator can be created")
  1090. } else {
  1091. // The first and only iterator was initialized.
  1092. streaming.iteratorInitialized = true
  1093. self._state = .streaming(streaming)
  1094. }
  1095. case .sourceFinished(var sourceFinished):
  1096. if sourceFinished.iteratorInitialized {
  1097. // Our sequence is a unicast sequence and does not support multiple AsyncIterator's
  1098. fatalError("Only a single AsyncIterator can be created")
  1099. } else {
  1100. // The first and only iterator was initialized.
  1101. sourceFinished.iteratorInitialized = true
  1102. self._state = .sourceFinished(sourceFinished)
  1103. }
  1104. case .finished(iteratorInitialized: true):
  1105. // Our sequence is a unicast sequence and does not support multiple AsyncIterator's
  1106. fatalError("Only a single AsyncIterator can be created")
  1107. case .finished(iteratorInitialized: false):
  1108. // It is strange that an iterator is created after we are finished
  1109. // but it can definitely happen, e.g.
  1110. // Sequence.init -> source.finish -> sequence.makeAsyncIterator
  1111. self._state = .finished(iteratorInitialized: true)
  1112. case .modify:
  1113. fatalError("AsyncStream internal inconsistency")
  1114. }
  1115. }
  1116. /// Actions returned by `iteratorDeinitialized()`.
  1117. @usableFromInline
  1118. enum IteratorDeinitializedAction {
  1119. /// Indicates that `onTermination` should be called.
  1120. case callOnTermination((@Sendable () -> Void)?)
  1121. /// Indicates that all producers should be failed and `onTermination` should be called.
  1122. case failProducersAndCallOnTermination(
  1123. [(Result<Void, any Error>) -> Void],
  1124. (@Sendable () -> Void)?
  1125. )
  1126. }
  1127. @inlinable
  1128. mutating func iteratorDeinitialized() -> IteratorDeinitializedAction? {
  1129. switch self._state {
  1130. case .initial(let initial):
  1131. if initial.iteratorInitialized {
  1132. // An iterator was created and deinited. Since we only support
  1133. // a single iterator we can now transition to finish.
  1134. self._state = .finished(iteratorInitialized: true)
  1135. return .callOnTermination(initial.onTermination)
  1136. } else {
  1137. // An iterator needs to be initialized before it can be deinitialized.
  1138. fatalError("AsyncStream internal inconsistency")
  1139. }
  1140. case .streaming(let streaming):
  1141. if streaming.iteratorInitialized {
  1142. // An iterator was created and deinited. Since we only support
  1143. // a single iterator we can now transition to finish.
  1144. self._state = .finished(iteratorInitialized: true)
  1145. return .failProducersAndCallOnTermination(
  1146. Array(streaming.producerContinuations.map { $0.1 }),
  1147. streaming.onTermination
  1148. )
  1149. } else {
  1150. // An iterator needs to be initialized before it can be deinitialized.
  1151. fatalError("AsyncStream internal inconsistency")
  1152. }
  1153. case .sourceFinished(let sourceFinished):
  1154. if sourceFinished.iteratorInitialized {
  1155. // An iterator was created and deinited. Since we only support
  1156. // a single iterator we can now transition to finish.
  1157. self._state = .finished(iteratorInitialized: true)
  1158. return .callOnTermination(sourceFinished.onTermination)
  1159. } else {
  1160. // An iterator needs to be initialized before it can be deinitialized.
  1161. fatalError("AsyncStream internal inconsistency")
  1162. }
  1163. case .finished:
  1164. // We are already finished so there is nothing left to clean up.
  1165. // This is just the references dropping afterwards.
  1166. return .none
  1167. case .modify:
  1168. fatalError("AsyncStream internal inconsistency")
  1169. }
  1170. }
  1171. /// Actions returned by `sourceDeinitialized()`.
  1172. @usableFromInline
  1173. enum SourceDeinitializedAction {
  1174. /// Indicates that `onTermination` should be called.
  1175. case callOnTermination((() -> Void)?)
  1176. /// Indicates that all producers should be failed and `onTermination` should be called.
  1177. case failProducersAndCallOnTermination(
  1178. CheckedContinuation<Element?, any Error>?,
  1179. [(Result<Void, any Error>) -> Void],
  1180. (@Sendable () -> Void)?
  1181. )
  1182. /// Indicates that all producers should be failed.
  1183. case failProducers([(Result<Void, any Error>) -> Void])
  1184. }
  1185. @inlinable
  1186. mutating func sourceDeinitialized() -> SourceDeinitializedAction? {
  1187. switch self._state {
  1188. case .initial(let initial):
  1189. // The source got deinited before anything was written
  1190. self._state = .finished(iteratorInitialized: initial.iteratorInitialized)
  1191. return .callOnTermination(initial.onTermination)
  1192. case .streaming(let streaming):
  1193. if streaming.buffer.isEmpty {
  1194. // We can transition to finished right away since the buffer is empty now
  1195. self._state = .finished(iteratorInitialized: streaming.iteratorInitialized)
  1196. return .failProducersAndCallOnTermination(
  1197. streaming.consumerContinuation,
  1198. Array(streaming.producerContinuations.map { $0.1 }),
  1199. streaming.onTermination
  1200. )
  1201. } else {
  1202. // The continuation must be `nil` if the buffer has elements
  1203. precondition(streaming.consumerContinuation == nil)
  1204. self._state = .sourceFinished(
  1205. .init(
  1206. iteratorInitialized: streaming.iteratorInitialized,
  1207. buffer: streaming.buffer,
  1208. failure: nil,
  1209. onTermination: streaming.onTermination
  1210. )
  1211. )
  1212. return .failProducers(
  1213. Array(streaming.producerContinuations.map { $0.1 })
  1214. )
  1215. }
  1216. case .sourceFinished, .finished:
  1217. // This is normal and we just have to tolerate it
  1218. return .none
  1219. case .modify:
  1220. fatalError("AsyncStream internal inconsistency")
  1221. }
  1222. }
  1223. /// Actions returned by `write()`.
  1224. @usableFromInline
  1225. enum WriteAction {
  1226. /// Indicates that the producer should be notified to produce more.
  1227. case returnProduceMore
  1228. /// Indicates that the producer should be suspended to stop producing.
  1229. case returnEnqueue(
  1230. callbackToken: Source.WriteResult.CallbackToken
  1231. )
  1232. /// Indicates that the consumer should be resumed and the producer should be notified to produce more.
  1233. case resumeConsumerAndReturnProduceMore(
  1234. continuation: CheckedContinuation<Element?, any Error>,
  1235. element: Element
  1236. )
  1237. /// Indicates that the consumer should be resumed and the producer should be suspended.
  1238. case resumeConsumerAndReturnEnqueue(
  1239. continuation: CheckedContinuation<Element?, any Error>,
  1240. element: Element,
  1241. callbackToken: Source.WriteResult.CallbackToken
  1242. )
  1243. /// Indicates that the producer has been finished.
  1244. case throwFinishedError
  1245. @inlinable
  1246. init(
  1247. callbackToken: Source.WriteResult.CallbackToken?,
  1248. continuationAndElement: (CheckedContinuation<Element?, any Error>, Element)? = nil
  1249. ) {
  1250. switch (callbackToken, continuationAndElement) {
  1251. case (.none, .none):
  1252. self = .returnProduceMore
  1253. case (.some(let callbackToken), .none):
  1254. self = .returnEnqueue(callbackToken: callbackToken)
  1255. case (.none, .some((let continuation, let element))):
  1256. self = .resumeConsumerAndReturnProduceMore(
  1257. continuation: continuation,
  1258. element: element
  1259. )
  1260. case (.some(let callbackToken), .some((let continuation, let element))):
  1261. self = .resumeConsumerAndReturnEnqueue(
  1262. continuation: continuation,
  1263. element: element,
  1264. callbackToken: callbackToken
  1265. )
  1266. }
  1267. }
  1268. }
  1269. @inlinable
  1270. mutating func write(_ sequence: some Sequence<Element>) -> WriteAction {
  1271. switch self._state {
  1272. case .initial(var initial):
  1273. var buffer = Deque<Element>()
  1274. buffer.append(contentsOf: sequence)
  1275. let shouldProduceMore = initial.backPressureStrategy.didYield(
  1276. bufferDepth: buffer.count
  1277. )
  1278. let callbackToken = shouldProduceMore ? nil : self.nextCallbackToken()
  1279. self._state = .streaming(
  1280. .init(
  1281. backPressureStrategy: initial.backPressureStrategy,
  1282. iteratorInitialized: initial.iteratorInitialized,
  1283. onTermination: initial.onTermination,
  1284. buffer: buffer,
  1285. consumerContinuation: nil,
  1286. producerContinuations: .init(),
  1287. cancelledAsyncProducers: .init(),
  1288. hasOutstandingDemand: shouldProduceMore
  1289. )
  1290. )
  1291. return .init(callbackToken: callbackToken)
  1292. case .streaming(var streaming):
  1293. self._state = .modify
  1294. streaming.buffer.append(contentsOf: sequence)
  1295. // We have an element and can resume the continuation
  1296. let shouldProduceMore = streaming.backPressureStrategy.didYield(
  1297. bufferDepth: streaming.buffer.count
  1298. )
  1299. streaming.hasOutstandingDemand = shouldProduceMore
  1300. let callbackToken = shouldProduceMore ? nil : self.nextCallbackToken()
  1301. if let consumerContinuation = streaming.consumerContinuation {
  1302. guard let element = streaming.buffer.popFirst() else {
  1303. // We got a yield of an empty sequence. We just tolerate this.
  1304. self._state = .streaming(streaming)
  1305. return .init(callbackToken: callbackToken)
  1306. }
  1307. // We got a consumer continuation and an element. We can resume the consumer now
  1308. streaming.consumerContinuation = nil
  1309. self._state = .streaming(streaming)
  1310. return .init(
  1311. callbackToken: callbackToken,
  1312. continuationAndElement: (consumerContinuation, element)
  1313. )
  1314. } else {
  1315. // We don't have a suspended consumer so we just buffer the elements
  1316. self._state = .streaming(streaming)
  1317. return .init(
  1318. callbackToken: callbackToken
  1319. )
  1320. }
  1321. case .sourceFinished, .finished:
  1322. // If the source has finished we are dropping the elements.
  1323. return .throwFinishedError
  1324. case .modify:
  1325. fatalError("AsyncStream internal inconsistency")
  1326. }
  1327. }
  1328. /// Actions returned by `enqueueProducer()`.
  1329. @usableFromInline
  1330. enum EnqueueProducerAction {
  1331. /// Indicates that the producer should be notified to produce more.
  1332. case resumeProducer((Result<Void, any Error>) -> Void)
  1333. /// Indicates that the producer should be notified about an error.
  1334. case resumeProducerWithError((Result<Void, any Error>) -> Void, any Error)
  1335. }
  1336. @inlinable
  1337. mutating func enqueueProducer(
  1338. callbackToken: Source.WriteResult.CallbackToken,
  1339. onProduceMore: @Sendable @escaping (Result<Void, any Error>) -> Void
  1340. ) -> EnqueueProducerAction? {
  1341. switch self._state {
  1342. case .initial:
  1343. // We need to transition to streaming before we can suspend
  1344. // This is enforced because the CallbackToken has no internal init so
  1345. // one must create it by calling `write` first.
  1346. fatalError("AsyncStream internal inconsistency")
  1347. case .streaming(var streaming):
  1348. if let index = streaming.cancelledAsyncProducers.firstIndex(of: callbackToken.id) {
  1349. // Our producer got marked as cancelled.
  1350. self._state = .modify
  1351. streaming.cancelledAsyncProducers.remove(at: index)
  1352. self._state = .streaming(streaming)
  1353. return .resumeProducerWithError(onProduceMore, CancellationError())
  1354. } else if streaming.hasOutstandingDemand {
  1355. // We hit an edge case here where we wrote but the consuming thread got interleaved
  1356. return .resumeProducer(onProduceMore)
  1357. } else {
  1358. self._state = .modify
  1359. streaming.producerContinuations.append((callbackToken.id, onProduceMore))
  1360. self._state = .streaming(streaming)
  1361. return .none
  1362. }
  1363. case .sourceFinished, .finished:
  1364. // Since we are unlocking between yielding and suspending the yield
  1365. // It can happen that the source got finished or the consumption fully finishes.
  1366. return .resumeProducerWithError(onProduceMore, AlreadyFinishedError())
  1367. case .modify:
  1368. fatalError("AsyncStream internal inconsistency")
  1369. }
  1370. }
  1371. /// Actions returned by `cancelProducer()`.
  1372. @usableFromInline
  1373. enum CancelProducerAction {
  1374. /// Indicates that the producer should be notified about cancellation.
  1375. case resumeProducerWithCancellationError((Result<Void, any Error>) -> Void)
  1376. }
  1377. @inlinable
  1378. mutating func cancelProducer(
  1379. callbackToken: Source.WriteResult.CallbackToken
  1380. ) -> CancelProducerAction? {
  1381. switch self._state {
  1382. case .initial:
  1383. // We need to transition to streaming before we can suspend
  1384. fatalError("AsyncStream internal inconsistency")
  1385. case .streaming(var streaming):
  1386. if let index = streaming.producerContinuations.firstIndex(where: {
  1387. $0.0 == callbackToken.id
  1388. }) {
  1389. // We have an enqueued producer that we need to resume now
  1390. self._state = .modify
  1391. let continuation = streaming.producerContinuations.remove(at: index).1
  1392. self._state = .streaming(streaming)
  1393. return .resumeProducerWithCancellationError(continuation)
  1394. } else {
  1395. // The task that yields was cancelled before yielding so the cancellation handler
  1396. // got invoked right away
  1397. self._state = .modify
  1398. streaming.cancelledAsyncProducers.append(callbackToken.id)
  1399. self._state = .streaming(streaming)
  1400. return .none
  1401. }
  1402. case .sourceFinished, .finished:
  1403. // Since we are unlocking between yielding and suspending the yield
  1404. // It can happen that the source got finished or the consumption fully finishes.
  1405. return .none
  1406. case .modify:
  1407. fatalError("AsyncStream internal inconsistency")
  1408. }
  1409. }
  1410. /// Actions returned by `finish()`.
  1411. @usableFromInline
  1412. enum FinishAction {
  1413. /// Indicates that `onTermination` should be called.
  1414. case callOnTermination((() -> Void)?)
  1415. /// Indicates that the consumer should be resumed with the failure, the producers
  1416. /// should be resumed with an error and `onTermination` should be called.
  1417. case resumeConsumerAndCallOnTermination(
  1418. consumerContinuation: CheckedContinuation<Element?, any Error>,
  1419. failure: (any Error)?,
  1420. onTermination: (() -> Void)?
  1421. )
  1422. /// Indicates that the producers should be resumed with an error.
  1423. case resumeProducers(
  1424. producerContinuations: [(Result<Void, any Error>) -> Void]
  1425. )
  1426. }
  1427. @inlinable
  1428. mutating func finish(_ failure: (any Error)?) -> FinishAction? {
  1429. switch self._state {
  1430. case .initial(let initial):
  1431. // Nothing was yielded nor did anybody call next
  1432. // This means we can transition to sourceFinished and store the failure
  1433. self._state = .sourceFinished(
  1434. .init(
  1435. iteratorInitialized: initial.iteratorInitialized,
  1436. buffer: .init(),
  1437. failure: failure,
  1438. onTermination: initial.onTermination
  1439. )
  1440. )
  1441. return .callOnTermination(initial.onTermination)
  1442. case .streaming(let streaming):
  1443. if let consumerContinuation = streaming.consumerContinuation {
  1444. // We have a continuation, this means our buffer must be empty
  1445. // Furthermore, we can now transition to finished
  1446. // and resume the continuation with the failure
  1447. precondition(streaming.buffer.isEmpty, "Expected an empty buffer")
  1448. precondition(
  1449. streaming.producerContinuations.isEmpty,
  1450. "Expected no suspended producers"
  1451. )
  1452. self._state = .finished(iteratorInitialized: streaming.iteratorInitialized)
  1453. return .resumeConsumerAndCallOnTermination(
  1454. consumerContinuation: consumerContinuation,
  1455. failure: failure,
  1456. onTermination: streaming.onTermination
  1457. )
  1458. } else {
  1459. self._state = .sourceFinished(
  1460. .init(
  1461. iteratorInitialized: streaming.iteratorInitialized,
  1462. buffer: streaming.buffer,
  1463. failure: failure,
  1464. onTermination: streaming.onTermination
  1465. )
  1466. )
  1467. return .resumeProducers(
  1468. producerContinuations: Array(streaming.producerContinuations.map { $0.1 })
  1469. )
  1470. }
  1471. case .sourceFinished, .finished:
  1472. // If the source has finished, finishing again has no effect.
  1473. return .none
  1474. case .modify:
  1475. fatalError("AsyncStream internal inconsistency")
  1476. }
  1477. }
  1478. /// Actions returned by `next()`.
  1479. @usableFromInline
  1480. enum NextAction {
  1481. /// Indicates that the element should be returned to the caller.
  1482. case returnElement(Element)
  1483. /// Indicates that the element should be returned to the caller and that all producers should be called.
  1484. case returnElementAndResumeProducers(Element, [(Result<Void, any Error>) -> Void])
  1485. /// Indicates that the `Error` should be returned to the caller and that `onTermination` should be called.
  1486. case returnErrorAndCallOnTermination((any Error)?, (() -> Void)?)
  1487. /// Indicates that the `nil` should be returned to the caller.
  1488. case returnNil
  1489. /// Indicates that the `Task` of the caller should be suspended.
  1490. case suspendTask
  1491. }
  1492. @inlinable
  1493. mutating func next() -> NextAction {
  1494. switch self._state {
  1495. case .initial(let initial):
  1496. // We are not interacting with the back-pressure strategy here because
  1497. // we are doing this inside `next(:)`
  1498. self._state = .streaming(
  1499. .init(
  1500. backPressureStrategy: initial.backPressureStrategy,
  1501. iteratorInitialized: initial.iteratorInitialized,
  1502. onTermination: initial.onTermination,
  1503. buffer: Deque<Element>(),
  1504. consumerContinuation: nil,
  1505. producerContinuations: .init(),
  1506. cancelledAsyncProducers: .init(),
  1507. hasOutstandingDemand: false
  1508. )
  1509. )
  1510. return .suspendTask
  1511. case .streaming(var streaming):
  1512. guard streaming.consumerContinuation == nil else {
  1513. // We have multiple AsyncIterators iterating the sequence
  1514. fatalError("AsyncStream internal inconsistency")
  1515. }
  1516. self._state = .modify
  1517. if let element = streaming.buffer.popFirst() {
  1518. // We have an element to fulfil the demand right away.
  1519. let shouldProduceMore = streaming.backPressureStrategy.didConsume(
  1520. bufferDepth: streaming.buffer.count
  1521. )
  1522. streaming.hasOutstandingDemand = shouldProduceMore
  1523. if shouldProduceMore {
  1524. // There is demand and we have to resume our producers
  1525. let producers = Array(streaming.producerContinuations.map { $0.1 })
  1526. streaming.producerContinuations.removeAll()
  1527. self._state = .streaming(streaming)
  1528. return .returnElementAndResumeProducers(element, producers)
  1529. } else {
  1530. // We don't have any new demand, so we can just return the element.
  1531. self._state = .streaming(streaming)
  1532. return .returnElement(element)
  1533. }
  1534. } else {
  1535. // There is nothing in the buffer to fulfil the demand so we need to suspend.
  1536. // We are not interacting with the back-pressure strategy here because
  1537. // we are doing this inside `suspendNext`
  1538. self._state = .streaming(streaming)
  1539. return .suspendTask
  1540. }
  1541. case .sourceFinished(var sourceFinished):
  1542. // Check if we have an element left in the buffer and return it
  1543. self._state = .modify
  1544. if let element = sourceFinished.buffer.popFirst() {
  1545. self._state = .sourceFinished(sourceFinished)
  1546. return .returnElement(element)
  1547. } else {
  1548. // We are returning the queued failure now and can transition to finished
  1549. self._state = .finished(iteratorInitialized: sourceFinished.iteratorInitialized)
  1550. return .returnErrorAndCallOnTermination(
  1551. sourceFinished.failure,
  1552. sourceFinished.onTermination
  1553. )
  1554. }
  1555. case .finished:
  1556. return .returnNil
  1557. case .modify:
  1558. fatalError("AsyncStream internal inconsistency")
  1559. }
  1560. }
  1561. /// Actions returned by `suspendNext()`.
  1562. @usableFromInline
  1563. enum SuspendNextAction {
  1564. /// Indicates that the consumer should be resumed.
  1565. case resumeConsumerWithElement(CheckedContinuation<Element?, any Error>, Element)
  1566. /// Indicates that the consumer and all producers should be resumed.
  1567. case resumeConsumerWithElementAndProducers(
  1568. CheckedContinuation<Element?, any Error>,
  1569. Element,
  1570. [(Result<Void, any Error>) -> Void]
  1571. )
  1572. /// Indicates that the consumer should be resumed with the failure and that `onTermination` should be called.
  1573. case resumeConsumerWithErrorAndCallOnTermination(
  1574. CheckedContinuation<Element?, any Error>,
  1575. (any Error)?,
  1576. (() -> Void)?
  1577. )
  1578. /// Indicates that the consumer should be resumed with `nil`.
  1579. case resumeConsumerWithNil(CheckedContinuation<Element?, any Error>)
  1580. }
  1581. @inlinable
  1582. mutating func suspendNext(
  1583. continuation: CheckedContinuation<Element?, any Error>
  1584. ) -> SuspendNextAction? {
  1585. switch self._state {
  1586. case .initial:
  1587. // We need to transition to streaming before we can suspend
  1588. preconditionFailure("AsyncStream internal inconsistency")
  1589. case .streaming(var streaming):
  1590. guard streaming.consumerContinuation == nil else {
  1591. // We have multiple AsyncIterators iterating the sequence
  1592. fatalError(
  1593. "This should never happen since we only allow a single Iterator to be created"
  1594. )
  1595. }
  1596. self._state = .modify
  1597. // We have to check here again since we might have a producer interleave next and suspendNext
  1598. if let element = streaming.buffer.popFirst() {
  1599. // We have an element to fulfil the demand right away.
  1600. let shouldProduceMore = streaming.backPressureStrategy.didConsume(
  1601. bufferDepth: streaming.buffer.count
  1602. )
  1603. streaming.hasOutstandingDemand = shouldProduceMore
  1604. if shouldProduceMore {
  1605. // There is demand and we have to resume our producers
  1606. let producers = Array(streaming.producerContinuations.map { $0.1 })
  1607. streaming.producerContinuations.removeAll()
  1608. self._state = .streaming(streaming)
  1609. return .resumeConsumerWithElementAndProducers(
  1610. continuation,
  1611. element,
  1612. producers
  1613. )
  1614. } else {
  1615. // We don't have any new demand, so we can just return the element.
  1616. self._state = .streaming(streaming)
  1617. return .resumeConsumerWithElement(continuation, element)
  1618. }
  1619. } else {
  1620. // There is nothing in the buffer to fulfil the demand so we to store the continuation.
  1621. streaming.consumerContinuation = continuation
  1622. self._state = .streaming(streaming)
  1623. return .none
  1624. }
  1625. case .sourceFinished(var sourceFinished):
  1626. // Check if we have an element left in the buffer and return it
  1627. self._state = .modify
  1628. if let element = sourceFinished.buffer.popFirst() {
  1629. self._state = .sourceFinished(sourceFinished)
  1630. return .resumeConsumerWithElement(continuation, element)
  1631. } else {
  1632. // We are returning the queued failure now and can transition to finished
  1633. self._state = .finished(iteratorInitialized: sourceFinished.iteratorInitialized)
  1634. return .resumeConsumerWithErrorAndCallOnTermination(
  1635. continuation,
  1636. sourceFinished.failure,
  1637. sourceFinished.onTermination
  1638. )
  1639. }
  1640. case .finished:
  1641. return .resumeConsumerWithNil(continuation)
  1642. case .modify:
  1643. fatalError("AsyncStream internal inconsistency")
  1644. }
  1645. }
  1646. /// Actions returned by `cancelNext()`.
  1647. @usableFromInline
  1648. enum CancelNextAction {
  1649. /// Indicates that the continuation should be resumed with a cancellation error, the producers should be finished and call onTermination.
  1650. case resumeConsumerWithCancellationErrorAndCallOnTermination(
  1651. CheckedContinuation<Element?, any Error>,
  1652. (() -> Void)?
  1653. )
  1654. /// Indicates that the producers should be finished and call onTermination.
  1655. case failProducersAndCallOnTermination([(Result<Void, any Error>) -> Void], (() -> Void)?)
  1656. }
  1657. @inlinable
  1658. mutating func cancelNext() -> CancelNextAction? {
  1659. switch self._state {
  1660. case .initial:
  1661. // We need to transition to streaming before we can suspend
  1662. fatalError("AsyncStream internal inconsistency")
  1663. case .streaming(let streaming):
  1664. self._state = .finished(iteratorInitialized: streaming.iteratorInitialized)
  1665. if let consumerContinuation = streaming.consumerContinuation {
  1666. precondition(
  1667. streaming.producerContinuations.isEmpty,
  1668. "Internal inconsistency. Unexpected producer continuations."
  1669. )
  1670. return .resumeConsumerWithCancellationErrorAndCallOnTermination(
  1671. consumerContinuation,
  1672. streaming.onTermination
  1673. )
  1674. } else {
  1675. return .failProducersAndCallOnTermination(
  1676. Array(streaming.producerContinuations.map { $0.1 }),
  1677. streaming.onTermination
  1678. )
  1679. }
  1680. case .sourceFinished, .finished:
  1681. return .none
  1682. case .modify:
  1683. fatalError("AsyncStream internal inconsistency")
  1684. }
  1685. }
  1686. }
  1687. }
  1688. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  1689. extension BufferedStream.Source: ClosableRPCWriterProtocol {
  1690. @inlinable
  1691. func finish() {
  1692. self.finish(throwing: nil)
  1693. }
  1694. @inlinable
  1695. func finish(throwing error: any Error) {
  1696. self.finish(throwing: error as (any Error)?)
  1697. }
  1698. }