- 
                Notifications
    You must be signed in to change notification settings 
- Fork 185
Retry & Backoff #364
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
      
      
            ph1ps
  wants to merge
  14
  commits into
  apple:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
ph1ps:retry
  
      
      
   
  
    
  
  
  
 
  
      
    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
                    Retry & Backoff #364
Changes from 3 commits
      Commits
    
    
            Show all changes
          
          
            14 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      c75fc64
              
                add retry&backoff
              
              
                ph1ps f32aca6
              
                add missing inlinable annotation
              
              
                ph1ps 03b623d
              
                correct logic
              
              
                ph1ps f8cb3cd
              
                mr feedback (#1)
              
              
                ph1ps 09538a5
              
                clean up and preconditions (#2)
              
              
                ph1ps a5ff83c
              
                correct decorrelated algorithm
              
              
                ph1ps b4b66ec
              
                revert package shuffle
              
              
                ph1ps c8e6f99
              
                fix availability (#4)
              
              
                ph1ps 24475e9
              
                add proposal, unit tests and implement feedback (#5)
              
              
                ph1ps 2406360
              
                add docs
              
              
                ph1ps 69fbbdb
              
                Merge branch 'apple:main' into retry
              
              
                ph1ps 93f21b4
              
                unify docs and proposal
              
              
                ph1ps 0d21f31
              
                Update NNNN-retry-backoff.md
              
              
                ph1ps d67a1f1
              
                use nonisolated(nonsending)
              
              
                ph1ps 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
          Some comments aren't visible on the classic Files Changed page.
        
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
    
  
  
    
              
  
    
      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,198 @@ | ||
| import _CPowSupport | ||
|  | ||
| #if compiler(<6.2) | ||
| @available(iOS 18.0, macCatalyst 18.0, macOS 15.0, tvOS 18.0, visionOS 2.0, watchOS 11.0, *) | ||
| extension Duration { | ||
| @usableFromInline var attoseconds: Int128 { | ||
| return Int128(_low: _low, _high: _high) | ||
| } | ||
| @usableFromInline init(attoseconds: Int128) { | ||
| self.init(_high: attoseconds._high, low: attoseconds._low) | ||
| } | ||
| } | ||
| #endif | ||
|  | ||
| @available(iOS 16.0, macCatalyst 16.0, macOS 13.0, tvOS 16.0, visionOS 1.0, watchOS 9.0, *) | ||
| public protocol BackoffStrategy<Duration> { | ||
| associatedtype Duration: DurationProtocol | ||
| mutating func duration(_ attempt: Int) -> Duration | ||
| mutating func duration(_ attempt: Int, using generator: inout some RandomNumberGenerator) -> Duration | ||
| } | ||
|  | ||
| @available(iOS 16.0, macCatalyst 16.0, macOS 13.0, tvOS 16.0, visionOS 1.0, watchOS 9.0, *) | ||
| extension BackoffStrategy { | ||
| @inlinable public mutating func duration(_ attempt: Int, using generator: inout some RandomNumberGenerator) -> Duration { | ||
|         
                  ph1ps marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| return duration(attempt) | ||
| } | ||
| } | ||
|  | ||
| @available(iOS 16.0, macCatalyst 16.0, macOS 13.0, tvOS 16.0, visionOS 1.0, watchOS 9.0, *) | ||
| @usableFromInline | ||
| struct ConstantBackoffStrategy<Duration: DurationProtocol>: BackoffStrategy { | ||
| @usableFromInline let c: Duration | ||
| @usableFromInline init(c: Duration) { | ||
| self.c = c | ||
| } | ||
| @inlinable func duration(_ attempt: Int) -> Duration { | ||
| return c | ||
| } | ||
| } | ||
|  | ||
| @available(iOS 16.0, macCatalyst 16.0, macOS 13.0, tvOS 16.0, visionOS 1.0, watchOS 9.0, *) | ||
| @usableFromInline | ||
| struct LinearBackoffStrategy<Duration: DurationProtocol>: BackoffStrategy { | ||
| @usableFromInline let a: Duration | ||
| @usableFromInline let b: Duration | ||
| @usableFromInline init(a: Duration, b: Duration) { | ||
| self.a = a | ||
| self.b = b | ||
| } | ||
| @inlinable func duration(_ attempt: Int) -> Duration { | ||
| return a * attempt + b | ||
| } | ||
| } | ||
|  | ||
| @available(iOS 16.0, macCatalyst 16.0, macOS 13.0, tvOS 16.0, visionOS 1.0, watchOS 9.0, *) | ||
| @usableFromInline struct ExponentialBackoffStrategy: BackoffStrategy { | ||
| @usableFromInline let a: Duration | ||
|         
                  ph1ps marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| @usableFromInline let b: Double | ||
| @usableFromInline init(a: Duration, b: Double) { | ||
| self.a = a | ||
| self.b = b | ||
| } | ||
| @inlinable func duration(_ attempt: Int) -> Duration { | ||
| return a * pow(b, Double(attempt)) | ||
|         
                  ph1ps marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| } | ||
| } | ||
|  | ||
| @available(iOS 16.0, macCatalyst 16.0, macOS 13.0, tvOS 16.0, visionOS 1.0, watchOS 9.0, *) | ||
| @usableFromInline | ||
| struct MinimumBackoffStrategy<Base: BackoffStrategy>: BackoffStrategy { | ||
| @usableFromInline var base: Base | ||
| @usableFromInline let minimum: Base.Duration | ||
| @usableFromInline init(base: Base, minimum: Base.Duration) { | ||
| self.base = base | ||
| self.minimum = minimum | ||
| } | ||
| @inlinable mutating func duration(_ attempt: Int) -> Base.Duration { | ||
| return max(minimum, base.duration(attempt)) | ||
| } | ||
| @inlinable mutating func duration(_ attempt: Int, using generator: inout some RandomNumberGenerator) -> Base.Duration { | ||
| return max(minimum, base.duration(attempt, using: &generator)) | ||
| } | ||
| } | ||
|  | ||
| @available(iOS 16.0, macCatalyst 16.0, macOS 13.0, tvOS 16.0, visionOS 1.0, watchOS 9.0, *) | ||
| @usableFromInline | ||
| struct MaximumBackoffStrategy<Base: BackoffStrategy>: BackoffStrategy { | ||
| @usableFromInline var base: Base | ||
| @usableFromInline let maximum: Base.Duration | ||
| @usableFromInline init(base: Base, maximum: Base.Duration) { | ||
| self.base = base | ||
| self.maximum = maximum | ||
| } | ||
| @inlinable mutating func duration(_ attempt: Int) -> Base.Duration { | ||
| return min(maximum, base.duration(attempt)) | ||
| } | ||
| @inlinable mutating func duration(_ attempt: Int, using generator: inout some RandomNumberGenerator) -> Base.Duration { | ||
| return min(maximum, base.duration(attempt, using: &generator)) | ||
| } | ||
| } | ||
|  | ||
| @available(iOS 18.0, macCatalyst 18.0, macOS 15.0, tvOS 18.0, visionOS 2.0, watchOS 11.0, *) | ||
| @usableFromInline | ||
| struct FullJitterBackoffStrategy<Base: BackoffStrategy>: BackoffStrategy where Base.Duration == Swift.Duration { | ||
| @usableFromInline var base: Base | ||
| @usableFromInline init(base: Base) { | ||
| self.base = base | ||
| } | ||
| @inlinable mutating func duration(_ attempt: Int) -> Base.Duration { | ||
| return .init(attoseconds: Int128.random(in: 0...base.duration(attempt).attoseconds)) | ||
| } | ||
| @inlinable mutating func duration(_ attempt: Int, using generator: inout some RandomNumberGenerator) -> Base.Duration { | ||
| return .init(attoseconds: Int128.random(in: 0...base.duration(attempt, using: &generator).attoseconds, using: &generator)) | ||
| } | ||
| } | ||
|  | ||
| @available(iOS 18.0, macCatalyst 18.0, macOS 15.0, tvOS 18.0, visionOS 2.0, watchOS 11.0, *) | ||
| @usableFromInline | ||
| struct EqualJitterBackoffStrategy<Base: BackoffStrategy>: BackoffStrategy where Base.Duration == Swift.Duration { | ||
| @usableFromInline var base: Base | ||
| @usableFromInline init(base: Base) { | ||
| self.base = base | ||
| } | ||
| @inlinable mutating func duration(_ attempt: Int) -> Base.Duration { | ||
| let halfBase = (base.duration(attempt) / 2).attoseconds | ||
| return .init(attoseconds: halfBase + Int128.random(in: 0...halfBase)) | ||
| } | ||
| @inlinable mutating func duration(_ attempt: Int, using generator: inout some RandomNumberGenerator) -> Base.Duration { | ||
| let halfBase = (base.duration(attempt, using: &generator) / 2).attoseconds | ||
| return .init(attoseconds: halfBase + Int128.random(in: 0...halfBase, using: &generator)) | ||
| } | ||
| } | ||
|  | ||
| @available(iOS 18.0, macCatalyst 18.0, macOS 15.0, tvOS 18.0, visionOS 2.0, watchOS 11.0, *) | ||
| @usableFromInline | ||
| struct DecorrelatedJitterBackoffStrategy<Base: BackoffStrategy>: BackoffStrategy where Base.Duration == Swift.Duration { | ||
| @usableFromInline var base: Base | ||
| @usableFromInline let divisor: Int128 | ||
| @usableFromInline var previousDuration: Duration? | ||
| @usableFromInline init(base: Base, divisor: Int128) { | ||
| self.base = base | ||
| self.divisor = divisor | ||
| } | ||
| @inlinable mutating func duration(_ attempt: Int) -> Base.Duration { | ||
| let base = base.duration(attempt) | ||
| let previousDuration = previousDuration ?? base | ||
| self.previousDuration = previousDuration | ||
| return .init(attoseconds: Int128.random(in: base.attoseconds...previousDuration.attoseconds / divisor)) | ||
| } | ||
| @inlinable mutating func duration(_ attempt: Int, using generator: inout some RandomNumberGenerator) -> Base.Duration { | ||
| let base = base.duration(attempt, using: &generator) | ||
| let previousDuration = previousDuration ?? base | ||
| self.previousDuration = previousDuration | ||
| return .init(attoseconds: Int128.random(in: base.attoseconds...previousDuration.attoseconds / divisor, using: &generator)) | ||
| } | ||
| } | ||
|  | ||
| @available(iOS 16.0, macCatalyst 16.0, macOS 13.0, tvOS 16.0, visionOS 1.0, watchOS 9.0, *) | ||
| public enum Backoff { | ||
| @inlinable public static func constant<Duration: DurationProtocol>(_ c: Duration) -> some BackoffStrategy<Duration> { | ||
| return ConstantBackoffStrategy(c: c) | ||
| } | ||
| @inlinable public static func constant(_ c: Duration) -> some BackoffStrategy<Duration> { | ||
| return ConstantBackoffStrategy(c: c) | ||
| } | ||
| @inlinable public static func linear<Duration: DurationProtocol>(increment a: Duration, initial b: Duration) -> some BackoffStrategy<Duration> { | ||
| return LinearBackoffStrategy(a: a, b: b) | ||
| } | ||
| @inlinable public static func linear(increment a: Duration, initial b: Duration) -> some BackoffStrategy<Duration> { | ||
| return LinearBackoffStrategy(a: a, b: b) | ||
| } | ||
| @inlinable public static func exponential(multiplier b: Double = 2, initial a: Duration) -> some BackoffStrategy<Duration> { | ||
| return ExponentialBackoffStrategy(a: a, b: b) | ||
| } | ||
| } | ||
|  | ||
| @available(iOS 16.0, macCatalyst 16.0, macOS 13.0, tvOS 16.0, visionOS 1.0, watchOS 9.0, *) | ||
| extension BackoffStrategy { | ||
| @inlinable public func minimum(_ minimum: Duration) -> some BackoffStrategy<Duration> { | ||
| return MinimumBackoffStrategy(base: self, minimum: minimum) | ||
| } | ||
| @inlinable public func maximum(_ maximum: Duration) -> some BackoffStrategy<Duration> { | ||
| return MaximumBackoffStrategy(base: self, maximum: maximum) | ||
| } | ||
| } | ||
|  | ||
| @available(iOS 18.0, macCatalyst 18.0, macOS 15.0, tvOS 18.0, visionOS 2.0, watchOS 11.0, *) | ||
| extension BackoffStrategy where Duration == Swift.Duration { | ||
| @inlinable public func fullJitter() -> some BackoffStrategy<Duration> { | ||
| return FullJitterBackoffStrategy(base: self) | ||
| } | ||
| @inlinable public func equalJitter() -> some BackoffStrategy<Duration> { | ||
| return EqualJitterBackoffStrategy(base: self) | ||
| } | ||
| @inlinable public func decorrelatedJitter(divisor: Int = 3) -> some BackoffStrategy<Duration> { | ||
| return DecorrelatedJitterBackoffStrategy(base: self, divisor: Int128(divisor)) | ||
| } | ||
| } | ||
  
    
      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,51 @@ | ||
| @available(iOS 16.0, macCatalyst 16.0, macOS 13.0, tvOS 16.0, visionOS 1.0, watchOS 9.0, *) | ||
| public enum RetryStrategy<Duration: DurationProtocol> { | ||
|         
                  ph1ps marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| case backoff(Duration) | ||
| case stop | ||
| } | ||
|  | ||
| @available(iOS 16.0, macCatalyst 16.0, macOS 13.0, tvOS 16.0, visionOS 1.0, watchOS 9.0, *) | ||
| @inlinable | ||
| public func retry<Result, ErrorType, ClockType>( | ||
| maxAttempts: Int = 3, | ||
|         
                  ph1ps marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| tolerance: ClockType.Instant.Duration? = nil, | ||
| clock: ClockType, | ||
| isolation: isolated (any Actor)? = #isolation, | ||
| operation: () async throws(ErrorType) -> sending Result, | ||
|         
                  ph1ps marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| strategy: (_ attempt: Int, ErrorType) -> RetryStrategy<ClockType.Instant.Duration> = { _, _ in .backoff(.zero) } | ||
| ) async throws -> Result where ClockType: Clock, ErrorType: Error { | ||
| precondition(maxAttempts > 0, "Must have at least one attempt") | ||
| for attempt in 0..<maxAttempts - 1 { | ||
| do { | ||
| return try await operation() | ||
| } catch where Task.isCancelled { | ||
|         
                  ph1ps marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| throw error | ||
| } catch { | ||
| switch strategy(attempt, error) { | ||
| case .backoff(let duration): | ||
| try await Task.sleep(for: duration, tolerance: tolerance, clock: clock) | ||
| case .stop: | ||
| throw error | ||
| } | ||
| } | ||
| } | ||
| return try await operation() | ||
| } | ||
|  | ||
| @available(iOS 16.0, macCatalyst 16.0, macOS 13.0, tvOS 16.0, visionOS 1.0, watchOS 9.0, *) | ||
| @inlinable | ||
| public func retry<Result, ErrorType>( | ||
| maxAttempts: Int = 3, | ||
| tolerance: ContinuousClock.Instant.Duration? = nil, | ||
| isolation: isolated (any Actor)? = #isolation, | ||
| operation: () async throws(ErrorType) -> sending Result, | ||
| strategy: (_ attempt: Int, ErrorType) -> RetryStrategy<ContinuousClock.Instant.Duration> = { _, _ in .backoff(.zero) } | ||
| ) async throws -> Result where ErrorType: Error { | ||
| return try await retry( | ||
| maxAttempts: maxAttempts, | ||
| tolerance: tolerance, | ||
| clock: ContinuousClock(), | ||
| operation: operation, | ||
| strategy: strategy | ||
| ) | ||
| } | ||
  
    
      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 @@ | ||
| #include "_CPowSupport.h" | 
  
    
      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,3 @@ | ||
| static inline __attribute__((__always_inline__)) double pow(double x, double y) { | ||
|         
                  ph1ps marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| return __builtin_pow(x, y); | ||
| } | ||
  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.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.