-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathFIFOQueue.swift
More file actions
304 lines (288 loc) · 11.6 KB
/
FIFOQueue.swift
File metadata and controls
304 lines (288 loc) · 11.6 KB
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
// MIT License
//
// Copyright (c) 2022 Dan Federman
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
/// A queue that executes asynchronous tasks enqueued from a nonisolated context in FIFO order.
/// Tasks are guaranteed to begin _and end_ executing in the order in which they are enqueued.
/// Asynchronous tasks sent to this queue work as they would in a `DispatchQueue` type. Attempting to `enqueueAndWait` this queue from a task executing on this queue will result in a deadlock.
public final class FIFOQueue: Sendable {
// MARK: Initialization
/// Instantiates a FIFO queue.
/// - Parameter name: Human readable name of the queue.
/// - Parameter priority: The baseline priority of the tasks added to the asynchronous queue.
public init(name: String? = nil, priority: TaskPriority? = nil) {
let (taskStream, taskStreamContinuation) = AsyncStream<FIFOTask>.makeStream()
self.taskStreamContinuation = taskStreamContinuation
Task.detached(name: name, priority: priority) {
for await fifoTask in taskStream {
await fifoTask.task()
}
}
}
deinit {
taskStreamContinuation.finish()
}
// MARK: Fileprivate
fileprivate struct FIFOTask: Sendable {
init(task: @escaping @Sendable () async -> Void) {
self.task = task
}
let task: @Sendable () async -> Void
}
fileprivate let taskStreamContinuation: AsyncStream<FIFOTask>.Continuation
}
extension Task {
/// Runs the given nonthrowing operation asynchronously
/// as part of a new top-level task that inherits the current isolated context.
/// The operation will not execute until all prior tasks – including
/// suspended tasks – have completed.
///
/// Use this function when creating asynchronous work
/// that operates on behalf of the synchronous function that calls it.
/// Like `Task.detached(priority:operation:)`,
/// this function creates a separate, top-level task.
/// Unlike `Task.detached(priority:operation:)`,
/// the task created by `Task.init(priority:operation:)`
/// inherits the priority and actor context of the caller,
/// so the operation is treated more like an asynchronous extension
/// to the synchronous operation.
///
/// You need to keep a reference to the task
/// if you want to cancel it by calling the `Task.cancel()` method.
/// Discarding your reference to a detached task
/// doesn't implicitly cancel that task,
/// it only makes it impossible for you to explicitly cancel the task.
///
/// - Parameters:
/// - name: Human readable name of the task.
/// - priority: The priority of the task.
/// - fifoQueue: The queue on which to enqueue the task.
/// - operation: The operation to perform.
@discardableResult
public init(
name: String? = nil,
priority: TaskPriority? = nil,
on fifoQueue: FIFOQueue,
@_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> Success,
) where Failure == Never {
let delivery = Delivery<Success, Failure>()
let semaphore = Semaphore()
let executeOnce = UnsafeClosureHolder(operation: operation)
let task = FIFOQueue.FIFOTask {
await semaphore.wait()
await delivery.execute({ @Sendable delivery in
await delivery.sendValue(executeOnce.operation())
}, in: delivery, name: name, priority: priority).value
}
fifoQueue.taskStreamContinuation.yield(task)
self.init(name: name) {
await withTaskCancellationHandler(
operation: {
await semaphore.signal()
return await delivery.getValue()
},
onCancel: delivery.cancel,
)
}
}
/// Runs the given throwing operation asynchronously
/// as part of a new top-level task that inherits the current isolated context.
/// The operation will not execute until all prior tasks – including
/// suspended tasks – have completed.
///
/// Use this function when creating asynchronous work
/// that operates on behalf of the synchronous function that calls it.
/// Like `Task.detached(priority:operation:)`,
/// this function creates a separate, top-level task.
/// Unlike `Task.detached(priority:operation:)`,
/// the task created by `Task.init(priority:operation:)`
/// inherits the priority and actor context of the caller,
/// so the operation is treated more like an asynchronous extension
/// to the synchronous operation.
///
/// You need to keep a reference to the task
/// if you want to cancel it by calling the `Task.cancel()` method.
/// Discarding your reference to a detached task
/// doesn't implicitly cancel that task,
/// it only makes it impossible for you to explicitly cancel the task.
///
/// - Parameters:
/// - name: Human readable name of the task.
/// - priority: The priority of the task.
/// - fifoQueue: The queue on which to enqueue the task.
/// - operation: The operation to perform.
@discardableResult
public init(
name: String? = nil,
priority: TaskPriority? = nil,
on fifoQueue: FIFOQueue,
@_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async throws -> Success,
) where Failure == any Error {
let delivery = Delivery<Success, Failure>()
let semaphore = Semaphore()
let executeOnce = UnsafeThrowingClosureHolder(operation: operation)
let task = FIFOQueue.FIFOTask {
await semaphore.wait()
await delivery.execute({ @Sendable delivery in
do {
try await delivery.sendValue(executeOnce.operation())
} catch {
delivery.sendFailure(error)
}
}, in: delivery, name: name, priority: priority).value
}
fifoQueue.taskStreamContinuation.yield(task)
self.init(name: name) {
try await withTaskCancellationHandler(
operation: {
await semaphore.signal()
return try await delivery.getValue()
},
onCancel: delivery.cancel,
)
}
}
/// Runs the given nonthrowing operation asynchronously
/// as part of a new top-level task isolated to the given actor.
/// The operation will not execute until all prior tasks – including
/// suspended tasks – have completed.
///
/// Use this function when creating asynchronous work
/// that operates on behalf of the synchronous function that calls it.
/// Like `Task.detached(priority:operation:)`,
/// this function creates a separate, top-level task.
/// Unlike `Task.detached(priority:operation:)`,
/// the task created by `Task.init(priority:operation:)`
/// inherits the priority and actor context of the caller,
/// so the operation is treated more like an asynchronous extension
/// to the synchronous operation.
///
/// You need to keep a reference to the task
/// if you want to cancel it by calling the `Task.cancel()` method.
/// Discarding your reference to a detached task
/// doesn't implicitly cancel that task,
/// it only makes it impossible for you to explicitly cancel the task.
///
/// - Parameters:
/// - name: Human readable name of the task.
/// - priority: The priority of the task.
/// Pass `nil` to use the priority from `Task.currentPriority`.
/// - fifoQueue: The queue on which to enqueue the task.
/// - isolatedActor: The actor to which the operation is isolated.
/// - operation: The operation to perform.
@discardableResult
public init<ActorType: Actor>(
name: String? = nil,
priority: TaskPriority? = nil,
on fifoQueue: FIFOQueue,
isolatedTo isolatedActor: ActorType,
operation: @Sendable @escaping (isolated ActorType) async -> Success,
) where Failure == Never {
let delivery = Delivery<Success, Failure>()
let semaphore = Semaphore()
let task = FIFOQueue.FIFOTask {
await semaphore.wait()
await delivery.execute({ @Sendable isolatedActor in
await delivery.sendValue(operation(isolatedActor))
}, in: isolatedActor, name: name, priority: priority).value
}
fifoQueue.taskStreamContinuation.yield(task)
self.init(name: name) {
await withTaskCancellationHandler(
operation: {
await semaphore.signal()
return await delivery.getValue()
},
onCancel: delivery.cancel,
)
}
}
/// Runs the given throwing operation asynchronously
/// as part of a new top-level task isolated to the given actor.
/// The operation will not execute until all prior tasks – including
/// suspended tasks – have completed.
///
/// Use this function when creating asynchronous work
/// that operates on behalf of the synchronous function that calls it.
/// Like `Task.detached(priority:operation:)`,
/// this function creates a separate, top-level task.
/// Unlike `Task.detached(priority:operation:)`,
/// the task created by `Task.init(priority:operation:)`
/// inherits the priority and actor context of the caller,
/// so the operation is treated more like an asynchronous extension
/// to the synchronous operation.
///
/// You need to keep a reference to the task
/// if you want to cancel it by calling the `Task.cancel()` method.
/// Discarding your reference to a detached task
/// doesn't implicitly cancel that task,
/// it only makes it impossible for you to explicitly cancel the task.
///
/// - Parameters:
/// - name: Human readable name of the task.
/// - priority: The priority of the task.
/// Pass `nil` to use the priority from `Task.currentPriority`.
/// - fifoQueue: The queue on which to enqueue the task.
/// - isolatedActor: The actor to which the operation is isolated.
/// - operation: The operation to perform.
@discardableResult
public init<ActorType: Actor>(
name: String? = nil,
priority: TaskPriority? = nil,
on fifoQueue: FIFOQueue,
isolatedTo isolatedActor: ActorType,
operation: @Sendable @escaping (isolated ActorType) async throws -> Success,
) where Failure == any Error {
let delivery = Delivery<Success, Failure>()
let semaphore = Semaphore()
let task = FIFOQueue.FIFOTask {
await semaphore.wait()
await delivery.execute({ @Sendable isolatedActor in
do {
try await delivery.sendValue(operation(isolatedActor))
} catch {
await delivery.sendFailure(error)
}
}, in: isolatedActor, name: name, priority: priority).value
}
fifoQueue.taskStreamContinuation.yield(task)
self.init(name: name, priority: priority) {
try await withTaskCancellationHandler(
operation: {
await semaphore.signal()
return try await delivery.getValue()
},
onCancel: delivery.cancel,
)
}
}
}
private struct UnsafeClosureHolder<Success: Sendable>: @unchecked Sendable {
init(operation: sending @escaping @isolated(any) () async -> Success) {
self.operation = operation
}
let operation: @isolated(any) () async -> Success
}
private struct UnsafeThrowingClosureHolder<Success: Sendable>: @unchecked Sendable {
init(operation: sending @escaping @isolated(any) () async throws -> Success) {
self.operation = operation
}
let operation: @isolated(any) () async throws -> Success
}