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
116 changes: 57 additions & 59 deletions Sources/AsyncQueue/CancellableQueue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,16 +46,46 @@ public final class CancellableQueue<UnderlyingQueue: Sendable>: 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
}
}

// MARK: Fileprivate

fileprivate let underlyingQueue: UnderlyingQueue

fileprivate let taskIdentifierToCancelMap = Lock<[UUID: () -> Void]>(value: [:])
fileprivate let taskIdentifierToCancelMap = Lock<[UUID: (() -> Void)?]>(value: [:])
}

extension Task {
Expand Down Expand Up @@ -87,18 +117,14 @@ extension Task {
on actorQueue: CancellableQueue<ActorQueue<ActorType>>,
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
Expand Down Expand Up @@ -129,18 +155,14 @@ extension Task {
on actorQueue: CancellableQueue<ActorQueue<ActorType>>,
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
Expand Down Expand Up @@ -171,18 +193,14 @@ extension Task {
on actorQueue: CancellableQueue<ActorQueue<MainActor>>,
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
Expand Down Expand Up @@ -213,18 +231,14 @@ extension Task {
on actorQueue: CancellableQueue<ActorQueue<MainActor>>,
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
Expand Down Expand Up @@ -252,18 +266,14 @@ extension Task {
on fifoQueue: CancellableQueue<FIFOQueue>,
@_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
Expand Down Expand Up @@ -291,18 +301,14 @@ extension Task {
on fifoQueue: CancellableQueue<FIFOQueue>,
@_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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
}

Expand Down
30 changes: 30 additions & 0 deletions Tests/AsyncQueueTests/CancellableQueueTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,36 @@ struct CancellableQueueTests {
#expect(!task.isCancelled)
}

@Test
func cancelTasks_doesNotCancelTaskThatFinishedBeforeRegisteringCancellation() {
let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue())
let task = Task<Void, Never> {}

// 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<Void, Never> {}

// 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)
}
Comment thread
dfed marked this conversation as resolved.
Resolved

@Test
func cancelTasks_fifoQueue_cancelsCurrentlyExecutingTask() async {
let systemUnderTest = CancellableQueue(underlyingQueue: FIFOQueue())
Expand Down
Loading