diff --git a/Sources/AsyncQueue/CancellableQueue.swift b/Sources/AsyncQueue/CancellableQueue.swift index 05e9bca..423baa2 100644 --- a/Sources/AsyncQueue/CancellableQueue.swift +++ b/Sources/AsyncQueue/CancellableQueue.swift @@ -46,8 +46,38 @@ public final class CancellableQueue: Sendable { /// Cancels currently executing and pending tasks. Does not affect tasks enqueued after this method is called. public func cancelTasks() { taskIdentifierToCancelMap.withLock { - $0.values.forEach { $0() } - $0.removeAll() + $0.values.forEach { $0?() } + // Keep reservations so that tasks that have not yet registered remain cancellable. + $0 = $0.filter { $0.value == nil } + } + } + + // MARK: Internal + + /// Reserves an identifier for a task that is about to be created. + /// Reserving before the task starts ensures the task's removal of the identifier can never be processed before the reservation. + func reserveTaskIdentifier() -> UUID { + let identifier = UUID() + taskIdentifierToCancelMap.writeAsync { + $0.updateValue(nil, forKey: identifier) + } + return identifier + } + + /// Registers the `cancel` closure for a task whose identifier was previously reserved. + func registerCancellation(forTaskWithIdentifier identifier: UUID, _ cancel: @escaping @Sendable () -> Void) { + taskIdentifierToCancelMap.writeAsync { + // Skip registration if the identifier was already removed because the task already finished. + if $0.keys.contains(identifier) { + $0[identifier] = cancel + } + } + } + + /// Removes the identifier of a task that has finished executing. + func taskDidFinish(withIdentifier identifier: UUID) { + taskIdentifierToCancelMap.writeAsync { + $0[identifier] = nil } } @@ -55,7 +85,7 @@ public final class CancellableQueue: Sendable { fileprivate let underlyingQueue: UnderlyingQueue - fileprivate let taskIdentifierToCancelMap = Lock<[UUID: () -> Void]>(value: [:]) + fileprivate let taskIdentifierToCancelMap = Lock<[UUID: (() -> Void)?]>(value: [:]) } extension Task { @@ -87,18 +117,14 @@ extension Task { on actorQueue: CancellableQueue>, operation: @Sendable @escaping (isolated ActorType) async -> Success, ) where Failure == Never { - let identifier = UUID() + let identifier = actorQueue.reserveTaskIdentifier() self.init(name: name, priority: priority, on: actorQueue.underlyingQueue, operation: { defer { - actorQueue.taskIdentifierToCancelMap.writeAsync { - $0[identifier] = nil - } + actorQueue.taskDidFinish(withIdentifier: identifier) } return await operation($0) }) - actorQueue.taskIdentifierToCancelMap.writeAsync { [cancel] in - $0[identifier] = cancel - } + actorQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) } /// Runs the given throwing operation asynchronously @@ -129,18 +155,14 @@ extension Task { on actorQueue: CancellableQueue>, operation: @escaping @Sendable (isolated ActorType) async throws -> Success, ) where Failure == any Error { - let identifier = UUID() + let identifier = actorQueue.reserveTaskIdentifier() self.init(name: name, priority: priority, on: actorQueue.underlyingQueue, operation: { defer { - actorQueue.taskIdentifierToCancelMap.writeAsync { - $0[identifier] = nil - } + actorQueue.taskDidFinish(withIdentifier: identifier) } return try await operation($0) }) - actorQueue.taskIdentifierToCancelMap.writeAsync { [cancel] in - $0[identifier] = cancel - } + actorQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) } /// Runs the given nonthrowing operation asynchronously @@ -171,18 +193,14 @@ extension Task { on actorQueue: CancellableQueue>, operation: @MainActor @escaping () async -> Success, ) where Failure == Never { - let identifier = UUID() + let identifier = actorQueue.reserveTaskIdentifier() self.init(name: name, priority: priority, on: actorQueue.underlyingQueue, operation: { defer { - actorQueue.taskIdentifierToCancelMap.writeAsync { - $0[identifier] = nil - } + actorQueue.taskDidFinish(withIdentifier: identifier) } return await operation() }) - actorQueue.taskIdentifierToCancelMap.writeAsync { [cancel] in - $0[identifier] = cancel - } + actorQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) } /// Runs the given throwing operation asynchronously @@ -213,18 +231,14 @@ extension Task { on actorQueue: CancellableQueue>, operation: @escaping @MainActor () async throws -> Success, ) where Failure == any Error { - let identifier = UUID() + let identifier = actorQueue.reserveTaskIdentifier() self.init(name: name, priority: priority, on: actorQueue.underlyingQueue, operation: { defer { - actorQueue.taskIdentifierToCancelMap.writeAsync { - $0[identifier] = nil - } + actorQueue.taskDidFinish(withIdentifier: identifier) } return try await operation() }) - actorQueue.taskIdentifierToCancelMap.writeAsync { [cancel] in - $0[identifier] = cancel - } + actorQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) } /// Runs the given nonthrowing operation asynchronously @@ -252,18 +266,14 @@ extension Task { on fifoQueue: CancellableQueue, @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> Success, ) where Failure == Never { - let identifier = UUID() + let identifier = fifoQueue.reserveTaskIdentifier() self.init(name: name, on: fifoQueue.underlyingQueue, operation: { defer { - fifoQueue.taskIdentifierToCancelMap.writeAsync { - $0[identifier] = nil - } + fifoQueue.taskDidFinish(withIdentifier: identifier) } return await operation() }) - fifoQueue.taskIdentifierToCancelMap.writeAsync { [cancel] in - $0[identifier] = cancel - } + fifoQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) } /// Runs the given throwing operation asynchronously @@ -291,18 +301,14 @@ extension Task { on fifoQueue: CancellableQueue, @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async throws -> Success, ) where Failure == any Error { - let identifier = UUID() + let identifier = fifoQueue.reserveTaskIdentifier() self.init(name: name, on: fifoQueue.underlyingQueue, operation: { defer { - fifoQueue.taskIdentifierToCancelMap.writeAsync { - $0[identifier] = nil - } + fifoQueue.taskDidFinish(withIdentifier: identifier) } return try await operation() }) - fifoQueue.taskIdentifierToCancelMap.writeAsync { [cancel] in - $0[identifier] = cancel - } + fifoQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) } /// Runs the given nonthrowing operation asynchronously @@ -335,18 +341,14 @@ extension Task { isolatedTo isolatedActor: ActorType, operation: @Sendable @escaping (isolated ActorType) async -> Success, ) where Failure == Never { - let identifier = UUID() + let identifier = fifoQueue.reserveTaskIdentifier() self.init(name: name, priority: priority, on: fifoQueue.underlyingQueue, isolatedTo: isolatedActor, operation: { defer { - fifoQueue.taskIdentifierToCancelMap.writeAsync { - $0[identifier] = nil - } + fifoQueue.taskDidFinish(withIdentifier: identifier) } return await operation($0) }) - fifoQueue.taskIdentifierToCancelMap.writeAsync { [cancel] in - $0[identifier] = cancel - } + fifoQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) } /// Runs the given throwing operation asynchronously @@ -379,18 +381,14 @@ extension Task { isolatedTo isolatedActor: ActorType, operation: @Sendable @escaping (isolated ActorType) async throws -> Success, ) where Failure == any Error { - let identifier = UUID() + let identifier = fifoQueue.reserveTaskIdentifier() self.init(name: name, priority: priority, on: fifoQueue.underlyingQueue, isolatedTo: isolatedActor, operation: { defer { - fifoQueue.taskIdentifierToCancelMap.writeAsync { - $0[identifier] = nil - } + fifoQueue.taskDidFinish(withIdentifier: identifier) } return try await operation($0) }) - fifoQueue.taskIdentifierToCancelMap.writeAsync { [cancel] in - $0[identifier] = cancel - } + fifoQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) } } diff --git a/Tests/AsyncQueueTests/CancellableQueueTests.swift b/Tests/AsyncQueueTests/CancellableQueueTests.swift index c3eec27..afd1ce0 100644 --- a/Tests/AsyncQueueTests/CancellableQueueTests.swift +++ b/Tests/AsyncQueueTests/CancellableQueueTests.swift @@ -45,6 +45,36 @@ struct CancellableQueueTests { #expect(!task.isCancelled) } + @Test + func cancelTasks_doesNotCancelTaskThatFinishedBeforeRegisteringCancellation() { + let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue()) + let task = Task {} + + // Finish the task before registering its cancellation. + let identifier = systemUnderTest.reserveTaskIdentifier() + systemUnderTest.taskDidFinish(withIdentifier: identifier) + systemUnderTest.registerCancellation(forTaskWithIdentifier: identifier, task.cancel) + + systemUnderTest.cancelTasks() + + #expect(!task.isCancelled) + } + + @Test + func cancelTasks_cancelsTaskThatRegisteredCancellationAfterEarlierCancelTasks() { + let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue()) + let task = Task {} + + // Cancel tasks after the task reserved its identifier but before it registered its cancellation. + let identifier = systemUnderTest.reserveTaskIdentifier() + systemUnderTest.cancelTasks() + systemUnderTest.registerCancellation(forTaskWithIdentifier: identifier, task.cancel) + + systemUnderTest.cancelTasks() + + #expect(task.isCancelled) + } + @Test func cancelTasks_fifoQueue_cancelsCurrentlyExecutingTask() async { let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue())