RequestInterceptor.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. //
  2. // RequestInterceptor.swift
  3. //
  4. // Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary.
  26. public protocol RequestAdapter {
  27. /// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result.
  28. ///
  29. /// - Parameters:
  30. /// - urlRequest: The `URLRequest` to adapt.
  31. /// - session: The `Session` that will execute the `URLRequest`.
  32. /// - completion: The completion handler that must be called when adaptation is complete.
  33. func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void)
  34. }
  35. // MARK: -
  36. /// Outcome of determination whether retry is necessary.
  37. public enum RetryResult {
  38. /// Retry should be attempted immediately.
  39. case retry
  40. /// Retry should be attempted after the associated `TimeInterval`.
  41. case retryWithDelay(TimeInterval)
  42. /// Do not retry.
  43. case doNotRetry
  44. /// Do not retry due to the associated `Error`.
  45. case doNotRetryWithError(Error)
  46. }
  47. extension RetryResult {
  48. var retryRequired: Bool {
  49. switch self {
  50. case .retry, .retryWithDelay: return true
  51. default: return false
  52. }
  53. }
  54. var delay: TimeInterval? {
  55. switch self {
  56. case let .retryWithDelay(delay): return delay
  57. default: return nil
  58. }
  59. }
  60. var error: Error? {
  61. guard case let .doNotRetryWithError(error) = self else { return nil }
  62. return error
  63. }
  64. }
  65. /// A type that determines whether a request should be retried after being executed by the specified session manager
  66. /// and encountering an error.
  67. public protocol RequestRetrier {
  68. /// Determines whether the `Request` should be retried by calling the `completion` closure.
  69. ///
  70. /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs
  71. /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly
  72. /// cleaned up after.
  73. ///
  74. /// - Parameters:
  75. /// - request: `Request` that failed due to the provided `Error`.
  76. /// - session: `Session` that produced the `Request`.
  77. /// - error: `Error` encountered while executing the `Request`.
  78. /// - completion: Completion closure to be executed when a retry decision has been determined.
  79. func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void)
  80. }
  81. // MARK: -
  82. /// Type that provides both `RequestAdapter` and `RequestRetrier` functionality.
  83. public protocol RequestInterceptor: RequestAdapter, RequestRetrier {}
  84. extension RequestInterceptor {
  85. public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
  86. completion(.success(urlRequest))
  87. }
  88. public func retry(_ request: Request,
  89. for session: Session,
  90. dueTo error: Error,
  91. completion: @escaping (RetryResult) -> Void) {
  92. completion(.doNotRetry)
  93. }
  94. }
  95. /// `RequestAdapter` closure definition.
  96. public typealias AdaptHandler = (URLRequest, Session, _ completion: @escaping (Result<URLRequest, Error>) -> Void) -> Void
  97. /// `RequestRetrier` closure definition.
  98. public typealias RetryHandler = (Request, Session, Error, _ completion: @escaping (RetryResult) -> Void) -> Void
  99. // MARK: -
  100. /// Closure-based `RequestAdapter`.
  101. open class Adapter: RequestInterceptor {
  102. private let adaptHandler: AdaptHandler
  103. /// Creates an instance using the provided closure.
  104. ///
  105. /// - Parameter adaptHandler: `AdaptHandler` closure to be executed when handling request adaptation.
  106. public init(_ adaptHandler: @escaping AdaptHandler) {
  107. self.adaptHandler = adaptHandler
  108. }
  109. open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
  110. adaptHandler(urlRequest, session, completion)
  111. }
  112. }
  113. #if swift(>=5.5)
  114. extension RequestAdapter where Self == Adapter {
  115. /// Creates an `Adapter` using the provided `AdaptHandler` closure.
  116. ///
  117. /// - Parameter closure: `AdaptHandler` to use to adapt the request.
  118. /// - Returns: The `Adapter`.
  119. public static func adapter(using closure: @escaping AdaptHandler) -> Adapter {
  120. Adapter(closure)
  121. }
  122. }
  123. #endif
  124. // MARK: -
  125. /// Closure-based `RequestRetrier`.
  126. open class Retrier: RequestInterceptor {
  127. private let retryHandler: RetryHandler
  128. /// Creates an instance using the provided closure.
  129. ///
  130. /// - Parameter retryHandler: `RetryHandler` closure to be executed when handling request retry.
  131. public init(_ retryHandler: @escaping RetryHandler) {
  132. self.retryHandler = retryHandler
  133. }
  134. open func retry(_ request: Request,
  135. for session: Session,
  136. dueTo error: Error,
  137. completion: @escaping (RetryResult) -> Void) {
  138. retryHandler(request, session, error, completion)
  139. }
  140. }
  141. #if swift(>=5.5)
  142. extension RequestRetrier where Self == Retrier {
  143. /// Creates a `Retrier` using the provided `RetryHandler` closure.
  144. ///
  145. /// - Parameter closure: `RetryHandler` to use to retry the request.
  146. /// - Returns: The `Retrier`.
  147. public static func retrier(using closure: @escaping RetryHandler) -> Retrier {
  148. Retrier(closure)
  149. }
  150. }
  151. #endif
  152. // MARK: -
  153. /// `RequestInterceptor` which can use multiple `RequestAdapter` and `RequestRetrier` values.
  154. open class Interceptor: RequestInterceptor {
  155. /// All `RequestAdapter`s associated with the instance. These adapters will be run until one fails.
  156. public let adapters: [RequestAdapter]
  157. /// All `RequestRetrier`s associated with the instance. These retriers will be run one at a time until one triggers retry.
  158. public let retriers: [RequestRetrier]
  159. /// Creates an instance from `AdaptHandler` and `RetryHandler` closures.
  160. ///
  161. /// - Parameters:
  162. /// - adaptHandler: `AdaptHandler` closure to be used.
  163. /// - retryHandler: `RetryHandler` closure to be used.
  164. public init(adaptHandler: @escaping AdaptHandler, retryHandler: @escaping RetryHandler) {
  165. adapters = [Adapter(adaptHandler)]
  166. retriers = [Retrier(retryHandler)]
  167. }
  168. /// Creates an instance from `RequestAdapter` and `RequestRetrier` values.
  169. ///
  170. /// - Parameters:
  171. /// - adapter: `RequestAdapter` value to be used.
  172. /// - retrier: `RequestRetrier` value to be used.
  173. public init(adapter: RequestAdapter, retrier: RequestRetrier) {
  174. adapters = [adapter]
  175. retriers = [retrier]
  176. }
  177. /// Creates an instance from the arrays of `RequestAdapter` and `RequestRetrier` values.
  178. ///
  179. /// - Parameters:
  180. /// - adapters: `RequestAdapter` values to be used.
  181. /// - retriers: `RequestRetrier` values to be used.
  182. /// - interceptors: `RequestInterceptor`s to be used.
  183. public init(adapters: [RequestAdapter] = [], retriers: [RequestRetrier] = [], interceptors: [RequestInterceptor] = []) {
  184. self.adapters = adapters + interceptors
  185. self.retriers = retriers + interceptors
  186. }
  187. open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
  188. adapt(urlRequest, for: session, using: adapters, completion: completion)
  189. }
  190. private func adapt(_ urlRequest: URLRequest,
  191. for session: Session,
  192. using adapters: [RequestAdapter],
  193. completion: @escaping (Result<URLRequest, Error>) -> Void) {
  194. var pendingAdapters = adapters
  195. guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return }
  196. let adapter = pendingAdapters.removeFirst()
  197. adapter.adapt(urlRequest, for: session) { result in
  198. switch result {
  199. case let .success(urlRequest):
  200. self.adapt(urlRequest, for: session, using: pendingAdapters, completion: completion)
  201. case .failure:
  202. completion(result)
  203. }
  204. }
  205. }
  206. open func retry(_ request: Request,
  207. for session: Session,
  208. dueTo error: Error,
  209. completion: @escaping (RetryResult) -> Void) {
  210. retry(request, for: session, dueTo: error, using: retriers, completion: completion)
  211. }
  212. private func retry(_ request: Request,
  213. for session: Session,
  214. dueTo error: Error,
  215. using retriers: [RequestRetrier],
  216. completion: @escaping (RetryResult) -> Void) {
  217. var pendingRetriers = retriers
  218. guard !pendingRetriers.isEmpty else { completion(.doNotRetry); return }
  219. let retrier = pendingRetriers.removeFirst()
  220. retrier.retry(request, for: session, dueTo: error) { result in
  221. switch result {
  222. case .retry, .retryWithDelay, .doNotRetryWithError:
  223. completion(result)
  224. case .doNotRetry:
  225. // Only continue to the next retrier if retry was not triggered and no error was encountered
  226. self.retry(request, for: session, dueTo: error, using: pendingRetriers, completion: completion)
  227. }
  228. }
  229. }
  230. }
  231. #if swift(>=5.5)
  232. extension RequestInterceptor where Self == Interceptor {
  233. /// Creates an `Interceptor` using the provided `AdaptHandler` and `RetryHandler` closures.
  234. ///
  235. /// - Parameters:
  236. /// - adapter: `AdapterHandler`to use to adapt the request.
  237. /// - retrier: `RetryHandler` to use to retry the request.
  238. /// - Returns: The `Interceptor`.
  239. public static func interceptor(adapter: @escaping AdaptHandler, retrier: @escaping RetryHandler) -> Interceptor {
  240. Interceptor(adaptHandler: adapter, retryHandler: retrier)
  241. }
  242. /// Creates an `Interceptor` using the provided `RequestAdapter` and `RequestRetrier` instances.
  243. /// - Parameters:
  244. /// - adapter: `RequestAdapter` to use to adapt the request
  245. /// - retrier: `RequestRetrier` to use to retry the request.
  246. /// - Returns: The `Interceptor`.
  247. public static func interceptor(adapter: RequestAdapter, retrier: RequestRetrier) -> Interceptor {
  248. Interceptor(adapter: adapter, retrier: retrier)
  249. }
  250. /// Creates an `Interceptor` using the provided `RequestAdapter`s, `RequestRetrier`s, and `RequestInterceptor`s.
  251. /// - Parameters:
  252. /// - adapters: `RequestAdapter`s to use to adapt the request. These adapters will be run until one fails.
  253. /// - retriers: `RequestRetrier`s to use to retry the request. These retriers will be run one at a time until
  254. /// a retry is triggered.
  255. /// - interceptors: `RequestInterceptor`s to use to intercept the request.
  256. /// - Returns: The `Interceptor`.
  257. public static func interceptor(adapters: [RequestAdapter] = [],
  258. retriers: [RequestRetrier] = [],
  259. interceptors: [RequestInterceptor] = []) -> Interceptor {
  260. Interceptor(adapters: adapters, retriers: retriers, interceptors: interceptors)
  261. }
  262. }
  263. #endif