|
| 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 subsequently enqueued tasks 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 | +/// |
| 27 | +/// An `ActorQueue` is used to ensure tasks sent from a nonisolated context to a single `actor`'s isolated context begin execution in order. |
| 28 | +/// Here is an example of how an `ActorQueue` should be utilized within an `actor`: |
| 29 | +/// ```swift |
| 30 | +/// public actor LogStore { |
| 31 | +/// |
| 32 | +/// nonisolated |
| 33 | +/// public func log(_ message: String) { |
| 34 | +/// queue.async { |
| 35 | +/// await self.append(message) |
| 36 | +/// } |
| 37 | +/// } |
| 38 | +/// |
| 39 | +/// nonisolated |
| 40 | +/// public func retrieveLogs() async -> [String] { |
| 41 | +/// await queue.await { await self.logs } |
| 42 | +/// } |
| 43 | +/// |
| 44 | +/// private func append(_ message: String) { |
| 45 | +/// logs.append(message) |
| 46 | +/// } |
| 47 | +/// |
| 48 | +/// private let queue = ActorQueue() |
| 49 | +/// private var logs = [String]() |
| 50 | +/// } |
| 51 | +/// ``` |
| 52 | +/// |
| 53 | +/// - Warning: Execution order is not guaranteed unless the enqueued tasks interact with a single `actor` instance. |
| 54 | +public final class ActorQueue { |
| 55 | + |
| 56 | + // MARK: Initialization |
| 57 | + |
| 58 | + /// Instantiates an actor queue. |
| 59 | + /// - Parameter priority: The baseline priority of the tasks added to the asynchronous queue. |
| 60 | + public init(priority: TaskPriority? = nil) { |
| 61 | + var capturedTaskStreamContinuation: AsyncStream<@Sendable () async -> Void>.Continuation? = nil |
| 62 | + let taskStream = AsyncStream<@Sendable () async -> Void> { continuation in |
| 63 | + capturedTaskStreamContinuation = continuation |
| 64 | + } |
| 65 | + // Continuation will be captured during stream creation, so it is safe to force unwrap here. |
| 66 | + // If this force-unwrap fails, something is fundamentally broken in the Swift runtime. |
| 67 | + taskStreamContinuation = capturedTaskStreamContinuation! |
| 68 | + |
| 69 | + Task.detached(priority: priority) { |
| 70 | + let executor = ActorExecutor() |
| 71 | + for await task in taskStream { |
| 72 | + await executor.suspendUntilStarted(task) |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + deinit { |
| 78 | + taskStreamContinuation.finish() |
| 79 | + } |
| 80 | + |
| 81 | + // MARK: Public |
| 82 | + |
| 83 | + /// Schedules an asynchronous task for execution and immediately returns. |
| 84 | + /// The scheduled task will not execute until all prior tasks have completed or suspended. |
| 85 | + /// - Parameter task: The task to enqueue. |
| 86 | + public func async(_ task: @escaping @Sendable () async -> Void) { |
| 87 | + taskStreamContinuation.yield(task) |
| 88 | + } |
| 89 | + |
| 90 | + /// Schedules an asynchronous task and returns after the task is complete. |
| 91 | + /// The scheduled task will not execute until all prior tasks have completed or suspended. |
| 92 | + /// - Parameter task: The task to enqueue. |
| 93 | + /// - Returns: The value returned from the enqueued task. |
| 94 | + public func await<T>(_ task: @escaping @Sendable () async -> T) async -> T { |
| 95 | + await withUnsafeContinuation { continuation in |
| 96 | + taskStreamContinuation.yield { |
| 97 | + continuation.resume(returning: await task()) |
| 98 | + } |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + /// Schedules an asynchronous throwing task and returns after the task is complete. |
| 103 | + /// The scheduled task will not execute until all prior tasks have completed or suspended. |
| 104 | + /// - Parameter task: The task to enqueue. |
| 105 | + /// - Returns: The value returned from the enqueued task. |
| 106 | + public func await<T>(_ task: @escaping @Sendable () async throws -> T) async throws -> T { |
| 107 | + try await withUnsafeThrowingContinuation { continuation in |
| 108 | + taskStreamContinuation.yield { |
| 109 | + do { |
| 110 | + continuation.resume(returning: try await task()) |
| 111 | + } catch { |
| 112 | + continuation.resume(throwing: error) |
| 113 | + } |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + // MARK: Private |
| 119 | + |
| 120 | + private let taskStreamContinuation: AsyncStream<@Sendable () async -> Void>.Continuation |
| 121 | + |
| 122 | + // MARK: - ActorExecutor |
| 123 | + |
| 124 | + private actor ActorExecutor { |
| 125 | + func suspendUntilStarted(_ task: @escaping @Sendable () async -> Void) async { |
| 126 | + // Suspend the calling code until our enqueued task starts. |
| 127 | + await withUnsafeContinuation { continuation in |
| 128 | + // Utilize the serial (but not FIFO) Actor context to execute the task without requiring the calling method to wait for the task to complete. |
| 129 | + Task { |
| 130 | + // Force this task to execute within the ActorExecutor's context by accessing an ivar on the instance. |
| 131 | + // This works around a bug when compiling with Xcode 14.1: https://github.com/apple/swift/issues/62503 |
| 132 | + _ = void |
| 133 | + |
| 134 | + // Signal that the task has started. As long as the `task` below interacts with another `actor` the order of execution is guaranteed. |
| 135 | + continuation.resume() |
| 136 | + await task() |
| 137 | + } |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + private let void: Void = () |
| 142 | + } |
| 143 | + |
| 144 | +} |
0 commit comments