Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 48 additions & 117 deletions Sources/AsyncQueue/ActorQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,24 +55,7 @@ public final class ActorQueue<ActorType: Actor>: @unchecked Sendable {
// MARK: Initialization

/// Instantiates an actor queue.
/// - Parameter name: Human readable name of the queue.
public init(name: String? = nil) {
let (taskStream, taskStreamContinuation) = AsyncStream<ActorTask>.makeStream()
self.taskStreamContinuation = taskStreamContinuation

Task(name: name) {
// In an ideal world, we would isolate this `for await` loop to the `ActorType`.
// However, there's no good way to do that without retaining the actor and creating a cycle.
for await actorTask in taskStream {
// Await switching to the ActorType context.
await actorTask.task(actorTask.executionContext)
}
}
}

deinit {
taskStreamContinuation.finish()
}
public init() {}

// MARK: Public

Expand All @@ -87,9 +70,12 @@ public final class ActorQueue<ActorType: Actor>: @unchecked Sendable {
weakExecutionContext = actor
}

// MARK: Fileprivate
// MARK: Internal

/// Hands out turns to begin executing on the adopted actor, in the order in which tasks are enqueued.
let turns = Turns()

fileprivate let taskStreamContinuation: AsyncStream<ActorTask>.Continuation
// MARK: Fileprivate

/// The actor on whose isolated context our tasks run, force-unwrapped.
/// Utilize this accessor to retrieve the weak execution context in order to avoid repeating the below comment.
Expand All @@ -100,19 +86,6 @@ public final class ActorQueue<ActorType: Actor>: @unchecked Sendable {
weakExecutionContext!
}

fileprivate struct ActorTask: Sendable {
init(
executionContext: ActorType,
task: @escaping @Sendable (isolated ActorType) async -> Void,
) {
self.executionContext = executionContext
self.task = task
}

let executionContext: ActorType
let task: @Sendable (isolated ActorType) async -> Void
}

// MARK: Private

/// The actor on whose isolated context our tasks run.
Expand Down Expand Up @@ -158,26 +131,11 @@ extension Task {
on actorQueue: ActorQueue<ActorType>,
operation: @Sendable @escaping (isolated ActorType) async -> Success,
) where Failure == Never {
let delivery = Delivery<Success, Failure>()
let semaphore = Semaphore()
let task = ActorQueue<ActorType>.ActorTask(
executionContext: actorQueue.executionContext,
task: { executionContext in
await semaphore.wait()
delivery.execute({ @Sendable executionContext in
await delivery.sendValue(operation(executionContext))
}, in: executionContext, name: name, priority: priority)
},
)
actorQueue.taskStreamContinuation.yield(task)
let executionContext = actorQueue.executionContext
let turn = actorQueue.turns.reserve()
self.init(name: name, priority: priority) {
await withTaskCancellationHandler(
operation: {
await semaphore.signal()
return await delivery.getValue()
},
onCancel: delivery.cancel,
)
await turn.begin()
return await execute(operation, on: executionContext, endingTurn: turn)
}
}

Expand Down Expand Up @@ -215,30 +173,11 @@ extension Task {
on actorQueue: ActorQueue<ActorType>,
operation: @escaping @Sendable (isolated ActorType) async throws -> Success,
) where Failure == any Error {
let delivery = Delivery<Success, Failure>()
let semaphore = Semaphore()
let task = ActorQueue<ActorType>.ActorTask(
executionContext: actorQueue.executionContext,
task: { executionContext in
await semaphore.wait()
delivery.execute({ @Sendable executionContext in
do {
try await delivery.sendValue(operation(executionContext))
} catch {
await delivery.sendFailure(error)
}
}, in: executionContext, name: name, priority: priority)
},
)
actorQueue.taskStreamContinuation.yield(task)
let executionContext = actorQueue.executionContext
let turn = actorQueue.turns.reserve()
self.init(name: name, priority: priority) {
try await withTaskCancellationHandler(
operation: {
await semaphore.signal()
return try await delivery.getValue()
},
onCancel: delivery.cancel,
)
await turn.begin()
return try await execute(operation, on: executionContext, endingTurn: turn)
}
}

Expand Down Expand Up @@ -276,26 +215,10 @@ extension Task {
on actorQueue: ActorQueue<MainActor>,
operation: @MainActor @escaping () async -> Success,
) where Failure == Never {
let delivery = Delivery<Success, Failure>()
let semaphore = Semaphore()
let task = ActorQueue<MainActor>.ActorTask(
executionContext: actorQueue.executionContext,
task: { executionContext in
await semaphore.wait()
delivery.execute({ @Sendable executionContext in
await delivery.sendValue(operation())
}, in: executionContext, name: name, priority: priority)
},
)
actorQueue.taskStreamContinuation.yield(task)
let turn = actorQueue.turns.reserve()
self.init(name: name, priority: priority) {
await withTaskCancellationHandler(
operation: {
await semaphore.signal()
return await delivery.getValue()
},
onCancel: delivery.cancel,
)
await turn.begin()
return await executeOnMainActor(operation, endingTurn: turn)
}
}

Expand Down Expand Up @@ -333,34 +256,42 @@ extension Task {
on actorQueue: ActorQueue<MainActor>,
operation: @escaping @MainActor () async throws -> Success,
) where Failure == any Error {
let delivery = Delivery<Success, Failure>()
let semaphore = Semaphore()
let task = ActorQueue<MainActor>.ActorTask(
executionContext: actorQueue.executionContext,
task: { executionContext in
await semaphore.wait()
delivery.execute({ @Sendable executionContext in
do {
try await delivery.sendValue(operation())
} catch {
await delivery.sendFailure(error)
}
}, in: executionContext, name: name, priority: priority)
},
)
actorQueue.taskStreamContinuation.yield(task)
let turn = actorQueue.turns.reserve()
self.init(name: name, priority: priority) {
try await withTaskCancellationHandler(
operation: {
await semaphore.signal()
return try await delivery.getValue()
},
onCancel: delivery.cancel,
)
await turn.begin()
return try await executeOnMainActor(operation, endingTurn: turn)
}
}
}

// MARK: - Execution

/// Executes `operation` on `actor`, ending `turn` as soon as the task is isolated to `actor`.
///
/// Ending the turn lets the next enqueued task hop to `actor`. That task cannot execute on `actor`
/// until `operation` suspends or returns, so tasks begin executing in the order in which they were enqueued.
private func execute<ActorType: Actor, Success>(
_ operation: (isolated ActorType) async throws -> Success,
on actor: isolated ActorType,
endingTurn turn: Turn,
) async rethrows -> Success {
turn.end()
return try await operation(actor)
}

/// Executes `operation` on the main actor, ending `turn` as soon as the task is isolated to the main actor.
///
/// Ending the turn lets the next enqueued task hop to the main actor. That task cannot execute on the main actor
/// until `operation` suspends or returns, so tasks begin executing in the order in which they were enqueued.
@MainActor
private func executeOnMainActor<Success>(
_ operation: @MainActor () async throws -> Success,
endingTurn turn: Turn,
) async rethrows -> Success {
turn.end()
return try await operation()
}

extension MainActor {
/// A global instance of an `ActorQueue<MainActor>`.
public static var queue: ActorQueue<MainActor> {
Expand Down
126 changes: 126 additions & 0 deletions Sources/AsyncQueue/Utilities/Turns.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// MIT License
//
// Copyright (c) 2026 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.

import Synchronization

/// Hands out turns in the order in which they are reserved.
///
/// Each turn begins once every turn reserved before it has ended.
final class Turns: Sendable {
// MARK: Initialization

init() {}

// MARK: Internal

/// Reserves the next turn.
func reserve() -> Turn {
let ended = Signal()
let previousTurnEnded = lastTurnEnded.withLock { lastTurnEnded in
defer { lastTurnEnded = ended }
return lastTurnEnded
}
return Turn(previousTurnEnded: previousTurnEnded, ended: ended)
}

// MARK: Private

/// The signal fired when the most recently reserved turn ends.
private let lastTurnEnded = Mutex<Signal?>(nil)
}

/// A turn reserved from a `Turns` instance.
struct Turn: Sendable {
// MARK: Initialization

fileprivate init(previousTurnEnded: Signal?, ended: Signal) {
self.previousTurnEnded = previousTurnEnded
self.ended = ended
}

// MARK: Internal

/// Suspends until every earlier turn has ended.
/// - Warning: Must be called at most once.
func begin() async {
await previousTurnEnded?.wait()
}

/// Ends this turn, allowing the next turn to begin.
func end() {
ended.fire()
}

// MARK: Private

private let previousTurnEnded: Signal?
private let ended: Signal
}

// MARK: - Signal

/// A one-shot latch that a single waiter can await.
private final class Signal: Sendable {
// MARK: Initialization

init() {}

// MARK: Internal

/// Opens the latch, resuming the waiter if there is one.
func fire() {
let waiter = state.withLock { state in
state.isFired = true
defer { state.waiter = nil }
return state.waiter
}
// Resume the waiter only after releasing the lock: never resume a continuation while holding a lock.
waiter?.resume()
}

/// Suspends until the latch is open. Returns immediately if it is already open.
/// - Warning: At most one task may wait on a signal.
func wait() async {
// A continuation resumed before its task suspends does not suspend the task,
// so an open latch costs no suspension even without a separate fast path.
await withUnsafeContinuation { (continuation: UnsafeContinuation<Void, Never>) in
let isFired = state.withLock { state in
if !state.isFired {
state.waiter = continuation
}
return state.isFired
}
if isFired {
continuation.resume()
}
}
}

// MARK: Private

private struct State {
var isFired = false
var waiter: UnsafeContinuation<Void, Never>?
}

private let state = Mutex(State())
}
Loading
Loading