-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathAsyncThrowingBufferedChannel.swift
268 lines (238 loc) · 7.54 KB
/
AsyncThrowingBufferedChannel.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
//
// AsyncThrowingBufferedChannel.swift
//
//
// Created by Thibault Wittemberg on 07/01/2022.
//
import DequeModule
import OrderedCollections
/// A channel for sending elements from one task to another.
///
/// The `AsyncThrowingBufferedChannel` class is intended to be used as a communication type between tasks,
/// particularly when one task produces values and another task consumes those values. The values are
/// buffered awaiting a consumer to consume them from iteration.
/// `finish()` and `fail()` induce a terminal state and no further elements can be sent.
///
/// ```swift
/// let channel = AsyncThrowingBufferedChannel<Int, Error>()
///
/// Task {
/// do {
/// for try await element in channel {
/// print(element) // will print 1, 2, 3
/// }
/// } catch {
/// print(error) // will catch MyError
/// }
/// }
///
/// sut.send(1)
/// sut.send(2)
/// sut.send(3)
/// sut.fail(MyError())
/// ```
public final class AsyncThrowingBufferedChannel<Element, Failure: Error>: AsyncSequence, Sendable where Element: Sendable {
public typealias Element = Element
public typealias AsyncIterator = Iterator
enum Termination: Sendable {
case finished
case failure(Failure)
}
struct Awaiting: Hashable {
let id: Int
let continuation: UnsafeContinuation<Element?, Error>?
static func placeHolder(id: Int) -> Awaiting {
Awaiting(id: id, continuation: nil)
}
func hash(into hasher: inout Hasher) {
hasher.combine(self.id)
}
static func == (lhs: Awaiting, rhs: Awaiting) -> Bool {
lhs.id == rhs.id
}
}
enum SendDecision {
case resume(Awaiting, Element)
case finish([Awaiting])
case fail([Awaiting], Error)
case nothing
}
enum AwaitingDecision {
case resume(Element?)
case fail(Error)
case suspend
}
enum Value {
case element(Element)
case termination(Termination)
}
enum State: @unchecked Sendable {
case idle
case queued(Deque<Value>)
case awaiting(OrderedSet<Awaiting>)
case terminated(Termination)
static var initial: State {
.idle
}
}
let ids: ManagedCriticalState<Int>
let state: ManagedCriticalState<State>
public init() {
self.ids = ManagedCriticalState(0)
self.state = ManagedCriticalState(.initial)
}
func generateId() -> Int {
self.ids.withCriticalRegion { ids in
ids += 1
return ids
}
}
var hasBufferedElements: Bool {
self.state.withCriticalRegion { state in
switch state {
case .idle:
return false
case .queued(let values) where !values.isEmpty:
return true
case .awaiting, .queued:
return false
case .terminated:
return true
}
}
}
func send(_ value: Value) {
let decision = self.state.withCriticalRegion { state -> SendDecision in
switch (state, value) {
case (.idle, .element):
state = .queued([value])
return .nothing
case (.idle, .termination(let termination)):
state = .terminated(termination)
return .nothing
case (.queued(var values), _):
values.append(value)
state = .queued(values)
return .nothing
case (.awaiting(var awaitings), .element(let element)):
let awaiting = awaitings.removeFirst()
if awaitings.isEmpty {
state = .idle
} else {
state = .awaiting(awaitings)
}
return .resume(awaiting, element)
case (.awaiting(let awaitings), .termination(.failure(let error))):
state = .terminated(.failure(error))
return .fail(Array(awaitings), error)
case (.awaiting(let awaitings), .termination(.finished)):
state = .terminated(.finished)
return .finish(Array(awaitings))
case (.terminated, _):
return .nothing
}
}
switch decision {
case .nothing:
break
case .finish(let awaitings):
awaitings.forEach { $0.continuation?.resume(returning: nil) }
case .fail(let awaitings, let error):
awaitings.forEach { $0.continuation?.resume(throwing: error) }
case let .resume(awaiting, element):
awaiting.continuation?.resume(returning: element)
}
}
public func send(_ element: Element) {
self.send(.element(element))
}
public func fail(_ error: Failure) where Failure == Error {
self.send(.termination(.failure(error)))
}
public func finish() {
self.send(.termination(.finished))
}
func next(onSuspend: (() -> Void)? = nil) async throws -> Element? {
let awaitingId = self.generateId()
let cancellation = ManagedCriticalState<Bool>(false)
return try await withTaskCancellationHandler { [state] in
let awaiting = state.withCriticalRegion { state -> Awaiting? in
cancellation.withCriticalRegion { cancellation in
cancellation = true
}
switch state {
case .awaiting(var awaitings):
let awaiting = awaitings.remove(.placeHolder(id: awaitingId))
if awaitings.isEmpty {
state = .idle
} else {
state = .awaiting(awaitings)
}
return awaiting
default:
return nil
}
}
awaiting?.continuation?.resume(returning: nil)
} operation: {
try await withUnsafeThrowingContinuation { [state] (continuation: UnsafeContinuation<Element?, Error>) in
let decision = state.withCriticalRegion { state -> AwaitingDecision in
let isCancelled = cancellation.withCriticalRegion { $0 }
guard !isCancelled else { return .resume(nil) }
switch state {
case .idle:
state = .awaiting([Awaiting(id: awaitingId, continuation: continuation)])
return .suspend
case .queued(var values):
let value = values.popFirst()
switch value {
case .termination(.finished):
state = .terminated(.finished)
return .resume(nil)
case .termination(.failure(let error)):
state = .terminated(.failure(error))
return .fail(error)
case .element(let element) where !values.isEmpty:
state = .queued(values)
return .resume(element)
case .element(let element):
state = .idle
return .resume(element)
default:
state = .idle
return .suspend
}
case .awaiting(var awaitings):
awaitings.updateOrAppend(Awaiting(id: awaitingId, continuation: continuation))
state = .awaiting(awaitings)
return .suspend
case .terminated(.finished):
return .resume(nil)
case .terminated(.failure(let error)):
return .fail(error)
}
}
switch decision {
case .resume(let element): continuation.resume(returning: element)
case .fail(let error): continuation.resume(throwing: error)
case .suspend:
onSuspend?()
}
}
}
}
public func makeAsyncIterator() -> AsyncIterator {
Iterator(
channel: self
)
}
public struct Iterator: AsyncIteratorProtocol, Sendable {
let channel: AsyncThrowingBufferedChannel<Element, Failure>
var hasBufferedElements: Bool {
self.channel.hasBufferedElements
}
public func next() async throws -> Element? {
try await self.channel.next()
}
}
}