|
| 1 | +// MIT License |
| 2 | +// |
| 3 | +// Copyright (c) 2022 Dan Federman |
| 4 | +// |
| 5 | +// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 | +// of this software and associated documentation files (the "Software"), to deal |
| 7 | +// in the Software without restriction, including without limitation the rights |
| 8 | +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 9 | +// copies of the Software, and to permit persons to whom the Software is |
| 10 | +// furnished to do so, subject to the following conditions: |
| 11 | +// |
| 12 | +// The above copyright notice and this permission notice shall be included in all |
| 13 | +// copies or substantial portions of the Software. |
| 14 | +// |
| 15 | +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 | +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 20 | +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 21 | +// SOFTWARE. |
| 22 | + |
| 23 | +/// A queue that executes asynchronous tasks enqueued from a nonisolated context. |
| 24 | +/// Tasks are guaranteed to begin executing in the order in which they are enqueued. However, if a task suspends it will allow tasks that were enqueued to begin executing. |
| 25 | +/// Asynchronous tasks sent to this queue execute as they would in an `actor` type, allowing for re-entrancy and non-FIFO behavior when an individual task suspends. |
| 26 | +public final class ActorQueue: Sendable { |
| 27 | + |
| 28 | + // MARK: Initialization |
| 29 | + |
| 30 | + /// Instantiates an asynchronous queue. |
| 31 | + /// - Parameter priority: The baseline priority of the tasks added to the asynchronous queue. |
| 32 | + public init(priority: TaskPriority? = nil) { |
| 33 | + var capturedTaskStreamContinuation: AsyncStream<@Sendable () async -> Void>.Continuation? = nil |
| 34 | + let taskStream = AsyncStream<@Sendable () async -> Void> { continuation in |
| 35 | + capturedTaskStreamContinuation = continuation |
| 36 | + } |
| 37 | + guard let capturedTaskStreamContinuation else { |
| 38 | + fatalError("Continuation not captured during stream creation!") |
| 39 | + } |
| 40 | + taskStreamContinuation = capturedTaskStreamContinuation |
| 41 | + |
| 42 | + streamTask = Task.detached(priority: priority) { |
| 43 | + actor ActorExecutor { |
| 44 | + init(priority: TaskPriority?) { |
| 45 | + self.priority = priority |
| 46 | + } |
| 47 | + |
| 48 | + func seriallyExecute(_ task: @escaping @Sendable () async -> Void) async { |
| 49 | + let semaphore = Semaphore() |
| 50 | + Task.detached(priority: priority) { |
| 51 | + await self.execute(task, afterSignaling: semaphore) |
| 52 | + } |
| 53 | + // Wait for the task to start. |
| 54 | + await semaphore.wait() |
| 55 | + } |
| 56 | + |
| 57 | + private let priority: TaskPriority? |
| 58 | + private func execute( |
| 59 | + _ task: @escaping @Sendable () async -> Void, |
| 60 | + afterSignaling semaphore: Semaphore |
| 61 | + ) async { |
| 62 | + // Signal that the task has started. |
| 63 | + await semaphore.signal() |
| 64 | + await task() |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + let executor = ActorExecutor(priority: priority) |
| 69 | + for await task in taskStream { |
| 70 | + await executor.seriallyExecute(task) |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + deinit { |
| 76 | + taskStreamContinuation.finish() |
| 77 | + } |
| 78 | + |
| 79 | + // MARK: Public |
| 80 | + |
| 81 | + /// Schedules an asynchronous task for execution and immediately returns. |
| 82 | + /// The schedueled task will not execute until all prior tasks have completed. |
| 83 | + /// - Parameter task: The task to enqueue. |
| 84 | + public func async(_ task: @escaping @Sendable () async -> Void) { |
| 85 | + taskStreamContinuation.yield(task) |
| 86 | + } |
| 87 | + |
| 88 | + /// Schedules an asynchronous throwing task and returns after the task is complete. |
| 89 | + /// The schedueled task will not execute until all prior tasks have completed. |
| 90 | + /// - Parameter task: The task to enqueue. |
| 91 | + /// - Returns: The value returned from the enqueued task. |
| 92 | + public func await<T>(_ task: @escaping @Sendable () async -> T) async -> T { |
| 93 | + await withUnsafeContinuation { continuation in |
| 94 | + taskStreamContinuation.yield { |
| 95 | + continuation.resume(returning: await task()) |
| 96 | + } |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + /// Schedules an asynchronous task and returns after the task is complete. |
| 101 | + /// The schedueled task will not execute until all prior tasks have completed. |
| 102 | + /// - Parameter task: The task to enqueue. |
| 103 | + /// - Returns: The value returned from the enqueued task. |
| 104 | + public func await<T>(_ task: @escaping @Sendable () async throws -> T) async throws -> T { |
| 105 | + try await withUnsafeThrowingContinuation { continuation in |
| 106 | + taskStreamContinuation.yield { |
| 107 | + do { |
| 108 | + continuation.resume(returning: try await task()) |
| 109 | + } catch { |
| 110 | + continuation.resume(throwing: error) |
| 111 | + } |
| 112 | + } |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + // MARK: Private |
| 117 | + |
| 118 | + private let streamTask: Task<Void, Never> |
| 119 | + private let taskStreamContinuation: AsyncStream<@Sendable () async -> Void>.Continuation |
| 120 | +} |
0 commit comments