RequestInterceptor.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. /// Stores all state associated with a `URLRequest` being adapted.
  26. public struct RequestAdapterState {
  27. /// The `UUID` of the `Request` associated with the `URLRequest` to adapt.
  28. public let requestID: UUID
  29. /// The `Session` associated with the `URLRequest` to adapt.
  30. public let session: Session
  31. }
  32. // MARK: -
  33. /// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary.
  34. public protocol RequestAdapter {
  35. /// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result.
  36. ///
  37. /// - Parameters:
  38. /// - urlRequest: The `URLRequest` to adapt.
  39. /// - session: The `Session` that will execute the `URLRequest`.
  40. /// - completion: The completion handler that must be called when adaptation is complete.
  41. func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void)
  42. /// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result.
  43. ///
  44. /// - Parameters:
  45. /// - urlRequest: The `URLRequest` to adapt.
  46. /// - state: The `RequestAdapterState` associated with the `URLRequest`.
  47. /// - completion: The completion handler that must be called when adaptation is complete.
  48. func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result<URLRequest, Error>) -> Void)
  49. }
  50. extension RequestAdapter {
  51. public func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result<URLRequest, Error>) -> Void) {
  52. adapt(urlRequest, for: state.session, completion: completion)
  53. }
  54. }
  55. // MARK: -
  56. /// Outcome of determination whether retry is necessary.
  57. public enum RetryResult {
  58. /// Retry should be attempted immediately.
  59. case retry
  60. /// Retry should be attempted after the associated `TimeInterval`.
  61. case retryWithDelay(TimeInterval)
  62. /// Do not retry.
  63. case doNotRetry
  64. /// Do not retry due to the associated `Error`.
  65. case doNotRetryWithError(Error)
  66. }
  67. extension RetryResult {
  68. var retryRequired: Bool {
  69. switch self {
  70. case .retry, .retryWithDelay: return true
  71. default: return false
  72. }
  73. }
  74. var delay: TimeInterval? {
  75. switch self {
  76. case let .retryWithDelay(delay): return delay
  77. default: return nil
  78. }
  79. }
  80. var error: Error? {
  81. guard case let .doNotRetryWithError(error) = self else { return nil }
  82. return error
  83. }
  84. }
  85. /// A type that determines whether a request should be retried after being executed by the specified session manager
  86. /// and encountering an error.
  87. public protocol RequestRetrier {
  88. /// Determines whether the `Request` should be retried by calling the `completion` closure.
  89. ///
  90. /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs
  91. /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly
  92. /// cleaned up after.
  93. ///
  94. /// - Parameters:
  95. /// - request: `Request` that failed due to the provided `Error`.
  96. /// - session: `Session` that produced the `Request`.
  97. /// - error: `Error` encountered while executing the `Request`.
  98. /// - completion: Completion closure to be executed when a retry decision has been determined.
  99. func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void)
  100. }
  101. // MARK: -
  102. /// Type that provides both `RequestAdapter` and `RequestRetrier` functionality.
  103. public protocol RequestInterceptor: RequestAdapter, RequestRetrier {}
  104. extension RequestInterceptor {
  105. public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
  106. completion(.success(urlRequest))
  107. }
  108. public func retry(_ request: Request,
  109. for session: Session,
  110. dueTo error: Error,
  111. completion: @escaping (RetryResult) -> Void) {
  112. completion(.doNotRetry)
  113. }
  114. }
  115. /// `RequestAdapter` closure definition.
  116. public typealias AdaptHandler = (URLRequest, Session, _ completion: @escaping (Result<URLRequest, Error>) -> Void) -> Void
  117. /// `RequestRetrier` closure definition.
  118. public typealias RetryHandler = (Request, Session, Error, _ completion: @escaping (RetryResult) -> Void) -> Void
  119. // MARK: -
  120. /// Closure-based `RequestAdapter`.
  121. open class Adapter: RequestInterceptor {
  122. private let adaptHandler: AdaptHandler
  123. /// Creates an instance using the provided closure.
  124. ///
  125. /// - Parameter adaptHandler: `AdaptHandler` closure to be executed when handling request adaptation.
  126. public init(_ adaptHandler: @escaping AdaptHandler) {
  127. self.adaptHandler = adaptHandler
  128. }
  129. open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
  130. adaptHandler(urlRequest, session, completion)
  131. }
  132. open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result<URLRequest, Error>) -> Void) {
  133. adaptHandler(urlRequest, state.session, completion)
  134. }
  135. }
  136. extension RequestAdapter where Self == Adapter {
  137. /// Creates an `Adapter` using the provided `AdaptHandler` closure.
  138. ///
  139. /// - Parameter closure: `AdaptHandler` to use to adapt the request.
  140. /// - Returns: The `Adapter`.
  141. public static func adapter(using closure: @escaping AdaptHandler) -> Adapter {
  142. Adapter(closure)
  143. }
  144. }
  145. // MARK: -
  146. /// Closure-based `RequestRetrier`.
  147. open class Retrier: RequestInterceptor {
  148. private let retryHandler: RetryHandler
  149. /// Creates an instance using the provided closure.
  150. ///
  151. /// - Parameter retryHandler: `RetryHandler` closure to be executed when handling request retry.
  152. public init(_ retryHandler: @escaping RetryHandler) {
  153. self.retryHandler = retryHandler
  154. }
  155. open func retry(_ request: Request,
  156. for session: Session,
  157. dueTo error: Error,
  158. completion: @escaping (RetryResult) -> Void) {
  159. retryHandler(request, session, error, completion)
  160. }
  161. }
  162. extension RequestRetrier where Self == Retrier {
  163. /// Creates a `Retrier` using the provided `RetryHandler` closure.
  164. ///
  165. /// - Parameter closure: `RetryHandler` to use to retry the request.
  166. /// - Returns: The `Retrier`.
  167. public static func retrier(using closure: @escaping RetryHandler) -> Retrier {
  168. Retrier(closure)
  169. }
  170. }
  171. // MARK: -
  172. /// `RequestInterceptor` which can use multiple `RequestAdapter` and `RequestRetrier` values.
  173. open class Interceptor: RequestInterceptor {
  174. /// All `RequestAdapter`s associated with the instance. These adapters will be run until one fails.
  175. public let adapters: [RequestAdapter]
  176. /// All `RequestRetrier`s associated with the instance. These retriers will be run one at a time until one triggers retry.
  177. public let retriers: [RequestRetrier]
  178. /// Creates an instance from `AdaptHandler` and `RetryHandler` closures.
  179. ///
  180. /// - Parameters:
  181. /// - adaptHandler: `AdaptHandler` closure to be used.
  182. /// - retryHandler: `RetryHandler` closure to be used.
  183. public init(adaptHandler: @escaping AdaptHandler, retryHandler: @escaping RetryHandler) {
  184. adapters = [Adapter(adaptHandler)]
  185. retriers = [Retrier(retryHandler)]
  186. }
  187. /// Creates an instance from `RequestAdapter` and `RequestRetrier` values.
  188. ///
  189. /// - Parameters:
  190. /// - adapter: `RequestAdapter` value to be used.
  191. /// - retrier: `RequestRetrier` value to be used.
  192. public init(adapter: RequestAdapter, retrier: RequestRetrier) {
  193. adapters = [adapter]
  194. retriers = [retrier]
  195. }
  196. /// Creates an instance from the arrays of `RequestAdapter` and `RequestRetrier` values.
  197. ///
  198. /// - Parameters:
  199. /// - adapters: `RequestAdapter` values to be used.
  200. /// - retriers: `RequestRetrier` values to be used.
  201. /// - interceptors: `RequestInterceptor`s to be used.
  202. public init(adapters: [RequestAdapter] = [], retriers: [RequestRetrier] = [], interceptors: [RequestInterceptor] = []) {
  203. self.adapters = adapters + interceptors
  204. self.retriers = retriers + interceptors
  205. }
  206. open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
  207. adapt(urlRequest, for: session, using: adapters, completion: completion)
  208. }
  209. private func adapt(_ urlRequest: URLRequest,
  210. for session: Session,
  211. using adapters: [RequestAdapter],
  212. completion: @escaping (Result<URLRequest, Error>) -> Void) {
  213. var pendingAdapters = adapters
  214. guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return }
  215. let adapter = pendingAdapters.removeFirst()
  216. adapter.adapt(urlRequest, for: session) { result in
  217. switch result {
  218. case let .success(urlRequest):
  219. self.adapt(urlRequest, for: session, using: pendingAdapters, completion: completion)
  220. case .failure:
  221. completion(result)
  222. }
  223. }
  224. }
  225. open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result<URLRequest, Error>) -> Void) {
  226. adapt(urlRequest, using: state, adapters: adapters, completion: completion)
  227. }
  228. private func adapt(_ urlRequest: URLRequest,
  229. using state: RequestAdapterState,
  230. adapters: [RequestAdapter],
  231. completion: @escaping (Result<URLRequest, Error>) -> Void) {
  232. var pendingAdapters = adapters
  233. guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return }
  234. let adapter = pendingAdapters.removeFirst()
  235. adapter.adapt(urlRequest, using: state) { result in
  236. switch result {
  237. case let .success(urlRequest):
  238. self.adapt(urlRequest, using: state, adapters: pendingAdapters, completion: completion)
  239. case .failure:
  240. completion(result)
  241. }
  242. }
  243. }
  244. open func retry(_ request: Request,
  245. for session: Session,
  246. dueTo error: Error,
  247. completion: @escaping (RetryResult) -> Void) {
  248. retry(request, for: session, dueTo: error, using: retriers, completion: completion)
  249. }
  250. private func retry(_ request: Request,
  251. for session: Session,
  252. dueTo error: Error,
  253. using retriers: [RequestRetrier],
  254. completion: @escaping (RetryResult) -> Void) {
  255. var pendingRetriers = retriers
  256. guard !pendingRetriers.isEmpty else { completion(.doNotRetry); return }
  257. let retrier = pendingRetriers.removeFirst()
  258. retrier.retry(request, for: session, dueTo: error) { result in
  259. switch result {
  260. case .retry, .retryWithDelay, .doNotRetryWithError:
  261. completion(result)
  262. case .doNotRetry:
  263. // Only continue to the next retrier if retry was not triggered and no error was encountered
  264. self.retry(request, for: session, dueTo: error, using: pendingRetriers, completion: completion)
  265. }
  266. }
  267. }
  268. }
  269. extension RequestInterceptor where Self == Interceptor {
  270. /// Creates an `Interceptor` using the provided `AdaptHandler` and `RetryHandler` closures.
  271. ///
  272. /// - Parameters:
  273. /// - adapter: `AdapterHandler`to use to adapt the request.
  274. /// - retrier: `RetryHandler` to use to retry the request.
  275. /// - Returns: The `Interceptor`.
  276. public static func interceptor(adapter: @escaping AdaptHandler, retrier: @escaping RetryHandler) -> Interceptor {
  277. Interceptor(adaptHandler: adapter, retryHandler: retrier)
  278. }
  279. /// Creates an `Interceptor` using the provided `RequestAdapter` and `RequestRetrier` instances.
  280. /// - Parameters:
  281. /// - adapter: `RequestAdapter` to use to adapt the request
  282. /// - retrier: `RequestRetrier` to use to retry the request.
  283. /// - Returns: The `Interceptor`.
  284. public static func interceptor(adapter: RequestAdapter, retrier: RequestRetrier) -> Interceptor {
  285. Interceptor(adapter: adapter, retrier: retrier)
  286. }
  287. /// Creates an `Interceptor` using the provided `RequestAdapter`s, `RequestRetrier`s, and `RequestInterceptor`s.
  288. /// - Parameters:
  289. /// - adapters: `RequestAdapter`s to use to adapt the request. These adapters will be run until one fails.
  290. /// - retriers: `RequestRetrier`s to use to retry the request. These retriers will be run one at a time until
  291. /// a retry is triggered.
  292. /// - interceptors: `RequestInterceptor`s to use to intercept the request.
  293. /// - Returns: The `Interceptor`.
  294. public static func interceptor(adapters: [RequestAdapter] = [],
  295. retriers: [RequestRetrier] = [],
  296. interceptors: [RequestInterceptor] = []) -> Interceptor {
  297. Interceptor(adapters: adapters, retriers: retriers, interceptors: interceptors)
  298. }
  299. }