- 
                Notifications
    You must be signed in to change notification settings 
- Fork 185
mapError - transforming failures #366
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            phausler
  wants to merge
  5
  commits into
  apple:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
phausler:pr/mapError
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            5 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      598ca12
              
                Implement AsyncMapErrorSequence
              
              
                clive819 6a958fd
              
                Update the proposal, implementation and tests with formatting, additi…
              
              
                phausler e59c3a2
              
                Foratting and preambles
              
              
                phausler 9ad2465
              
                Update Copyright date for error sequence
              
              
                phausler 980e5f7
              
                Update copyright year for mapError tests
              
              
                phausler File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | 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. | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | 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) 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<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 | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | 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) 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 | ||
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
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-testinghere?