Skip to content

Commit

Permalink
Feat: add custom retry strategy implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Niccolò Fontana committed Mar 19, 2023
1 parent c0ffb26 commit eef7478
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 0 deletions.
1 change: 1 addition & 0 deletions Documentation/3.Advanced_HTTPClient.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ The options are:
- `exponential` and `fibonacci` are the same as `delayed`, but with sequentially increasing delay times
- `after(HTTPRequest, TimeInterval, AltRequestCatcher?)` will retry the original call after calling an alternate request. For example, if you are making an authenticated request and the session has expired; you can then call a login alternate request to perform a new login and retry the original call.
- `afterTask(TimeInterval, RetryTask, RetryTaskErrorCatcher?)` performs an async task before retrying the original request. By using an async `Task`, you may perform work outside of the scope of RealHTTP and inject whatever you need into the original request. Note that, like with the existing retry with `HTTPRequest` strategy, any error triggered by the async `Task` is not propagated to the original request. However, a callback could be provided to at least "see" it.
- `custom` will retry the original call after the amount of seconds returned by the closure you are required to provide for this case. The closure provides you with the failed `HTTPRequest` object so you have the chance to define any custom logic based on it and return the desired amount of seconds.

We'll take a closer look at these strategies below.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,15 @@ public enum HTTPRetryStrategy {
public typealias AltRequestCatcher = ((_ request: HTTPRequest, _ response: HTTPResponse) async throws -> Void)
public typealias RetryTask = ((_ originalRequest: HTTPRequest) async throws -> Void)
public typealias RetryTaskErrorCatcher = ((_ error: Error) async -> Void)
public typealias CustomRetryIntervalProvider = (_ request: HTTPRequest) -> TimeInterval

case immediate
case delayed(_ interval: TimeInterval)
case exponential(_ base: Int)
case fibonacci
case after(HTTPRequest, TimeInterval, AltRequestCatcher?)
case afterTask(TimeInterval, RetryTask, RetryTaskErrorCatcher?)
case custom(_ retryIntervalProvider: CustomRetryIntervalProvider)

// MARK: - Internal Functions

Expand Down Expand Up @@ -108,6 +110,9 @@ public enum HTTPRetryStrategy {

case .afterTask:
return 0

case .custom(let retryIntervalProvider):
return retryIntervalProvider(request)
}
}

Expand Down

0 comments on commit eef7478

Please sign in to comment.