From 07d1255c92f1020904010e63286b721cc1a52fac Mon Sep 17 00:00:00 2001 From: Nikita Vasilev Date: Fri, 6 Nov 2026 12:50:13 +0400 Subject: [PATCH 1/3] feat: add TypedTask to keep the error type of a task --- Package.swift | 2 +- Package@swift-5.10.swift | 2 +- README.md | 38 ++++++ .../TaskFactory/ITaskFactory.swift | 45 +++++++ .../Concurrency/TaskFactory/TaskFactory.swift | 16 +++ .../Concurrency/TaskFactory/TypedTask.swift | 110 ++++++++++++++++++ Sources/TestConcurrency/Task.swift | 11 ++ Sources/TestConcurrency/TestTaskFactory.swift | 18 +++ Tests/ConcurrencyTests/TaskFactoryTests.swift | 109 +++++++++++++++++ Tests/ConcurrencyTests/TypedTaskTests.swift | 105 +++++++++++++++++ 10 files changed, 454 insertions(+), 2 deletions(-) create mode 100644 Sources/Concurrency/TaskFactory/TypedTask.swift create mode 100644 Tests/ConcurrencyTests/TaskFactoryTests.swift create mode 100644 Tests/ConcurrencyTests/TypedTaskTests.swift diff --git a/Package.swift b/Package.swift index 7c960ed..c2a5902 100644 --- a/Package.swift +++ b/Package.swift @@ -19,6 +19,6 @@ let package = Package( targets: [ .target(name: "Concurrency", dependencies: []), .target(name: "TestConcurrency", dependencies: ["Concurrency"]), - .testTarget(name: "ConcurrencyTests", dependencies: ["Concurrency"]), + .testTarget(name: "ConcurrencyTests", dependencies: ["Concurrency", "TestConcurrency"]), ] ) diff --git a/Package@swift-5.10.swift b/Package@swift-5.10.swift index e0ea80c..c571607 100644 --- a/Package@swift-5.10.swift +++ b/Package@swift-5.10.swift @@ -19,6 +19,6 @@ let package = Package( targets: [ .target(name: "Concurrency", dependencies: []), .target(name: "TestConcurrency", dependencies: ["Concurrency"]), - .testTarget(name: "ConcurrencyTests", dependencies: ["Concurrency"]), + .testTarget(name: "ConcurrencyTests", dependencies: ["Concurrency", "TestConcurrency"]), ] ) diff --git a/README.md b/README.md index ebad62c..c5a1dce 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ ## Features ✨ **Type-Safe Queue Abstractions** - Clean interfaces for main, global, and custom queues +🧵 **Typed Task Failures** - `TypedTask` keeps the error type of a `throws(Failure)` operation 🧪 **Built for Testing** - Comes with dedicated test doubles for unit testing ⚡ **Lightweight** - Minimal wrapper around GCD with zero overhead 🎯 **Protocol-Based** - Easy to mock and inject dependencies @@ -31,6 +32,8 @@ - [Main Queue](#main-queue) - [Global Queue](#global-queue) - [Private Queue](#private-queue) + - [Task Factory](#task-factory) + - [Typed Task](#typed-task) - [Testing](#testing) - [Communication](#communication) - [Contributing](#contributing) @@ -203,6 +206,41 @@ class NetworkManager { - `autoreleaseFrequency` - Memory management strategy - `target` - Queue to execute blocks on (advanced usage) +### Task Factory + +`ITaskFactory` creates Swift concurrency tasks, so code that starts a task can be given a test double: + +```swift +import Concurrency + +let factory: ITaskFactory = TaskFactory() + +factory.task { await refresh() } // tied to the current actor +factory.detached { try await export() } // detached from it +``` + +### Typed Task + +A `Task` created by the standard library only fails with `Never` or `any Error`, so the error type of an operation that +`throws(NetworkError)` is lost. `typedTask` and `typedDetached` return a `TypedTask`, which keeps it: + +```swift +let task = factory.typedTask { () async throws(NetworkError) -> User in + try await client.loadUser() +} + +do throws(NetworkError) { + let user = try await task.value +} catch { + // `error` is a `NetworkError`, no cast is needed. +} + +let result: Result = await task.result +``` + +`TypedTask` is `Hashable` like `Task`, can be cancelled with `cancel()`, and `TestTaskFactory` waits for it in +`waitUntilIdle()` like it does for the other tasks. + ## Testing Concurrency includes a dedicated test target with synchronous test doubles: diff --git a/Sources/Concurrency/TaskFactory/ITaskFactory.swift b/Sources/Concurrency/TaskFactory/ITaskFactory.swift index bd87057..05ff9bc 100644 --- a/Sources/Concurrency/TaskFactory/ITaskFactory.swift +++ b/Sources/Concurrency/TaskFactory/ITaskFactory.swift @@ -62,6 +62,30 @@ import Foundation priority: TaskPriority?, @_inheritActorContext operation: sending @escaping @isolated(any) () async -> Success ) -> Task + + /// Creates a task tied to the current actor context whose operation fails with a specific type of error. + /// - Parameters: + /// - priority: The priority of the task (optional). + /// - operation: An asynchronous operation to execute within the task. The operation + /// inherits the current actor context and is isolated to that actor. + /// - Returns: A ``TypedTask`` that keeps the type of the error of the operation. + @discardableResult + func typedTask( + priority: TaskPriority?, + @_inheritActorContext operation: sending @escaping @isolated(any) () async throws(Failure) -> Success + ) -> TypedTask + + /// Creates a detached task whose operation fails with a specific type of error. + /// - Parameters: + /// - priority: The priority of the task (optional). + /// - operation: An asynchronous operation to execute within the task. The operation + /// is isolated and does not inherit the current actor context. + /// - Returns: A ``TypedTask`` that keeps the type of the error of the operation. + @discardableResult + func typedDetached( + priority: TaskPriority?, + @_inheritActorContext operation: sending @escaping @isolated(any) () async throws(Failure) -> Success + ) -> TypedTask } /// Default implementations for the `ITaskFactory` protocol. @@ -109,5 +133,26 @@ import Foundation ) -> Task { detached(priority: nil, operation: operation) } + + /// Creates a task tied to the current actor context with a default priority whose operation + /// fails with a specific type of error. + /// - Parameter operation: An asynchronous operation to execute within the task. + /// - Returns: A ``TypedTask`` that keeps the type of the error of the operation. + @discardableResult + func typedTask( + @_inheritActorContext operation: sending @escaping @isolated(any) () async throws(Failure) -> Success + ) -> TypedTask { + typedTask(priority: nil, operation: operation) + } + + /// Creates a detached task with a default priority whose operation fails with a specific type of error. + /// - Parameter operation: An asynchronous operation to execute within the task. + /// - Returns: A ``TypedTask`` that keeps the type of the error of the operation. + @discardableResult + func typedDetached( + @_inheritActorContext operation: sending @escaping @isolated(any) () async throws(Failure) -> Success + ) -> TypedTask { + typedDetached(priority: nil, operation: operation) + } } #endif diff --git a/Sources/Concurrency/TaskFactory/TaskFactory.swift b/Sources/Concurrency/TaskFactory/TaskFactory.swift index 3ac86c9..86d5072 100644 --- a/Sources/Concurrency/TaskFactory/TaskFactory.swift +++ b/Sources/Concurrency/TaskFactory/TaskFactory.swift @@ -42,5 +42,21 @@ ) -> Task { Task.detached(priority: priority, operation: operation) } + + @discardableResult + public func typedTask( + priority: TaskPriority?, + @_inheritActorContext operation: sending @escaping @isolated(any) () async throws(Failure) -> Success + ) -> TypedTask { + TypedTask(priority: priority, operation: operation) + } + + @discardableResult + public func typedDetached( + priority: TaskPriority?, + @_inheritActorContext operation: sending @escaping @isolated(any) () async throws(Failure) -> Success + ) -> TypedTask { + TypedTask.detached(priority: priority, operation: operation) + } } #endif diff --git a/Sources/Concurrency/TaskFactory/TypedTask.swift b/Sources/Concurrency/TaskFactory/TypedTask.swift new file mode 100644 index 0000000..3b78d4a --- /dev/null +++ b/Sources/Concurrency/TaskFactory/TypedTask.swift @@ -0,0 +1,110 @@ +// +// Concurrency +// Copyright © 2026 Space Code. All rights reserved. +// + +#if swift(>=6.0) + + // MARK: - TypedTask + + /// A unit of asynchronous work that fails with a specific type of error. + /// + /// The standard library only creates a `Task` that fails with `Never` or `any Error`, so a task whose operation + /// `throws(MyError)` loses its error type. `TypedTask` keeps it: awaiting ``value`` throws `Failure`, and + /// ``result`` is a `Result`. + /// + /// ```swift + /// let task = TypedTask { () async throws(NetworkError) -> User in + /// try await client.loadUser() + /// } + /// + /// do throws(NetworkError) { + /// let user = try await task.value + /// } catch { + /// // `error` is a `NetworkError`. + /// } + /// ``` + /// + /// Cancelling a `TypedTask` cancels the work like cancelling a `Task` does: it only sets a flag that the operation + /// reads, and the operation decides whether to fail. + public struct TypedTask: Sendable, Hashable { + // MARK: Properties + + private let task: Task, Never> + + // MARK: Initialization + + /// Runs the operation in a new task that inherits the actor context of the caller. + /// + /// - Parameters: + /// - priority: The priority of the task. Pass `nil` to inherit the priority of the caller. + /// - operation: The operation to run. It can only fail with `Failure`. + public init( + priority: TaskPriority? = nil, + @_inheritActorContext operation: sending @escaping @isolated(any) () async throws(Failure) -> Success + ) { + task = Task(priority: priority) { + await Self.run(operation) + } + } + + private init(task: Task, Never>) { + self.task = task + } + + // MARK: Interface + + /// The success value of the task, or the error it failed with. + /// + /// Waiting for the value does not cancel the task when the waiting code is cancelled. + public var value: Success { + get async throws(Failure) { + try await task.value.get() + } + } + + /// The outcome of the task, once it has finished. + public var result: Result { + get async { + await task.value + } + } + + /// Whether the task was cancelled. + public var isCancelled: Bool { + task.isCancelled + } + + /// Runs the operation in a new task that does not inherit the actor context of the caller. + /// + /// - Parameters: + /// - priority: The priority of the task. Pass `nil` to use the default priority. + /// - operation: The operation to run. It can only fail with `Failure`. + /// - Returns: The task that runs the operation. + public static func detached( + priority: TaskPriority? = nil, + operation: sending @escaping @isolated(any) () async throws(Failure) -> Success + ) -> TypedTask { + TypedTask(task: Task.detached(priority: priority) { + await run(operation) + }) + } + + /// Cancels the task. + public func cancel() { + task.cancel() + } + + // MARK: Private + + private static func run( + _ operation: @isolated(any) () async throws(Failure) -> Success + ) async -> Result { + do throws(Failure) { + return try await .success(operation()) + } catch { + return .failure(error) + } + } + } +#endif diff --git a/Sources/TestConcurrency/Task.swift b/Sources/TestConcurrency/Task.swift index d6f9c05..dbf4ae8 100644 --- a/Sources/TestConcurrency/Task.swift +++ b/Sources/TestConcurrency/Task.swift @@ -6,6 +6,8 @@ // MARK: - ITask #if swift(>=6.0) + import Concurrency + /// A protocol representing a task that can be awaited until its execution completes. protocol ITask { /// Waits for the `Task` to complete by retrieving its result. @@ -20,4 +22,13 @@ _ = await result } } + + // MARK: - TypedTask + ITask + + /// Extends the `TypedTask` type to conform to the `ITask` protocol. + extension TypedTask: ITask { + func wait() async { + _ = await result + } + } #endif diff --git a/Sources/TestConcurrency/TestTaskFactory.swift b/Sources/TestConcurrency/TestTaskFactory.swift index fe098af..4d5f5c1 100644 --- a/Sources/TestConcurrency/TestTaskFactory.swift +++ b/Sources/TestConcurrency/TestTaskFactory.swift @@ -81,5 +81,23 @@ import Foundation addTask(task) return task } + + public func typedTask( + priority: TaskPriority?, + @_inheritActorContext operation: sending @escaping @isolated(any) () async throws(Failure) -> Success + ) -> TypedTask { + let task = TypedTask(priority: priority, operation: operation) + addTask(task) + return task + } + + public func typedDetached( + priority: TaskPriority?, + @_inheritActorContext operation: sending @escaping @isolated(any) () async throws(Failure) -> Success + ) -> TypedTask { + let task = TypedTask.detached(priority: priority, operation: operation) + addTask(task) + return task + } } #endif diff --git a/Tests/ConcurrencyTests/TaskFactoryTests.swift b/Tests/ConcurrencyTests/TaskFactoryTests.swift new file mode 100644 index 0000000..61d335d --- /dev/null +++ b/Tests/ConcurrencyTests/TaskFactoryTests.swift @@ -0,0 +1,109 @@ +// +// Concurrency +// Copyright © 2026 Space Code. All rights reserved. +// + +@testable import Concurrency +import TestConcurrency +import XCTest + +#if swift(>=6.0) + + // MARK: - TaskFactoryTests + + final class TaskFactoryTests: XCTestCase { + // MARK: Types + + private enum TestError: Error, Equatable { + case failed + } + + // MARK: Tests + + func testThatTaskFactoryKeepsTheTypeOfTheErrorOfATypedTask() async { + // given + let sut: ITaskFactory = TaskFactory() + + // when + let task = sut.typedTask { () async throws(TestError) -> Int in throw .failed } + let result = await task.result + + // then + XCTAssertEqual(result, .failure(.failed)) + } + + func testThatTaskFactoryKeepsTheTypeOfTheErrorOfATypedDetachedTask() async { + // given + let sut: ITaskFactory = TaskFactory() + + // when + let task = sut.typedDetached { () async throws(TestError) -> Int in throw .failed } + let result = await task.result + + // then + XCTAssertEqual(result, .failure(.failed)) + } + + func testThatTaskFactoryStillMakesUntypedAndNonThrowingTasks() async throws { + // given + let sut: ITaskFactory = TaskFactory() + + // when + let throwing = sut.task { () async throws -> Int in 1 } + let nonThrowing = sut.task { 2 } + + // then + let first = try await throwing.value + let second = await nonThrowing.value + XCTAssertEqual(first, 1) + XCTAssertEqual(second, 2) + } + + func testThatTestTaskFactoryWaitsForTypedTasks() async { + // given + let sut = TestTaskFactory() + let finished = Flag() + + // when + _ = sut.typedTask { () async throws(TestError) in + await Task.yield() + finished.set() + } + await sut.waitUntilIdle() + + // then + XCTAssertTrue(finished.isSet) + } + + func testThatTestTaskFactoryWaitsForTypedDetachedTasks() async { + // given + let sut = TestTaskFactory() + let finished = Flag() + + // when + _ = sut.typedDetached { () async throws(TestError) in + await Task.yield() + finished.set() + } + await sut.waitUntilIdle() + + // then + XCTAssertTrue(finished.isSet) + } + } + + // MARK: - Flag + + private final class Flag: @unchecked Sendable { + private let lock = NSLock() + private var value = false + + var isSet: Bool { + lock.withLock { value } + } + + func set() { + lock.withLock { value = true } + } + } +#endif diff --git a/Tests/ConcurrencyTests/TypedTaskTests.swift b/Tests/ConcurrencyTests/TypedTaskTests.swift new file mode 100644 index 0000000..ea9d5c6 --- /dev/null +++ b/Tests/ConcurrencyTests/TypedTaskTests.swift @@ -0,0 +1,105 @@ +// +// Concurrency +// Copyright © 2026 Space Code. All rights reserved. +// + +@testable import Concurrency +import XCTest + +#if swift(>=6.0) + + // MARK: - TypedTaskTests + + final class TypedTaskTests: XCTestCase { + // MARK: Types + + private enum TestError: Error, Equatable { + case failed + } + + // MARK: Tests + + func testThatTypedTaskReturnsTheValueOfTheOperation() async throws { + // given + let sut = TypedTask { () async throws(TestError) -> Int in 42 } + + // when + let value = try await sut.value + + // then + XCTAssertEqual(value, 42) + } + + func testThatTypedTaskThrowsTheTypedErrorOfTheOperation() async { + // given + let sut = TypedTask { () async throws(TestError) -> Int in throw .failed } + + // when + var thrown: TestError? + do throws(TestError) { + _ = try await sut.value + } catch { + thrown = error + } + + // then + XCTAssertEqual(thrown, .failed) + } + + func testThatTypedTaskResultKeepsTheTypeOfTheError() async { + // given + let sut = TypedTask { () async throws(TestError) -> Int in throw .failed } + + // when + let result: Result = await sut.result + + // then + XCTAssertEqual(result, .failure(.failed)) + } + + func testThatTypedTaskRunsTheOperationDetached() async throws { + // given + let sut = TypedTask.detached { "detached" } + + // when + let value = try await sut.value + + // then + XCTAssertEqual(value, "detached") + } + + func testThatTypedTaskReportsCancellation() async { + // given + let sut = TypedTask { () async throws(TestError) -> Bool in + while !Task.isCancelled { + await Task.yield() + } + return Task.isCancelled + } + + // when + sut.cancel() + let wasCancelled = await (sut.result.success ?? false) + + // then + XCTAssertTrue(sut.isCancelled) + XCTAssertTrue(wasCancelled) + } + + func testThatEqualTypedTasksAreTheSameTask() { + // given + let first = TypedTask { () async throws(TestError) -> Int in 1 } + let second = TypedTask { () async throws(TestError) -> Int in 1 } + + // then + XCTAssertEqual(first, first) + XCTAssertNotEqual(first, second) + } + } + + private extension Result { + var success: Success? { + try? get() + } + } +#endif From 7656f917f7151911a5238d07aa65a545d6eb1c9c Mon Sep 17 00:00:00 2001 From: Nikita Vasilev Date: Fri, 6 Nov 2026 12:55:55 +0400 Subject: [PATCH 2/3] ci: move off the retired macOS 14 runners --- .github/workflows/ci.yml | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 177aa74..8fa8051 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,24 +48,19 @@ jobs: include: # macOS - { platform: macOS, name: "macOS 26, Xcode 26.5, Swift 6.2.0", xcode: "Xcode_26.5", runsOn: macOS-26, destination: "platform=macOS" } - - { platform: macOS, name: "macOS 14, Xcode 16.1, Swift 6.0.2", xcode: "Xcode_16.1", runsOn: macOS-14, destination: "platform=macOS" } - - { platform: macOS, name: "macOS 14, Xcode 15.4, Swift 5.10", xcode: "Xcode_15.4", runsOn: macOS-14, destination: "platform=macOS" } + - { platform: macOS, name: "macOS 15, Xcode 16.1, Swift 6.0.2", xcode: "Xcode_16.1", runsOn: macOS-15, destination: "platform=macOS" } # iOS - { platform: iOS, name: "iOS 26.5", xcode: "Xcode_26.5", runsOn: macOS-26, destination: "OS=26.5,name=iPhone 17 Pro" } - - { platform: iOS, name: "iOS 18.1", xcode: "Xcode_16.1", runsOn: macOS-14, destination: "OS=18.1,name=iPhone 16 Pro" } - - { platform: iOS, name: "iOS 17.4", xcode: "Xcode_15.3", runsOn: macOS-14, destination: "OS=17.4,name=iPhone 15 Pro" } + - { platform: iOS, name: "iOS 18.5", xcode: "Xcode_16.4", runsOn: macOS-15, destination: "OS=18.5,name=iPhone 16 Pro" } # tvOS - { platform: tvOS, name: "tvOS 26.5", xcode: "Xcode_26.5", runsOn: macOS-26, destination: "OS=26.5,name=Apple TV" } - - { platform: tvOS, name: "tvOS 18.1", xcode: "Xcode_16.1", runsOn: macOS-14, destination: "OS=18.1,name=Apple TV" } - - { platform: tvOS, name: "tvOS 17.4", xcode: "Xcode_15.3", runsOn: macOS-14, destination: "OS=17.4,name=Apple TV" } + - { platform: tvOS, name: "tvOS 18.5", xcode: "Xcode_16.4", runsOn: macOS-15, destination: "OS=18.5,name=Apple TV" } # watchOS - { platform: watchOS, name: "watchOS 26.5", xcode: "Xcode_26.5", runsOn: macOS-26, destination: "OS=26.5,name=Apple Watch Ultra 3 (49mm)" } - - { platform: watchOS, name: "watchOS 11.1", xcode: "Xcode_16.1", runsOn: macOS-14, destination: "OS=11.1,name=Apple Watch Series 10 (46mm)" } - - { platform: watchOS, name: "watchOS 10.5", xcode: "Xcode_15.3", runsOn: macOS-14, destination: "OS=10.5,name=Apple Watch Series 9 (45mm)" } - - { platform: watchOS, name: "watchOS 10.4", xcode: "Xcode_15.3", runsOn: macOS-14, destination: "OS=10.4,name=Apple Watch Series 9 (45mm)" } + - { platform: watchOS, name: "watchOS 11.5", xcode: "Xcode_16.4", runsOn: macOS-15, destination: "OS=11.5,name=Apple Watch Series 10 (46mm)" } steps: - name: Checkout code uses: actions/checkout@v7 @@ -89,9 +84,7 @@ jobs: matrix: include: - { name: "macOS 26, SPM 6.2.0", xcode: "Xcode_26.1.1", runsOn: macOS-26 } - - { name: "macOS 15, SPM 6.0.2", xcode: "Xcode_16.0", runsOn: macOS-15 } - - { name: "macOS 14, SPM 6.0.2", xcode: "Xcode_16.1", runsOn: macOS-14 } - - { name: "macOS 14, SPM 5.10.0", xcode: "Xcode_15.3", runsOn: macOS-14 } + - { name: "macOS 15, SPM 6.0.2", xcode: "Xcode_16.1", runsOn: macOS-15 } steps: - name: Checkout code uses: actions/checkout@v7 From 6f19b54c919adf39efa3d4f8c2a371114bf8b3ce Mon Sep 17 00:00:00 2001 From: Nikita Vasilev Date: Fri, 6 Nov 2026 13:03:52 +0400 Subject: [PATCH 3/3] ci: run simulator jobs on macOS 26 --- .github/workflows/ci.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8fa8051..3985bf5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,15 +52,15 @@ jobs: # iOS - { platform: iOS, name: "iOS 26.5", xcode: "Xcode_26.5", runsOn: macOS-26, destination: "OS=26.5,name=iPhone 17 Pro" } - - { platform: iOS, name: "iOS 18.5", xcode: "Xcode_16.4", runsOn: macOS-15, destination: "OS=18.5,name=iPhone 16 Pro" } + - { platform: iOS, name: "iOS 26.2", xcode: "Xcode_26.2", runsOn: macOS-26, destination: "OS=26.2,name=iPhone 17 Pro" } # tvOS - { platform: tvOS, name: "tvOS 26.5", xcode: "Xcode_26.5", runsOn: macOS-26, destination: "OS=26.5,name=Apple TV" } - - { platform: tvOS, name: "tvOS 18.5", xcode: "Xcode_16.4", runsOn: macOS-15, destination: "OS=18.5,name=Apple TV" } + - { platform: tvOS, name: "tvOS 26.2", xcode: "Xcode_26.2", runsOn: macOS-26, destination: "OS=26.2,name=Apple TV" } # watchOS - { platform: watchOS, name: "watchOS 26.5", xcode: "Xcode_26.5", runsOn: macOS-26, destination: "OS=26.5,name=Apple Watch Ultra 3 (49mm)" } - - { platform: watchOS, name: "watchOS 11.5", xcode: "Xcode_16.4", runsOn: macOS-15, destination: "OS=11.5,name=Apple Watch Series 10 (46mm)" } + - { platform: watchOS, name: "watchOS 26.2", xcode: "Xcode_26.2", runsOn: macOS-26, destination: "OS=26.2,name=Apple Watch Ultra 3 (49mm)" } steps: - name: Checkout code uses: actions/checkout@v7