diff --git a/Sources/AsyncQueue/Utilities/Delivery.swift b/Sources/AsyncQueue/Utilities/Delivery.swift index d9dda64..23e050e 100644 --- a/Sources/AsyncQueue/Utilities/Delivery.swift +++ b/Sources/AsyncQueue/Utilities/Delivery.swift @@ -32,10 +32,13 @@ actor Delivery { } 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 @@ -50,11 +53,13 @@ actor Delivery { 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 } @@ -120,8 +125,10 @@ private struct Locked: @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(_ 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 @@ -137,7 +144,6 @@ private struct Locked: @unchecked Sendable { } var unsafeValue: State + let lockQueue = DispatchQueue(label: "Locked.lockQueue", target: DispatchQueue.global()) } } - -private let lockQueue = DispatchQueue(label: "LockedValue.lockQueue", target: DispatchQueue.global()) diff --git a/Tests/AsyncQueueTests/ActorQueueTests.swift b/Tests/AsyncQueueTests/ActorQueueTests.swift index c2e56c5..378656b 100644 --- a/Tests/AsyncQueueTests/ActorQueueTests.swift +++ b/Tests/AsyncQueueTests/ActorQueueTests.swift @@ -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() diff --git a/Tests/AsyncQueueTests/DeliveryTests.swift b/Tests/AsyncQueueTests/DeliveryTests.swift index a124e6b..0a451d1 100644 --- a/Tests/AsyncQueueTests/DeliveryTests.swift +++ b/Tests/AsyncQueueTests/DeliveryTests.swift @@ -50,4 +50,38 @@ struct DeliveryTests { try await systemUnderTest.getValue() }) } + + @Test + func getValue_whenValueIsSentAfterGetValueSuspends() async { + let systemUnderTest = Delivery() + await #expect(valueOnceGetValueSuspends(on: systemUnderTest) == true) + } + + @Test + func getValueThrowing_whenFailureIsSentAfterGetValueSuspends() async throws { + let systemUnderTest = Delivery() + 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) 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) 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() + } } diff --git a/Tests/AsyncQueueTests/FIFOQueueTests.swift b/Tests/AsyncQueueTests/FIFOQueueTests.swift index 6224807..1baa78f 100644 --- a/Tests/AsyncQueueTests/FIFOQueueTests.swift +++ b/Tests/AsyncQueueTests/FIFOQueueTests.swift @@ -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() diff --git a/Tests/AsyncQueueTests/Utilities/TestHelpers.swift b/Tests/AsyncQueueTests/Utilities/TestHelpers.swift new file mode 100644 index 0000000..d9dc23d --- /dev/null +++ b/Tests/AsyncQueueTests/Utilities/TestHelpers.swift @@ -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.makeStream() + var untilCancelledIterator = untilCancelled.makeAsyncIterator() + await untilCancelledIterator.next() + withExtendedLifetime(untilCancelledContinuation) {} +}