diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 774b41c..06a561a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,6 +62,76 @@ jobs: run: sudo xcode-select --switch /Applications/Xcode_27.2.app/Contents/Developer - name: Build and Test Framework run: xcrun swift test -c release -Xswiftc -enable-testing + tsan: + name: "Thread Sanitizer on macOS" + runs-on: xcode-27 + # A test that deadlocks keeps the test run from ending, so stop the + # job after 30 minutes rather than at GitHub's six-hour default. + timeout-minutes: 30 + permissions: + contents: read + steps: + - name: Checkout Repo + uses: actions/checkout@v7 + - name: Select Xcode Version + run: sudo xcode-select --switch /Applications/Xcode_27.2.app/Contents/Developer + - name: Build With Thread Sanitizer + run: xcrun swift build --build-tests --sanitize=thread + - name: Test With Thread Sanitizer + run: xcrun swift test --skip-build --sanitize=thread + ios18-export-spike: + name: "Spike: export the iOS 18 runtime with Xcode 26" + runs-on: macos-15 + timeout-minutes: 50 + permissions: + contents: read + steps: + - name: Export the iOS 18.5 Simulator Runtime + run: | + set -x + sudo xcode-select --switch /Applications/Xcode_26.1.1.app/Contents/Developer + mkdir -p runtime + SECONDS=0 + # The image has iOS 18.5 installed as a disk image. Copy that image + # directly; `xcodebuild -downloadPlatform -exportPath` exports it too, + # but fails at random with "Unable to connect to simulator." + xcrun simctl runtime list -j > runtimes.json + image=$(python3 -c 'import json,sys; d=json.load(open("runtimes.json")); print(next((v["path"] for v in d.values() if v.get("build") == "22F77" and v.get("path")), ""))') + if [ -n "$image" ]; then + cp "$image" runtime/iphonesimulator_18.5_22F77.dmg + else + cat runtimes.json + sudo xcodebuild -runFirstLaunch + sudo xcodebuild -downloadPlatform iOS -buildVersion 22F77 -exportPath runtime || echo "xcodebuild exited with $?" + sudo chown -R "$(whoami)" runtime + fi + echo "Export took ${SECONDS}s" + ls -la runtime + test -f runtime/iphonesimulator_18.5_22F77.dmg + - name: Upload the Runtime + uses: actions/upload-artifact@v4 + with: + name: ios-18-5-runtime + path: runtime + compression-level: 0 + retention-days: 1 + ios18-spike: + name: "Spike: test on the iOS 18 runtime with Xcode 27" + needs: ios18-export-spike + runs-on: xcode-27 + timeout-minutes: 50 + permissions: + contents: read + steps: + - name: Checkout Repo + uses: actions/checkout@v7 + - name: Download the Runtime + uses: actions/download-artifact@v4 + with: + name: ios-18-5-runtime + path: runtime + - name: Install the Runtime and Test on It + run: Scripts/spike-old-simulator.sh linux: name: "Build and Test on Linux" runs-on: ubuntu-24.04 diff --git a/README.md b/README.md index 63832cd..8befad4 100644 --- a/README.md +++ b/README.md @@ -265,6 +265,43 @@ Task(on: cancellableQueue) { } ``` +## Checking whether a queue is idle + +A `FIFOQueue` and an `ActorQueue` each have an `isIdle` property: + +- A `FIFOQueue` is idle when every task you enqueued on it has finished. A task that is suspended at an `await` hasn't finished. Neither has a cancelled task: it keeps its place, and its operation still runs. +- An `ActorQueue` is idle when every task you enqueued on it has started running on the actor. The operations of its tasks might not have finished. + +The value can change as soon as you read it: a task you enqueue afterward makes the queue busy again. + +For example, here's how an actor that keeps one `FIFOQueue` per document might remove the queues it no longer needs: + +```swift +actor DocumentStore { + func save(_ contents: String, as name: String) -> Task { + let queue = queues[name] ?? FIFOQueue() + queues[name] = queue + return Task(on: queue) { + await self.write(contents, as: name) + } + } + + func removeIdleQueues() { + queues = queues.filter { !$0.value.isIdle } + } + + private func write(_ contents: String, as name: String) async { + // Write implementation… + } + + private var queues = [String: FIFOQueue]() +} +``` + +In the code above, the actor enqueues every task and reads `isIdle`, and it doesn't suspend between reading `isIdle` and removing the queue. So no task can be enqueued in between. A document you save after its queue is removed gets a new queue, and its task runs after the tasks of the removed queue, which have all finished. + +`CancellableQueue` has no `isIdle` property. To check one, keep a reference to the queue it wraps, and read that queue's `isIdle`. + ## Task-local values, priority, and cancellation `Task(on:)` creates a new [unstructured task](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/#Unstructured-Concurrency), as `Task.init` does, and your operation runs in that task. So the task behaves like a task you create with `Task.init`. @@ -276,7 +313,7 @@ Your operation sees the [task-local values](https://developer.apple.com/document ### Priority - A task runs at the priority you pass to `Task(on:)`. If you pass `nil`, it runs at the priority of the code that enqueues it, as with `Task.init`. -- `FIFOQueue(priority:)` gives each of the queue's tasks at least that priority. A task that would run at a lower priority runs at the queue's priority instead. +- `FIFOQueue(priority:)` and `ActorQueue(priority:)` give each of the queue's tasks at least that priority. A task that would run at a lower priority runs at the queue's priority instead. `MainActor.queue` has no priority of its own. - When a higher-priority task awaits a task's value, Swift raises, or *escalates*, that task's priority, as it does for any task. - On Linux, and on macOS 26, iOS 26, tvOS 26, watchOS 26, and visionOS 26 or later, a task that waits in a queue also raises the priority of the tasks ahead of it to its own priority. That way, the tasks ahead of a high-priority task don't run at a lower priority while it waits. On earlier releases, the tasks ahead keep their own priority. - A task keeps a raised priority until it finishes. @@ -295,9 +332,10 @@ Cancellation is [cooperative](https://docs.swift.org/swift-book/documentation/th - **Swift and platform versions.** Version 2.0 requires Swift 6.4 and newer platform versions; see [Installation](#installation). Update your toolchain and deployment targets. - **Priority.** An operation you enqueue without a priority now runs at the priority of the code that enqueues it. In 1.x, a `FIFOQueue` created without a priority ran it at `.medium`, and an `ActorQueue` ran it at the priority of the code that created the queue. - On a `FIFOQueue`, a task enqueued from low-priority code now runs at low priority, and the tasks behind it wait for it. To keep the 1.x priority, create the queue with `FIFOQueue(priority: .medium)`. - - On an `ActorQueue`, pass `priority:` to `Task(on:)` when you enqueue important work from low-priority code. + - On an `ActorQueue`, a task enqueued from low-priority code now runs at low priority. To keep its tasks at the 1.x priority or higher, create the queue with the priority of the code that creates it, such as `ActorQueue(priority: .medium)`. + - On `MainActor.queue`, pass `priority:` to `Task(on:)` when you enqueue important work from low-priority code. - **Task-local values.** An operation now sees the task-local values of the code that enqueues it. In 1.x, an operation on an `ActorQueue` saw the values of the code that created the queue, and an operation on a `FIFOQueue` saw none. You need to change your code only if an operation relied on the 1.x values. -- **Queue names.** `FIFOQueue(name:priority:)` and `ActorQueue(name:)` are removed, because operations now run in the task that `Task(on:)` returns. Use `FIFOQueue(priority:)` and `ActorQueue()`, and pass `name:` to `Task(on:)` to name each task instead. +- **Queue names.** `FIFOQueue(name:priority:)` and `ActorQueue(name:)` are removed, because operations now run in the task that `Task(on:)` returns. Use `FIFOQueue(priority:)` and `ActorQueue(priority:)`, and pass `name:` to `Task(on:)` to name each task instead. ## Installation diff --git a/Scripts/spike-old-simulator.sh b/Scripts/spike-old-simulator.sh new file mode 100755 index 0000000..20f7942 --- /dev/null +++ b/Scripts/spike-old-simulator.sh @@ -0,0 +1,68 @@ +#!/bin/bash +# Spike, not for merging: can Xcode 27.2 run the tests on an iOS 18.5 +# simulator runtime that Xcode 26.1.1 exported on another runner? +set -x +export DEVELOPER_DIR=/Applications/Xcode_27.2.app/Contents/Developer +ls -la runtime + +echo "::group::Free disk space" +df -h / +xcrun simctl runtime list +SECONDS=0 +# Keep only the 27.2 runtime of each platform: the jobs test on those. +for id in $(xcrun simctl runtime list | grep -v ' 27\.2 (' | grep -v '24B91016s' | grep -oE '[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}'); do + sudo xcrun simctl runtime delete "$id" || true +done +# The iPhone-specific 27.2 variant isn't used either. +for id in $(xcrun simctl runtime list | grep '24B91016s' | grep -oE '[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}'); do + sudo xcrun simctl runtime delete "$id" || true +done +for attempt in $(seq 1 60); do + xcrun simctl runtime list | grep -q 'Deleting' || break + sleep 5 +done +echo "Deleting runtimes took ${SECONDS}s" +xcrun simctl runtime list +df -h / +echo "::endgroup::" + +echo "::group::Add the runtime" +find runtime -maxdepth 2 -print +sudo xcodebuild -runFirstLaunch +SECONDS=0 +for image in runtime/*; do + sudo xcodebuild -importPlatform "$image" + echo "xcodebuild -importPlatform $image exit $? after ${SECONDS}s" + if ! xcrun simctl list runtimes | grep -q 'iOS 18\.'; then + SECONDS=0 + sudo xcrun simctl runtime add "$image" + echo "simctl runtime add $image exit $? after ${SECONDS}s" + fi +done +xcrun simctl runtime list +xcrun simctl list runtimes +echo "::endgroup::" + +echo "::group::Prebuild the dyld shared cache" +SECONDS=0 +sudo xcrun simctl runtime dyld_shared_cache update --all +echo "dyld_shared_cache update exit $? after ${SECONDS}s" +echo "::endgroup::" + +RUNTIME=$(xcrun simctl list runtimes | grep 'iOS 18\.' | tail -1 | grep -o 'com\.apple\.CoreSimulator\.SimRuntime\.iOS-18-[0-9-]*') +if [ -z "$RUNTIME" ]; then + echo "::error::Xcode 27.2 does not list an iOS 18 runtime after adding the image." + exit 1 +fi +UDID=$(xcrun simctl create "iPad iOS 18" "com.apple.CoreSimulator.SimDeviceType.iPad-10th-generation" "$RUNTIME") +echo "Created $UDID on $RUNTIME" + +echo "::group::Test with Xcode 27.2 on the iOS 18 simulator" +SECONDS=0 +xcodebuild -scheme swift-async-queue -sdk iphonesimulator \ + -derivedDataPath .build/derivedData/iOS18 -PBXBuildsContinueAfterErrors=0 \ + OTHER_SWIFT_FLAGS=-warnings-as-errors -destination "id=$UDID" build test +STATUS=$? +echo "Test exit $STATUS after ${SECONDS}s" +echo "::endgroup::" +exit $STATUS diff --git a/Sources/AsyncQueue/ActorQueue.swift b/Sources/AsyncQueue/ActorQueue.swift index 97a7ceb..0ef21bf 100644 --- a/Sources/AsyncQueue/ActorQueue.swift +++ b/Sources/AsyncQueue/ActorQueue.swift @@ -55,7 +55,13 @@ public final class ActorQueue: @unchecked Sendable { // MARK: Initialization /// Creates an actor queue. - public init() {} + /// - Parameter priority: The lowest priority at which the queue's tasks run. + /// A task that would run at a lower priority runs at this priority instead. + /// Pass `nil` to run each task at the priority you pass to `Task(on:)`, + /// or, if you pass `nil` there too, at the priority of the code that enqueues it. + public init(priority: TaskPriority? = nil) { + minimumPriority = MinimumPriority(priority) + } // MARK: Public @@ -70,11 +76,29 @@ public final class ActorQueue: @unchecked Sendable { weakExecutionContext = actor } + /// Whether every task you enqueued on this queue has started running on the actor. + /// + /// A task counts from the moment you enqueue it until it starts running on the actor. + /// So the queue can be idle while the operations of its tasks haven't finished. + /// A task runs alongside the code that enqueues it, so the task might start running on the actor before that code reads this property. + /// If that code is running on the actor, though, the task can't start running there until the code suspends or returns. + /// + /// The value can change as soon as you read it: a task you enqueue afterward makes the queue busy again. + /// If one actor enqueues every task on the queue, that actor can read this property and then remove an idle queue + /// without suspending between the read and the removal. + /// No task can be enqueued in between, so every task enqueued on the removed queue has started running on the queue's actor. + public var isIdle: Bool { + turns.isIdle + } + // MARK: Internal /// Hands out turns to begin executing on the adopted actor, in the order in which tasks are enqueued. let turns = Turns() + /// The priority that the queue gives each of its tasks at least. + let minimumPriority: MinimumPriority + // MARK: Fileprivate /// The actor on whose isolated context our tasks run, force-unwrapped. @@ -125,6 +149,7 @@ extension Task { /// - priority: The priority of the task. /// Pass `nil` to inherit the priority of the code that enqueues the task, /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -136,7 +161,7 @@ extension Task { ) where Failure == Never { let executionContext = actorQueue.executionContext let turn = actorQueue.turns.reserve() - self.init(name: name, priority: priority) { + self.init(name: name, priority: actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { await turn.begin() return await execute(operation, on: executionContext, endingTurn: turn) } @@ -170,6 +195,7 @@ extension Task { /// - priority: The priority of the task. /// Pass `nil` to inherit the priority of the code that enqueues the task, /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -181,7 +207,7 @@ extension Task { ) where Failure == any Error { let executionContext = actorQueue.executionContext let turn = actorQueue.turns.reserve() - self.init(name: name, priority: priority) { + self.init(name: name, priority: actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { await turn.begin() return try await execute(operation, on: executionContext, endingTurn: turn) } @@ -215,6 +241,7 @@ extension Task { /// - priority: The priority of the task. /// Pass `nil` to inherit the priority of the code that enqueues the task, /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -225,7 +252,7 @@ extension Task { operation: @MainActor @escaping () async -> Success, ) where Failure == Never { let turn = actorQueue.turns.reserve() - self.init(name: name, priority: priority) { + self.init(name: name, priority: actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { await turn.begin() return await executeOnMainActor(operation, endingTurn: turn) } @@ -259,6 +286,7 @@ extension Task { /// - priority: The priority of the task. /// Pass `nil` to inherit the priority of the code that enqueues the task, /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -269,7 +297,7 @@ extension Task { operation: @escaping @MainActor () async throws -> Success, ) where Failure == any Error { let turn = actorQueue.turns.reserve() - self.init(name: name, priority: priority) { + self.init(name: name, priority: actorQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { await turn.begin() return try await executeOnMainActor(operation, endingTurn: turn) } @@ -307,6 +335,10 @@ private func executeOnMainActor( extension MainActor { /// A global instance of an `ActorQueue`. + /// + /// This queue has no priority of its own: each task runs at the priority you pass to `Task(on:)`, + /// or, if you pass `nil`, at the priority of the code that enqueues it. + /// Pass a `priority` to `Task(on:)` when you enqueue important work from low-priority code. public static var queue: ActorQueue { mainActorQueue } diff --git a/Sources/AsyncQueue/CancellableQueue.swift b/Sources/AsyncQueue/CancellableQueue.swift index 7b9d0a2..b34f8d4 100644 --- a/Sources/AsyncQueue/CancellableQueue.swift +++ b/Sources/AsyncQueue/CancellableQueue.swift @@ -172,6 +172,7 @@ extension Task { /// - priority: The priority of the task. /// Pass `nil` to inherit the priority of the code that enqueues the task, /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -219,6 +220,7 @@ extension Task { /// - priority: The priority of the task. /// Pass `nil` to inherit the priority of the code that enqueues the task, /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -266,6 +268,7 @@ extension Task { /// - priority: The priority of the task. /// Pass `nil` to inherit the priority of the code that enqueues the task, /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult @@ -313,6 +316,7 @@ extension Task { /// - priority: The priority of the task. /// Pass `nil` to inherit the priority of the code that enqueues the task, /// as a task created with `Task.init(name:priority:operation:)` does. + /// If the queue was created with a higher priority, the task runs at the queue's priority instead. /// - actorQueue: The queue on which to enqueue the task. /// - operation: The operation to perform. @discardableResult diff --git a/Sources/AsyncQueue/FIFOQueue.swift b/Sources/AsyncQueue/FIFOQueue.swift index 8de755b..96acd4c 100644 --- a/Sources/AsyncQueue/FIFOQueue.swift +++ b/Sources/AsyncQueue/FIFOQueue.swift @@ -35,45 +35,60 @@ public final class FIFOQueue: Sendable { /// Pass `nil` to run each task at the priority you pass to `Task(on:)`, /// or, if you pass `nil` there too, at the priority of the code that enqueues it. public init(priority: TaskPriority? = nil) { - self.priority = priority + minimumPriority = MinimumPriority(priority) } - // MARK: Internal - - /// Hands out turns to execute, in the order in which tasks are enqueued. - let turns = Turns() - - // MARK: Fileprivate + // MARK: Public - /// Returns the priority with which to create a task that was enqueued with the given priority. - /// - Parameter taskPriority: The priority with which the task was enqueued. `nil` means the priority of the enqueuing context. - fileprivate func priority(forTaskEnqueuedWith taskPriority: TaskPriority?) -> TaskPriority? { - if let priority, Self.priorityOfNewTask(enqueuedWith: taskPriority) < priority { - priority - } else { - // Keep the enqueued priority when it suffices, so that `Task` determines the task's priority itself. - taskPriority - } + /// Whether every task you enqueued on this queue has finished. + /// + /// A task counts from the moment you enqueue it until its operation returns or throws. + /// A task that is suspended at an `await` hasn't finished, + /// so an operation that reads this property on its own queue always reads `false`. + /// A cancelled task hasn't finished either: it keeps its place in the queue, and its operation still runs. + /// A task runs alongside the code that enqueues it, so the task might finish before that code reads this property. + /// If the task's operation needs an actor that the code is running on, though, + /// the task can't finish until the code suspends or returns. + /// + /// The value can change as soon as you read it: a task you enqueue afterward makes the queue busy again. + /// If one actor enqueues every task on the queue, that actor can read this property and then safely remove an idle queue, + /// without suspending between the read and the removal. + /// No task can be enqueued in between, and a task that the actor enqueues afterward on a new queue + /// runs after every task on the removed queue, because they have all finished. + /// For example, an actor that keeps one queue per document can remove the queues of documents whose work has finished: + /// + /// ```swift + /// actor DocumentStore { + /// func save(_ contents: String, as name: String) -> Task { + /// let queue = queues[name] ?? FIFOQueue() + /// queues[name] = queue + /// return Task(on: queue) { + /// await self.write(contents, as: name) + /// } + /// } + /// + /// func removeIdleQueues() { + /// queues = queues.filter { !$0.value.isIdle } + /// } + /// + /// private func write(_ contents: String, as name: String) async { + /// // Write implementation… + /// } + /// + /// private var queues = [String: FIFOQueue]() + /// } + /// ``` + public var isIdle: Bool { + turns.isIdle } - /// Returns the priority that `Task.init(priority:)` gives a task created in the current context with the given priority. - private static func priorityOfNewTask(enqueuedWith taskPriority: TaskPriority?) -> TaskPriority { - // `Task` treats a priority with a raw value of zero as no priority. - if let taskPriority, taskPriority.rawValue != 0 { - return taskPriority - } else { - // Within a task, a new task inherits the task's base priority, not its escalated priority. - // Outside of a task, a new task takes the current thread's priority, or `.medium` if the thread has none. - let inheritedPriority = Task.basePriority ?? Task.currentPriority - guard inheritedPriority.rawValue != 0 else { return .medium } - // `Task` lowers an inherited user-interactive priority to user-initiated, which is `.high`. - return min(inheritedPriority, .high) - } - } + // MARK: Internal - // MARK: Private + /// Hands out turns to execute, in the order in which tasks are enqueued. + let turns = Turns() - private let priority: TaskPriority? + /// The priority that the queue gives each of its tasks at least. + let minimumPriority: MinimumPriority } extension Task { @@ -116,7 +131,7 @@ extension Task { @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async -> Success, ) where Failure == Never { let turn = fifoQueue.turns.reserve() - self.init(name: name, priority: fifoQueue.priority(forTaskEnqueuedWith: priority)) { + self.init(name: name, priority: fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { await turn.begin() defer { turn.end() } return await operation() @@ -163,7 +178,7 @@ extension Task { @_inheritActorContext @_implicitSelfCapture operation: sending @escaping @isolated(any) () async throws -> Success, ) where Failure == any Error { let turn = fifoQueue.turns.reserve() - self.init(name: name, priority: fifoQueue.priority(forTaskEnqueuedWith: priority)) { + self.init(name: name, priority: fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { await turn.begin() defer { turn.end() } return try await operation() @@ -212,7 +227,7 @@ extension Task { operation: @Sendable @escaping (isolated ActorType) async -> Success, ) where Failure == Never { let turn = fifoQueue.turns.reserve() - self.init(name: name, priority: fifoQueue.priority(forTaskEnqueuedWith: priority)) { + self.init(name: name, priority: fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { await turn.begin() defer { turn.end() } return await operation(isolatedActor) @@ -261,7 +276,7 @@ extension Task { operation: @Sendable @escaping (isolated ActorType) async throws -> Success, ) where Failure == any Error { let turn = fifoQueue.turns.reserve() - self.init(name: name, priority: fifoQueue.priority(forTaskEnqueuedWith: priority)) { + self.init(name: name, priority: fifoQueue.minimumPriority.priority(forTaskEnqueuedWith: priority)) { await turn.begin() defer { turn.end() } return try await operation(isolatedActor) diff --git a/Sources/AsyncQueue/Utilities/MinimumPriority.swift b/Sources/AsyncQueue/Utilities/MinimumPriority.swift new file mode 100644 index 0000000..f192ff3 --- /dev/null +++ b/Sources/AsyncQueue/Utilities/MinimumPriority.swift @@ -0,0 +1,64 @@ +// 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. + +/// The priority that a queue gives each of its tasks at least. +struct MinimumPriority: Sendable { + // MARK: Initialization + + /// - Parameter priority: The lowest priority at which the queue's tasks run. + /// Pass `nil` to run each task at the priority with which it was enqueued. + init(_ priority: TaskPriority?) { + self.priority = priority + } + + // MARK: Internal + + /// Returns the priority with which to create a task that was enqueued with the given priority. + /// - Parameter taskPriority: The priority with which the task was enqueued. `nil` means the priority of the enqueuing context. + func priority(forTaskEnqueuedWith taskPriority: TaskPriority?) -> TaskPriority? { + if let priority, Self.priorityOfNewTask(enqueuedWith: taskPriority) < priority { + priority + } else { + // Keep the enqueued priority when it suffices, so that `Task` determines the task's priority itself. + taskPriority + } + } + + // MARK: Private + + private let priority: TaskPriority? + + /// Returns the priority that `Task.init(priority:)` gives a task created in the current context with the given priority. + private static func priorityOfNewTask(enqueuedWith taskPriority: TaskPriority?) -> TaskPriority { + // `Task` treats a priority with a raw value of zero as no priority. + if let taskPriority, taskPriority.rawValue != 0 { + return taskPriority + } else { + // Within a task, a new task inherits the task's base priority, not its escalated priority. + // Outside of a task, a new task takes the current thread's priority, or `.medium` if the thread has none. + let inheritedPriority = Task.basePriority ?? Task.currentPriority + guard inheritedPriority.rawValue != 0 else { return .medium } + // `Task` lowers an inherited user-interactive priority to user-initiated, which is `.high`. + return min(inheritedPriority, .high) + } + } +} diff --git a/Sources/AsyncQueue/Utilities/Turns.swift b/Sources/AsyncQueue/Utilities/Turns.swift index 6f47a1e..01ab936 100644 --- a/Sources/AsyncQueue/Utilities/Turns.swift +++ b/Sources/AsyncQueue/Utilities/Turns.swift @@ -59,6 +59,13 @@ final class Turns: Sendable { return Turn(turns: self, previousTicket: previousTicket, ticket: ticket) } + /// Whether every turn reserved so far has ended. + /// + /// A turn ends only after every turn reserved before it has ended, so every turn has ended once the most recently reserved turn has. + var isIdle: Bool { + state.withLock { $0.lastTicket?.hasEnded ?? true } + } + /// The number of tasks waiting for their turn whose priority is recorded. Used by tests. var waitingTaskCount: Int { state.withLock { $0.waitingTaskCounts.values.reduce(0, +) } diff --git a/Tests/AsyncQueueTests/ActorQueueTests.swift b/Tests/AsyncQueueTests/ActorQueueTests.swift index fdfeadd..fc49ca6 100644 --- a/Tests/AsyncQueueTests/ActorQueueTests.swift +++ b/Tests/AsyncQueueTests/ActorQueueTests.swift @@ -514,6 +514,108 @@ struct ActorQueueTests { #expect(executor.wasEachJobEnqueuedOnMainQueue == [true, true]) } + @Test + func isIdle_onNewQueue_isTrue() { + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_afterTaskIsEnqueued_isFalseUntilTaskIsIsolatedToActor() async { + let actor = ManuallyExecutedActor() + var enqueuedJobs = actor.executor.enqueuedJobs.makeAsyncIterator() + let task = Task(on: actor.queue) { actor in + actor.queue.isIdle + } + // `Task(on:)` takes the task's place on the queue before it returns, and the task cannot be isolated to the actor + // until the test runs the actor's executor. + let isIdleAfterTaskWasEnqueued = actor.queue.isIdle + // Wait for the task to hop to the actor. It has begun executing, but it is not isolated to the actor yet. + _ = await enqueuedJobs.next() + let isIdleAfterTaskHoppedToActor = actor.queue.isIdle + actor.executor.runUntilIdle() + let isIdleWhileOperationExecuted = await task.value + #expect(!isIdleAfterTaskWasEnqueued) + #expect(!isIdleAfterTaskHoppedToActor) + #expect(isIdleWhileOperationExecuted) + } + + @Test + func isIdle_whileLastOperationIsSuspended_isTrue() async { + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest) { _ in + await operationStarted.signal() + await operationAllowedToReturn.wait() + } + await operationStarted.wait() + // The task gave up its place on the queue once it was isolated to the actor, before its operation began. + let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle + await operationAllowedToReturn.signal() + await task.value + #expect(isIdleWhileOperationWasSuspended) + } + + @Test + func isIdle_withSeveralTasks_isFalseUntilLastTaskIsIsolatedToActor() async { + let actor = ManuallyExecutedActor() + var enqueuedJobs = actor.executor.enqueuedJobs.makeAsyncIterator() + // Each operation reads the property before it can suspend. The actor executes one job at a time, so the last task + // cannot be isolated to the actor while the first task's operation executes. + let firstTask = Task(on: actor.queue) { actor in + actor.queue.isIdle + } + let lastTask = Task(on: actor.queue) { actor in + actor.queue.isIdle + } + // Wait for the first task to hop to the actor, then run it. Its operation cannot execute before both tasks are enqueued. + _ = await enqueuedJobs.next() + actor.executor.runUntilIdle() + // Wait for the last task to hop to the actor, then run it if the previous call did not already. + _ = await enqueuedJobs.next() + actor.executor.runUntilIdle() + let isIdleWhileFirstOperationExecuted = await firstTask.value + let isIdleWhileLastOperationExecuted = await lastTask.value + #expect(!isIdleWhileFirstOperationExecuted) + #expect(isIdleWhileLastOperationExecuted) + } + + @Test + func isIdle_onMainActorQueue_afterTaskIsEnqueuedWhileCallerHoldsMainActor_isFalseUntilOperationRuns() async { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + // While this closure holds the main actor, the task cannot be isolated to it. The test cannot wait here for the task + // to hop to the main actor, so `mainTask_holdsTurnUntilItIsIsolatedToMainActor` covers when the task's turn ends. + let (task, isIdleAfterTaskWasEnqueued) = await MainActor.run { + let task = Task(on: mainActorQueue) { + mainActorQueue.isIdle + } + return (task, mainActorQueue.isIdle) + } + let isIdleWhileOperationExecuted = await task.value + #expect(!isIdleAfterTaskWasEnqueued) + #expect(isIdleWhileOperationExecuted) + } + + @Test + func isIdle_onMainActorQueue_whileLastOperationIsSuspended_isTrue() async { + // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. + let mainActorQueue = ActorQueue() + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: mainActorQueue) { + await operationStarted.signal() + await operationAllowedToReturn.wait() + } + await operationStarted.wait() + // The task gave up its place on the queue once it was isolated to the main actor, before its operation began. + let isIdleWhileOperationWasSuspended = mainActorQueue.isIdle + await operationAllowedToReturn.signal() + await task.value + #expect(isIdleWhileOperationWasSuspended) + } + @Test func task_seesCallersTaskLocalValues() async throws { // Create the queue while a task-local value is bound: enqueued tasks must see their caller's values instead. @@ -571,22 +673,235 @@ struct ActorQueueTests { @Test func task_withPriority_executesAtThatPriority() async { - let (priorities, prioritiesContinuation) = AsyncStream.makeStream() // Use a queue of our own rather than `MainActor.queue`, which tests running in parallel share. let mainActorQueue = ActorQueue() mainActorQueue.adoptExecutionContext(of: MainActor.shared) - await Task.detached(priority: .high) { [systemUnderTest] in - // Do not await these tasks: awaiting them from this task would escalate them. - Task(priority: .low, on: systemUnderTest) { _ in + for priority in [TaskPriority.background, .low, .medium, .high] { + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .high) { [systemUnderTest] report in + Task(priority: priority, on: systemUnderTest) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { [systemUnderTest] report in + Task(priority: priority, on: systemUnderTest) { _ in try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: priority, on: mainActorQueue) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: priority, on: mainActorQueue) { try doWork(); report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == Array(repeating: priority, count: 4)) + } + } + + @Test + func task_onQueueWithPriority_withLowerPriority_executesAtQueuePriority() async { + let systemUnderTest = ActorQueue(priority: .medium) + systemUnderTest.adoptExecutionContext(of: counter) + let mainActorQueue = ActorQueue(priority: .medium) + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: .low, on: systemUnderTest) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: .low, on: systemUnderTest) { _ in try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: .low, on: mainActorQueue) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: .low, on: mainActorQueue) { try doWork(); report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == [.medium, .medium, .medium, .medium]) + } + + @Test + func task_onQueueWithPriority_withHigherPriority_executesAtThatPriority() async { + let systemUnderTest = ActorQueue(priority: .medium) + systemUnderTest.adoptExecutionContext(of: counter) + let mainActorQueue = ActorQueue(priority: .medium) + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(priority: .high, on: systemUnderTest) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(priority: .high, on: systemUnderTest) { _ in try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(priority: .high, on: mainActorQueue) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(priority: .high, on: mainActorQueue) { try doWork(); report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == [.high, .high, .high, .high]) + } + + @Test + func task_onQueueWithPriority_withNilPriority_executesAtHigherOfCallersAndQueuePriority() async { + let systemUnderTest = ActorQueue(priority: .medium) + systemUnderTest.adoptExecutionContext(of: counter) + let mainActorQueue = ActorQueue(priority: .medium) + mainActorQueue.adoptExecutionContext(of: MainActor.shared) + let executionPriorities = await [ + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(on: systemUnderTest) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(on: systemUnderTest) { _ in report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(on: systemUnderTest) { _ in try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(on: systemUnderTest) { _ in try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(on: mainActorQueue) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(on: mainActorQueue) { report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .background) { report in + Task(on: mainActorQueue) { try doWork(); report(Task.currentPriority) } + }, + priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(on: mainActorQueue) { try doWork(); report(Task.currentPriority) } + }, + ] + #expect(executionPriorities == [.medium, .high, .medium, .high, .medium, .high, .medium, .high]) + } + + @Test + func task_onQueueWithPriority_enqueuedFromEscalatedTaskWithLowerBasePriority_executesAtQueuePriority() async { + let systemUnderTest = ActorQueue(priority: .medium) + systemUnderTest.adoptExecutionContext(of: counter) + let enqueuingTaskAllowedToEnqueue = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + let enqueuingTask = Task.detached(priority: .background) { + // Wait for a higher-priority task to escalate this task above the queue's priority. + await enqueuingTaskAllowedToEnqueue.wait() + // Do not await the enqueued task: awaiting it would escalate it. + Task(on: systemUnderTest) { _ in prioritiesContinuation.yield(Task.currentPriority) } - Task(priority: .low, on: mainActorQueue) { - prioritiesContinuation.yield(Task.currentPriority) + } + await value(of: enqueuingTask, awaitedFromTaskWithPriority: .high) { + await enqueuingTaskAllowedToEnqueue.signal() + } + var prioritiesIterator = priorities.makeAsyncIterator() + let executionPriority = await prioritiesIterator.next() + #expect(executionPriority == .medium) + } + + @Test + func task_onQueueWithPriority_enqueuedOutsideOfAnyTask_executesAtHigherOfNewTaskAndQueuePriority() async { + // Threads without a quality of service take the default branch; threads with one, on platforms that support it, do not. + for qualityOfService in [QualityOfService.default, .userInitiated, .utility] { + for queuePriority in [TaskPriority.background, .low, .medium, .high] { + let systemUnderTest = ActorQueue(priority: queuePriority) + systemUnderTest.adoptExecutionContext(of: counter) + let (priorities, prioritiesContinuation) = AsyncStream<(isEnqueued: Bool, priority: TaskPriority)>.makeStream() + // Enqueue from a thread that is not running a task, and create a plain task there for comparison. + let thread = Thread { + Task { + prioritiesContinuation.yield((isEnqueued: false, priority: Task.currentPriority)) + } + Task(on: systemUnderTest) { _ in + prioritiesContinuation.yield((isEnqueued: true, priority: Task.currentPriority)) + } + } + thread.qualityOfService = qualityOfService + thread.start() + var plainTaskPriority: TaskPriority? + var executionPriority: TaskPriority? + // The thread reports exactly two priorities: one from each task. + for await (isEnqueued, priority) in priorities.prefix(2) { + if isEnqueued { + executionPriority = priority + } else { + plainTaskPriority = priority + } + } + #expect(plainTaskPriority.map { executionPriority == max($0, queuePriority) } == true) } - }.value + } + } + + @Test + func task_onQueueWithPriority_withUnspecifiedPriority_executesAtHigherOfCallersAndQueuePriority() async { + let systemUnderTest = ActorQueue(priority: .low) + systemUnderTest.adoptExecutionContext(of: counter) + // `Task` treats a priority with a raw value of zero as no priority, so the task inherits the caller's priority. + let executionPriority = await priorityOfTask(enqueuedFromTaskWithPriority: .high) { report in + Task(priority: TaskPriority(rawValue: 0), on: systemUnderTest) { _ in report(Task.currentPriority) } + } + #expect(executionPriority == .high) + } + + @Test + func task_onQueueWithUserInteractivePriority_enqueuedFromUserInteractiveTask_executesAtQueuePriority() async { + let userInteractivePriority = TaskPriority(rawValue: 0x21) + let systemUnderTest = ActorQueue(priority: userInteractivePriority) + systemUnderTest.adoptExecutionContext(of: counter) + // `Task` lowers an inherited user-interactive priority, so only the queue's priority keeps the task user-interactive. + let executionPriority = await priorityOfTask(enqueuedFromTaskWithPriority: userInteractivePriority) { report in + Task(on: systemUnderTest) { _ in report(Task.currentPriority) } + } + #expect(executionPriority == userInteractivePriority) + } + + @Test + func task_onQueueWithPriority_isEscalatedWhenAwaitedFromHigherPriorityTask() async { + let systemUnderTest = ActorQueue(priority: .low) + systemUnderTest.adoptExecutionContext(of: counter) + let taskStarted = Semaphore() + let taskAllowedToReturn = Semaphore() + let task = Task(priority: .background, on: systemUnderTest) { _ in + let startingPriority = Task.currentPriority + await taskStarted.signal() + await taskAllowedToReturn.wait() + return [startingPriority, Task.currentPriority] + } + await taskStarted.wait() + let priorities = await value(of: task, awaitedFromTaskWithPriority: .high) { + await taskAllowedToReturn.signal() + } + #expect(priorities[0] == .low) + #expect(priorities[1] >= .high) + } + + @available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *) + @Test + func throwingTask_onQueueWithPriority_isEscalatedWhenItsTurnBeginsWhileHigherPriorityTaskWaits() async { + let systemUnderTest = ActorQueue(priority: .low) + systemUnderTest.adoptExecutionContext(of: counter) + // Hold the turn before the task enqueued at `.background`, so that the task cannot begin its turn yet. + let heldTurn = systemUnderTest.turns.reserve() + let taskAllowedToReport = Semaphore() + let (priorities, prioritiesContinuation) = AsyncStream.makeStream() + // Never await this task before it reports its priority: awaiting it would escalate it without the queue's help. + let task = Task(priority: .background, on: systemUnderTest) { _ in + await taskAllowedToReport.wait() + try doWork() + prioritiesContinuation.yield(Task.currentPriority) + } + // This task waits for that task's turn to end, and so escalates that task once its turn begins. + let finishWaiting = runTaskWaitingForNextTurn(of: systemUnderTest.turns, withPriority: .high) + await heldTurn.begin() + // Ending the held turn escalates that task on behalf of the waiting task before `end()` returns. + heldTurn.end() + // That task may begin its turn before `end()` escalates it, so let it report only once `end()` has returned. + await taskAllowedToReport.signal() var prioritiesIterator = priorities.makeAsyncIterator() - #expect(await prioritiesIterator.next() == .low) - #expect(await prioritiesIterator.next() == .low) + let priority = await prioritiesIterator.next() + await finishWaiting() + _ = await task.result + #expect(priority.map { $0 >= .high } == true) } @Test diff --git a/Tests/AsyncQueueTests/FIFOQueueTests.swift b/Tests/AsyncQueueTests/FIFOQueueTests.swift index b8163cc..a833c12 100644 --- a/Tests/AsyncQueueTests/FIFOQueueTests.swift +++ b/Tests/AsyncQueueTests/FIFOQueueTests.swift @@ -570,6 +570,145 @@ struct FIFOQueueTests { #expect(didNextTurnBeginAfterTaskCompleted) } + @Test + func isIdle_onNewQueue_isTrue() { + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_afterTaskIsEnqueuedWhileOperationCannotReturn_isFalse() async { + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest) { + await operationAllowedToReturn.wait() + } + // `Task(on:)` takes the task's place on the queue before it returns, and the operation cannot return yet. + let isIdleAfterTaskWasEnqueued = systemUnderTest.isIdle + await operationAllowedToReturn.signal() + _ = await task.value + #expect(!isIdleAfterTaskWasEnqueued) + } + + @Test + func isIdle_whileOperationIsSuspended_isFalseUntilOperationReturns() async { + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest) { + await operationStarted.signal() + await operationAllowedToReturn.wait() + } + await operationStarted.wait() + // The task holds its place on the queue until its operation returns. + let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle + await operationAllowedToReturn.signal() + await task.value + #expect(!isIdleWhileOperationWasSuspended) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_whileThrowingOperationIsSuspended_isFalseUntilOperationThrows() async { + struct TestError: Error {} + let operationStarted = Semaphore() + let operationAllowedToThrow = Semaphore() + let task = Task(on: systemUnderTest) { + await operationStarted.signal() + await operationAllowedToThrow.wait() + throw TestError() + } + await operationStarted.wait() + // The task holds its place on the queue until its operation throws. + let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle + await operationAllowedToThrow.signal() + await #expect(throws: TestError.self) { try await task.value } + #expect(!isIdleWhileOperationWasSuspended) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_whileOperationIsolatedToActorIsSuspended_isFalseUntilOperationReturns() async { + let operationStarted = Semaphore() + let operationAllowedToReturn = Semaphore() + let task = Task(on: systemUnderTest, isolatedTo: Counter()) { _ in + await operationStarted.signal() + await operationAllowedToReturn.wait() + } + await operationStarted.wait() + // The task holds its place on the queue until its operation returns. + let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle + await operationAllowedToReturn.signal() + await task.value + #expect(!isIdleWhileOperationWasSuspended) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_whileThrowingOperationIsolatedToActorIsSuspended_isFalseUntilOperationThrows() async { + struct TestError: Error {} + let operationStarted = Semaphore() + let operationAllowedToThrow = Semaphore() + let task = Task(on: systemUnderTest, isolatedTo: Counter()) { _ in + await operationStarted.signal() + await operationAllowedToThrow.wait() + throw TestError() + } + await operationStarted.wait() + // The task holds its place on the queue until its operation throws. + let isIdleWhileOperationWasSuspended = systemUnderTest.isIdle + await operationAllowedToThrow.signal() + await #expect(throws: TestError.self) { try await task.value } + #expect(!isIdleWhileOperationWasSuspended) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_withCancelledTask_isFalseUntilItsOperationReturns() async { + let firstOperationAllowedToReturn = Semaphore() + let cancelledOperationStarted = Semaphore() + let cancelledOperationAllowedToReturn = Semaphore() + let firstTask = Task(on: systemUnderTest) { + await firstOperationAllowedToReturn.wait() + } + let cancelledTask = Task(on: systemUnderTest) { + await cancelledOperationStarted.signal() + await cancelledOperationAllowedToReturn.wait() + return Task.isCancelled + } + // The first operation cannot return yet, so this cancels the task while it waits on the queue. + cancelledTask.cancel() + await firstOperationAllowedToReturn.signal() + _ = await firstTask.value + // The cancelled task keeps its place on the queue, and its operation still runs. + let isIdleAfterFirstTaskCompleted = systemUnderTest.isIdle + await cancelledOperationStarted.wait() + let isIdleWhileCancelledOperationWasSuspended = systemUnderTest.isIdle + await cancelledOperationAllowedToReturn.signal() + let wasCancelledWhileOperationRan = await cancelledTask.value + #expect(!isIdleAfterFirstTaskCompleted) + #expect(!isIdleWhileCancelledOperationWasSuspended) + #expect(wasCancelledWhileOperationRan) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_withSeveralTasks_isFalseUntilLastOperationReturns() async { + let firstOperationAllowedToReturn = Semaphore() + let lastOperationAllowedToReturn = Semaphore() + let firstTask = Task(on: systemUnderTest) { + await firstOperationAllowedToReturn.wait() + } + let lastTask = Task(on: systemUnderTest) { + await lastOperationAllowedToReturn.wait() + } + await firstOperationAllowedToReturn.signal() + _ = await firstTask.value + // The last operation cannot return yet, so the last task still holds its place on the queue. + let isIdleAfterFirstTaskCompleted = systemUnderTest.isIdle + await lastOperationAllowedToReturn.signal() + _ = await lastTask.value + #expect(!isIdleAfterFirstTaskCompleted) + #expect(systemUnderTest.isIdle) + } + @Test func task_seesCallersTaskLocalValues() async throws { let systemUnderTest = TestTaskLocal.$value.withValue("queue creator") { diff --git a/Tests/AsyncQueueTests/TurnsTests.swift b/Tests/AsyncQueueTests/TurnsTests.swift index 075c03b..1d3136e 100644 --- a/Tests/AsyncQueueTests/TurnsTests.swift +++ b/Tests/AsyncQueueTests/TurnsTests.swift @@ -627,6 +627,59 @@ struct TurnsTests { #expect(priority.map { $0 >= .high } == true) } + @Test + func isIdle_beforeAnyTurnIsReserved_isTrue() { + let systemUnderTest = Turns() + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_afterTurnIsReserved_isFalseUntilTurnEnds() async { + let systemUnderTest = Turns() + let turn = systemUnderTest.reserve() + let isIdleAfterTurnWasReserved = systemUnderTest.isIdle + await turn.begin() + let isIdleAfterTurnBegan = systemUnderTest.isIdle + turn.end() + #expect(!isIdleAfterTurnWasReserved) + #expect(!isIdleAfterTurnBegan) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_withSeveralTurns_isFalseUntilLastTurnEnds() async { + let systemUnderTest = Turns() + let firstTurn = systemUnderTest.reserve() + let secondTurn = systemUnderTest.reserve() + let lastTurn = systemUnderTest.reserve() + await firstTurn.begin() + firstTurn.end() + let isIdleAfterFirstTurnEnded = systemUnderTest.isIdle + await secondTurn.begin() + secondTurn.end() + let isIdleAfterSecondTurnEnded = systemUnderTest.isIdle + await lastTurn.begin() + lastTurn.end() + #expect(!isIdleAfterFirstTurnEnded) + #expect(!isIdleAfterSecondTurnEnded) + #expect(systemUnderTest.isIdle) + } + + @Test + func isIdle_afterTurnIsReservedOnceEveryEarlierTurnEnded_isFalseUntilThatTurnEnds() async { + let systemUnderTest = Turns() + let firstTurn = systemUnderTest.reserve() + await firstTurn.begin() + firstTurn.end() + // The value is a snapshot: reserving another turn makes the turns busy again. + let laterTurn = systemUnderTest.reserve() + let isIdleAfterLaterTurnWasReserved = systemUnderTest.isIdle + await laterTurn.begin() + laterTurn.end() + #expect(!isIdleAfterLaterTurnWasReserved) + #expect(systemUnderTest.isIdle) + } + // MARK: Private /// Creates a task that takes `turn` and, once its turn begins, installs an escalation handler that uses `turns`,