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
24 changes: 15 additions & 9 deletions Sources/AsyncQueue/Utilities/Delivery.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,13 @@ actor Delivery<Success: Sendable, Failure: Error> {
}

nonisolated func cancel() {
taskContainer.withLock {
let task = taskContainer.withLock {
$0.isCancelled = true
$0.task?.cancel()
return $0.task
}
// Cancelling a task synchronously runs its cancellation handlers, which may cancel other tasks.
// Cancel only after releasing the lock so that those handlers can never re-enter it.
task?.cancel()
}

@discardableResult
Expand All @@ -50,11 +53,13 @@ actor Delivery<Success: Sendable, Failure: Error> {
let task = Task(name: name, priority: priority) {
await operation(context)
}
taskContainer.withLock {
if $0.isCancelled {
task.cancel()
}
let isCancelled = taskContainer.withLock {
$0.task = task
return $0.isCancelled
}
if isCancelled {
// Cancel only after releasing the lock. See `cancel()`.
task.cancel()
}
return task
}
Expand Down Expand Up @@ -120,8 +125,10 @@ private struct Locked<State>: @unchecked Sendable {
container = .init(value: value)
}

/// Executes `body` while holding the lock.
/// - Warning: `body` must not cancel a task, resume a continuation, or otherwise call out to code that may re-enter this lock.
func withLock<R>(_ body: @Sendable (inout State) throws -> R) rethrows -> R where R: Sendable {
try lockQueue.sync {
try container.lockQueue.sync {
var value = container.unsafeValue
let returnValue = try body(&value)
container.unsafeValue = value
Expand All @@ -137,7 +144,6 @@ private struct Locked<State>: @unchecked Sendable {
}

var unsafeValue: State
let lockQueue = DispatchQueue(label: "Locked.lockQueue", target: DispatchQueue.global())
}
}

private let lockQueue = DispatchQueue(label: "LockedValue.lockQueue", target: DispatchQueue.global())
40 changes: 40 additions & 0 deletions Tests/AsyncQueueTests/ActorQueueTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,46 @@ struct ActorQueueTests {
try? await task.value
}

@MainActor
@Test
func mainTask_cancelledWhileMainActorIsBusy_executesOperationCancelled() async {
let task = Task(on: MainActor.queue) {
Task.isCancelled
}

// The task's operation cannot begin until this test suspends and frees the main actor,
// so this cancels the task before its operation begins.
task.cancel()

#expect(await task.value)
}

@Test
func task_canBeCancelledFromCancellationHandlerOfAnotherQueuedTask() async {
let taskStarted = Semaphore()
let innerTaskStarted = Semaphore()
let task = Task(on: systemUnderTest) { [systemUnderTest] _ in
let innerTask = Task(on: systemUnderTest) { _ in
await innerTaskStarted.signal()
await suspendUntilCancelled()
return Task.isCancelled
}
return await withTaskCancellationHandler {
// Wait for the inner operation to start, so that cancelling the inner task runs its cancellation handler.
await innerTaskStarted.wait()
await taskStarted.signal()
return await innerTask.value
} onCancel: {
innerTask.cancel()
}
}
await taskStarted.wait()
task.cancel()
// The inner task returns only once it is cancelled, so if cancellation does not reach it, this test hangs rather
// than failing the expectation.
#expect(await task.value)
}

@Test
func task_canReturn() async {
let expectedValue = UUID()
Expand Down
34 changes: 34 additions & 0 deletions Tests/AsyncQueueTests/DeliveryTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,38 @@ struct DeliveryTests {
try await systemUnderTest.getValue()
})
}

@Test
func getValue_whenValueIsSentAfterGetValueSuspends() async {
let systemUnderTest = Delivery<Bool, Never>()
await #expect(valueOnceGetValueSuspends(on: systemUnderTest) == true)
}

@Test
func getValueThrowing_whenFailureIsSentAfterGetValueSuspends() async throws {
let systemUnderTest = Delivery<Bool, Error>()
await #expect(throws: CancellationError.self, performing: {
try await valueOnceGetValueSuspends(on: systemUnderTest)
})
}

// MARK: Private

/// Sends `true` to the delivery once `getValue()` suspends, and returns the value that `getValue()` returns.
private func valueOnceGetValueSuspends(on delivery: isolated Delivery<Bool, Never>) async -> Bool {
// This task is isolated to the delivery, which this function occupies until `getValue()` suspends.
Task {
delivery.sendValue(true)
}
return await delivery.getValue()
}

/// Sends a `CancellationError` to the delivery once `getValue()` suspends, and returns the value that `getValue()` returns.
private func valueOnceGetValueSuspends(on delivery: isolated Delivery<Bool, Error>) async throws -> Bool {
// This task is isolated to the delivery, which this function occupies until `getValue()` suspends.
Task {
delivery.sendFailure(CancellationError())
}
return try await delivery.getValue()
}
}
44 changes: 44 additions & 0 deletions Tests/AsyncQueueTests/FIFOQueueTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,50 @@ struct FIFOQueueTests {
try? await task.value
}

@Test
func task_cancelledWhileWaitingForPriorTask_executesOperationCancelled() async {
let priorTaskAllowedToEnd = Semaphore()
Task(on: systemUnderTest) {
await priorTaskAllowedToEnd.wait()
}
let task = Task(on: systemUnderTest) {
Task.isCancelled
}

// The task's operation cannot begin until the prior task ends, so this cancels the task before its operation begins.
task.cancel()
await priorTaskAllowedToEnd.signal()

#expect(await task.value)
}

@Test
func task_canBeCancelledFromCancellationHandlerOfAnotherQueuedTask() async {
let otherQueue = FIFOQueue()
let taskStarted = Semaphore()
let innerTaskStarted = Semaphore()
let task = Task(on: systemUnderTest) {
let innerTask = Task(on: otherQueue) {
await innerTaskStarted.signal()
await suspendUntilCancelled()
return Task.isCancelled
}
return await withTaskCancellationHandler {
// Wait for the inner operation to start, so that cancelling the inner task runs its cancellation handler.
await innerTaskStarted.wait()
await taskStarted.signal()
return await innerTask.value
} onCancel: {
innerTask.cancel()
}
}
await taskStarted.wait()
task.cancel()
// The inner task returns only once it is cancelled, so if cancellation does not reach it, this test hangs rather
// than failing the expectation.
#expect(await task.value)
}

@Test
func task_canReturn() async {
let expectedValue = UUID()
Expand Down
34 changes: 34 additions & 0 deletions Tests/AsyncQueueTests/Utilities/TestHelpers.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// 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.

/// Suspends the calling task until it is cancelled.
///
/// Returns once the calling task is cancelled. If the task is never cancelled, this function suspends forever, so a
/// regression that keeps cancellation from reaching the task hangs the test until the CI job times out.
func suspendUntilCancelled() async {
// Nothing yields to or finishes this stream, and its continuation stays alive until this function returns, so only
// cancelling the calling task ends the wait for the stream's next element.
let (untilCancelled, untilCancelledContinuation) = AsyncStream<Void>.makeStream()
var untilCancelledIterator = untilCancelled.makeAsyncIterator()
await untilCancelledIterator.next()
withExtendedLifetime(untilCancelledContinuation) {}
}
Loading