-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
40b7efe
commit 8d46e7e
Showing
2 changed files
with
94 additions
and
7 deletions.
There are no files selected for viewing
This file contains 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 |
---|---|---|
@@ -1,2 +1,38 @@ | ||
// The Swift Programming Language | ||
// https://docs.swift.org/swift-book | ||
import Foundation | ||
|
||
|
||
enum Retry { | ||
public enum Error: Swift.Error, Equatable { | ||
case retryLimitExceeded(lastError: String?) | ||
} | ||
|
||
public static func backedOffDelay(baseDelay: Double, attempt: Int) -> UInt32 { | ||
(pow(2, max(0, attempt - 1)) * Decimal(baseDelay) as NSDecimalNumber).uint32Value | ||
} | ||
|
||
public static func attempt<T>(_ label: String, | ||
delay: Double = 5, | ||
retries: Int = 5, | ||
_ block: () throws -> T) throws -> T { | ||
var retriesLeft = retries | ||
var currentTry = 1 | ||
var lastError: String? | ||
while true { | ||
if currentTry > 1 { | ||
print("\(label) (attempt \(currentTry))") | ||
} | ||
do { | ||
return try block() | ||
} catch { | ||
lastError = "\(error)" | ||
guard retriesLeft > 0 else { break } | ||
let delay = backedOffDelay(baseDelay: delay, attempt: currentTry) | ||
print("Retrying in \(delay) seconds ...") | ||
sleep(delay) | ||
currentTry += 1 | ||
retriesLeft -= 1 | ||
} | ||
} | ||
throw Error.retryLimitExceeded(lastError: lastError) | ||
} | ||
} |
This file contains 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