Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
49 changes: 49 additions & 0 deletions Evolution/NNNN-map-error.md
Original file line number Diff line number Diff line change
@@ -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<MappedFailure: Error>(_ transform: @Sendable @escaping (Failure) async -> MappedFailure) -> AsyncMapErrorSequence<Element, MappedFailure>
}

public struct AsyncMapErrorSequence<Base: AsyncSequence, TransformedFailure: Error>: 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.
93 changes: 93 additions & 0 deletions Sources/AsyncAlgorithms/AsyncMapErrorSequence.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 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<MappedError: Error>(
_ transform: @Sendable @escaping (Failure) async -> MappedError
) -> AsyncMapErrorSequence<Self, MappedError> {
AsyncMapErrorSequence(base: self, transform: transform)
}
}

/// An asynchronous sequence that converts any failure into a new error.
@available(AsyncAlgorithms 1.1, *)
public struct AsyncMapErrorSequence<Base: AsyncSequence, MappedError: Error> {
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
117 changes: 117 additions & 0 deletions Tests/AsyncAlgorithmsTests/TestMapError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 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 {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we start using swift-testing here?


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