|
| 1 | +import Foundation |
| 2 | + |
| 3 | +/// A utility that performs automatic retries of a task that can fail with a exponential backoff delay between each retry attempt |
| 4 | +public enum DelayedRetry { |
| 5 | + private enum Constants { |
| 6 | + static let retryDelayForOneRetryRemaining: TimeInterval = 4.0 |
| 7 | + } |
| 8 | + |
| 9 | + /// What attempt number is this? Useful so if == 1 you know this is the first attempt and not actually a retry |
| 10 | + public typealias AttemptNumber = Int |
| 11 | + public typealias TaskResult = (_ success: Bool) -> Void |
| 12 | + public typealias Task = (AttemptNumber, @escaping TaskResult) -> Void |
| 13 | + public typealias RetryAttemptsFailed = (() -> Void) |
| 14 | + |
| 15 | + /// Overload for testing where we can setup a faster delay so tests don't take 5+ seconds for this one test. |
| 16 | + static func performTask(on queue: DispatchQueue, attemptNumber: AttemptNumber, numberOfRetries: Int, delayCalculator: @escaping (Int) -> TimeInterval, |
| 17 | + finishedAllRetryAttempts: RetryAttemptsFailed?, task: @escaping Task) { |
| 18 | + queue.async { |
| 19 | + task(attemptNumber, { (success) in |
| 20 | + guard !success else { |
| 21 | + return |
| 22 | + } |
| 23 | + if numberOfRetries > 0 { |
| 24 | + let delay = delayCalculator(numberOfRetries) |
| 25 | + queue.asyncAfter(deadline: .now() + delay, execute: { |
| 26 | + performTask(on: queue, attemptNumber: attemptNumber + 1, numberOfRetries: numberOfRetries - 1, delayCalculator: delayCalculator, |
| 27 | + finishedAllRetryAttempts: finishedAllRetryAttempts, task: task) |
| 28 | + }) |
| 29 | + } else if let finishedAllRetryAttempts = finishedAllRetryAttempts { |
| 30 | + queue.async(execute: finishedAllRetryAttempts) |
| 31 | + } |
| 32 | + }) |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + /// Perform a task on a queue. If that task fails, this will retry running that task with an exponential growing delay before each retry |
| 37 | + /// attempt. |
| 38 | + /// |
| 39 | + /// - Parameters: |
| 40 | + /// - queue: The queue that the `task` will be run on asynchronously |
| 41 | + /// - numberOfRetries: How many times will this `task` be rerun if you say it has failed |
| 42 | + /// - finishedAllRetryAttempts: Will be called on the `queue` only if we have retried the task `numberOfRetries` and all attempts have failed. |
| 43 | + /// - task: The task that is to be performed. Once you are finished your work inside the task, call the `TaskResult` parameter with a `true` if it |
| 44 | + /// was completed successfully (no retry needed), or `false` if the task should be retried. It is up to the caller to ensure that running the |
| 45 | + /// `task` multiple times won't cause issues. This closure is not retained beyond the minimum required to run/retry the task. |
| 46 | + public static func performTask(on queue: DispatchQueue, numberOfRetries: Int, finishedAllRetryAttempts: RetryAttemptsFailed?, task: @escaping Task) { |
| 47 | + performTask(on: queue, attemptNumber: 1, numberOfRetries: numberOfRetries, delayCalculator: delay(forNumberOfRemainingRetries:), |
| 48 | + finishedAllRetryAttempts: finishedAllRetryAttempts, task: task) |
| 49 | + } |
| 50 | + |
| 51 | + /// Compute the delay for the next retry based on the number of retries remaining. |
| 52 | + /// |
| 53 | + /// - Parameter retriesRemaining: The number of retires remaining before we stop retrying |
| 54 | + /// - Returns: How long to delay before starting the next retry. The delay is the longest if this is the last retry attempt, and is cut in half for each |
| 55 | + /// additional retry remaining. So 1 retry remain = 4 second delay, 2 retry remain = 2 second delay, 3 retry = 1 second delay and so on. |
| 56 | + static func delay(forNumberOfRemainingRetries retriesRemaining: Int) -> TimeInterval { |
| 57 | + if retriesRemaining <= 1 { |
| 58 | + return Constants.retryDelayForOneRetryRemaining |
| 59 | + } else { |
| 60 | + return delay(forNumberOfRemainingRetries: retriesRemaining - 1) / 2 |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments