diff --git a/Evolution/NNNN-map-error.md b/Evolution/NNNN-map-error.md new file mode 100644 index 00000000..04d59163 --- /dev/null +++ b/Evolution/NNNN-map-error.md @@ -0,0 +1,49 @@ +# Map Error + +* Proposal: [SAA-NNNN](NNNN-map-error.md) +* Authors: [Clive Liu](https://github.com/clive819) [Philippe Hausler](https://github.com/phausler) +* Review Manager: TBD +* Status: **Awaiting review** + +## Introduction + +Asynchronous sequences often particpate in carefully crafted systems of algorithms spliced together. Some of those algorithms require that both the element type and the failure type are the same as each-other. In order to line those types up for the element we have the map algorithm today, however there are other times at which when using more specific APIs that transforming the Failure type is needed. + +## Motivation + +The `mapError` function empowers developers to elegantly transform errors within asynchronous sequences, enhancing code readability and maintainability. + +Building failure-type-safe versions of zip or other algorithms will need to require that the associated Failure types are the same. Having an effecient and easy to use transformation routine to adjust the failure-types is then key to delivering or interfacing with those failure-type-safe algorithms. + +## Proposed solution + +A new extension and type will be added to transform the failure-types of AsyncSequences. + +## Detailed design + +The method will be applied to all AsyncSequences via an extension with the function name of `mapError`. This is spiritually related to the `mapError` method on `Result` and similar in functionality to other frameworks' methods of the similar naming. This will not return an opaque result since the type needs to be refined for `Sendable`; in that the `AsyncMapERrorSequence` is only `Sendable` when the base `AsyncSequence` is `Sendable`. + +```swift +extension AsyncSequence { + public func mapError(_ transform: @Sendable @escaping (Failure) async -> MappedFailure) -> AsyncMapErrorSequence +} + +public struct AsyncMapErrorSequence: AsyncSequence { } + +extension AsyncMapErrorSequence: Sendable where Base: Sendable { } + +@available(*, unavailable) +extension AsyncMapErrorSequence.Iterator: Sendable {} +``` + +## Effect on API resilience + +This cannot be back-deployed to 1.0 since it has a base requirement for the associated `Failure` and requires typed throws. + +## Naming + +The naming follows to current method naming of the Combine [mapError](https://developer.apple.com/documentation/combine/publisher/maperror(_:)) method and similarly the name of the method on `Result` + +## Alternatives considered + +It was initially considered that the return type would be opaque, however the only way to refine that as Sendable would be to have a disfavored overload; this ended up creating more ambiguity than it seemed worth. \ No newline at end of file diff --git a/Sources/AsyncAlgorithms/AsyncMapErrorSequence.swift b/Sources/AsyncAlgorithms/AsyncMapErrorSequence.swift new file mode 100644 index 00000000..b4a8b91f --- /dev/null +++ b/Sources/AsyncAlgorithms/AsyncMapErrorSequence.swift @@ -0,0 +1,93 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.0) +@available(AsyncAlgorithms 1.1, *) +extension AsyncSequence { + + /// Converts any failure into a new error. + /// + /// - Parameter transform: A closure that takes the failure as a parameter and returns a new error. + /// - Returns: An asynchronous sequence that maps the error thrown into the one produced by the transform closure. + /// + /// Use the ``mapError(_:)`` operator when you need to replace one error type with another. + @available(AsyncAlgorithms 1.1, *) + public func mapError( + _ transform: @Sendable @escaping (Failure) async -> MappedError + ) -> AsyncMapErrorSequence { + AsyncMapErrorSequence(base: self, transform: transform) + } +} + +/// An asynchronous sequence that converts any failure into a new error. +@available(AsyncAlgorithms 1.1, *) +public struct AsyncMapErrorSequence { + public typealias Element = Base.Element + public typealias Failure = MappedError + + private let base: Base + private let transform: @Sendable (Base.Failure) async -> MappedError + + init( + base: Base, + transform: @Sendable @escaping (Base.Failure) async -> MappedError + ) { + self.base = base + self.transform = transform + } +} + +@available(AsyncAlgorithms 1.1, *) +extension AsyncMapErrorSequence: AsyncSequence { + + /// The iterator that produces elements of the map sequence. + public struct Iterator: AsyncIteratorProtocol { + public typealias Element = Base.Element + + private var base: Base.AsyncIterator + + private let transform: @Sendable (Base.Failure) async -> MappedError + + init( + base: Base.AsyncIterator, + transform: @Sendable @escaping (Base.Failure) async -> MappedError + ) { + self.base = base + self.transform = transform + } + + public mutating func next() async throws(MappedError) -> Element? { + try await self.next(isolation: nil) + } + + public mutating func next(isolation actor: isolated (any Actor)?) async throws(MappedError) -> Element? { + do { + return try await base.next(isolation: actor) + } catch { + throw await transform(error) + } + } + } + + public func makeAsyncIterator() -> Iterator { + Iterator( + base: base.makeAsyncIterator(), + transform: transform + ) + } +} + +@available(AsyncAlgorithms 1.1, *) +extension AsyncMapErrorSequence: Sendable where Base: Sendable {} + +@available(*, unavailable) +extension AsyncMapErrorSequence.Iterator: Sendable {} +#endif diff --git a/Tests/AsyncAlgorithmsTests/TestMapError.swift b/Tests/AsyncAlgorithmsTests/TestMapError.swift new file mode 100644 index 00000000..ef3a0ddb --- /dev/null +++ b/Tests/AsyncAlgorithmsTests/TestMapError.swift @@ -0,0 +1,117 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import AsyncAlgorithms +import XCTest + +#if compiler(>=6.0) +@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) +final class TestMapError: XCTestCase { + + func test_mapError() async throws { + let array: [Any] = [1, 2, 3, MyAwesomeError.originalError, 4, 5, 6] + let sequence = array.async + .map { + if let error = $0 as? Error { + throw error + } else { + $0 as! Int + } + } + .mapError { _ in + MyAwesomeError.mappedError + } + + var results: [Int] = [] + + do { + for try await number in sequence { + results.append(number) + } + XCTFail("sequence should throw") + } catch { + XCTAssertEqual(error, .mappedError) + } + + XCTAssertEqual(results, [1, 2, 3]) + } + + func test_mapError_cancellation() async throws { + let value = "test" + let source = Indefinite(value: value).async + let sequence = + source + .map { + if $0 == "just to trick compiler that this may throw" { + throw MyAwesomeError.originalError + } else { + $0 + } + } + .mapError { _ in + MyAwesomeError.mappedError + } + + let finished = expectation(description: "finished") + let iterated = expectation(description: "iterated") + + let task = Task { + var firstIteration = false + for try await el in sequence { + XCTAssertEqual(el, value) + + if !firstIteration { + firstIteration = true + iterated.fulfill() + } + } + finished.fulfill() + } + + // ensure the other task actually starts + await fulfillment(of: [iterated], timeout: 1.0) + // cancellation should ensure the loop finishes + // without regards to the remaining underlying sequence + task.cancel() + await fulfillment(of: [finished], timeout: 1.0) + } + + func test_mapError_empty() async throws { + let array: [String] = [] + let sequence = array.async + .map { + if $0 == "just to trick compiler that this may throw" { + throw MyAwesomeError.originalError + } else { + $0 + } + } + .mapError { _ in + MyAwesomeError.mappedError + } + + var results: [String] = [] + for try await value in sequence { + results.append(value) + } + XCTAssert(results.isEmpty) + } +} + +@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) +extension TestMapError { + + fileprivate enum MyAwesomeError: Error { + case originalError + case mappedError + } +} +#endif