RequestInterceptor.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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: Sendable {
  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: Sendable {
  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: @Sendable @escaping (_ result: Result<URLRequest, any 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: @Sendable @escaping (_ result: Result<URLRequest, any Error>) -> Void)
  49. }
  50. extension RequestAdapter {
  51. public func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @Sendable @escaping (_ result: Result<URLRequest, any 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: Sendable {
  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(any Error)
  66. }
  67. extension RetryResult {
  68. var retryRequired: Bool {
  69. switch self {
  70. case .retry, .retryWithDelay: true
  71. default: false
  72. }
  73. }
  74. var delay: TimeInterval? {
  75. switch self {
  76. case let .retryWithDelay(delay): delay
  77. default: nil
  78. }
  79. }
  80. var error: (any 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: Sendable {
  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: any Error, completion: @Sendable @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. @preconcurrency
  106. public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @Sendable @escaping (Result<URLRequest, any Error>) -> Void) {
  107. completion(.success(urlRequest))
  108. }
  109. @preconcurrency
  110. public func retry(_ request: Request,
  111. for session: Session,
  112. dueTo error: any Error,
  113. completion: @Sendable @escaping (RetryResult) -> Void) {
  114. completion(.doNotRetry)
  115. }
  116. }
  117. /// `RequestAdapter` closure definition.
  118. public typealias AdaptHandler = @Sendable (_ request: URLRequest,
  119. _ session: Session,
  120. _ completion: @escaping (Result<URLRequest, any Error>) -> Void) -> Void
  121. /// `RequestRetrier` closure definition.
  122. public typealias RetryHandler = @Sendable (_ request: Request,
  123. _ session: Session,
  124. _ error: any Error,
  125. _ completion: @escaping (RetryResult) -> Void) -> Void
  126. // MARK: -
  127. /// Closure-based `RequestAdapter`.
  128. open class Adapter: @unchecked Sendable, RequestInterceptor {
  129. private let adaptHandler: AdaptHandler
  130. /// Creates an instance using the provided closure.
  131. ///
  132. /// - Parameter adaptHandler: `AdaptHandler` closure to be executed when handling request adaptation.
  133. ///
  134. @preconcurrency
  135. public init(_ adaptHandler: @escaping AdaptHandler) {
  136. self.adaptHandler = adaptHandler
  137. }
  138. @preconcurrency
  139. open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, any Error>) -> Void) {
  140. adaptHandler(urlRequest, session, completion)
  141. }
  142. @preconcurrency
  143. open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @escaping (Result<URLRequest, any Error>) -> Void) {
  144. adaptHandler(urlRequest, state.session, completion)
  145. }
  146. }
  147. extension RequestAdapter where Self == Adapter {
  148. /// Creates an `Adapter` using the provided `AdaptHandler` closure.
  149. ///
  150. /// - Parameter closure: `AdaptHandler` to use to adapt the request.
  151. /// - Returns: The `Adapter`.
  152. public static func adapter(using closure: @escaping AdaptHandler) -> Adapter {
  153. Adapter(closure)
  154. }
  155. }
  156. // MARK: -
  157. /// Closure-based `RequestRetrier`.
  158. open class Retrier: @unchecked Sendable, RequestInterceptor {
  159. private let retryHandler: RetryHandler
  160. /// Creates an instance using the provided closure.
  161. ///
  162. /// - Parameter retryHandler: `RetryHandler` closure to be executed when handling request retry.
  163. @preconcurrency
  164. public init(_ retryHandler: @escaping RetryHandler) {
  165. self.retryHandler = retryHandler
  166. }
  167. open func retry(_ request: Request,
  168. for session: Session,
  169. dueTo error: any Error,
  170. completion: @escaping (RetryResult) -> Void) {
  171. retryHandler(request, session, error, completion)
  172. }
  173. }
  174. extension RequestRetrier where Self == Retrier {
  175. /// Creates a `Retrier` using the provided `RetryHandler` closure.
  176. ///
  177. /// - Parameter closure: `RetryHandler` to use to retry the request.
  178. /// - Returns: The `Retrier`.
  179. public static func retrier(using closure: @escaping RetryHandler) -> Retrier {
  180. Retrier(closure)
  181. }
  182. }
  183. // MARK: -
  184. /// `RequestInterceptor` which can use multiple `RequestAdapter` and `RequestRetrier` values.
  185. open class Interceptor: @unchecked Sendable, RequestInterceptor {
  186. /// All `RequestAdapter`s associated with the instance. These adapters will be run until one fails.
  187. public let adapters: [any RequestAdapter]
  188. /// All `RequestRetrier`s associated with the instance. These retriers will be run one at a time until one triggers retry.
  189. public let retriers: [any RequestRetrier]
  190. /// Creates an instance from `AdaptHandler` and `RetryHandler` closures.
  191. ///
  192. /// - Parameters:
  193. /// - adaptHandler: `AdaptHandler` closure to be used.
  194. /// - retryHandler: `RetryHandler` closure to be used.
  195. public init(adaptHandler: @escaping AdaptHandler, retryHandler: @escaping RetryHandler) {
  196. adapters = [Adapter(adaptHandler)]
  197. retriers = [Retrier(retryHandler)]
  198. }
  199. /// Creates an instance from `RequestAdapter` and `RequestRetrier` values.
  200. ///
  201. /// - Parameters:
  202. /// - adapter: `RequestAdapter` value to be used.
  203. /// - retrier: `RequestRetrier` value to be used.
  204. public init(adapter: any RequestAdapter, retrier: any RequestRetrier) {
  205. adapters = [adapter]
  206. retriers = [retrier]
  207. }
  208. /// Creates an instance from the arrays of `RequestAdapter` and `RequestRetrier` values.
  209. ///
  210. /// - Parameters:
  211. /// - adapters: `RequestAdapter` values to be used.
  212. /// - retriers: `RequestRetrier` values to be used.
  213. /// - interceptors: `RequestInterceptor`s to be used.
  214. public init(adapters: [any RequestAdapter] = [],
  215. retriers: [any RequestRetrier] = [],
  216. interceptors: [any RequestInterceptor] = []) {
  217. self.adapters = adapters + interceptors
  218. self.retriers = retriers + interceptors
  219. }
  220. @preconcurrency
  221. open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @Sendable @escaping (Result<URLRequest, any Error>) -> Void) {
  222. adapt(urlRequest, for: session, using: adapters, completion: completion)
  223. }
  224. private func adapt(_ urlRequest: URLRequest,
  225. for session: Session,
  226. using adapters: [any RequestAdapter],
  227. completion: @Sendable @escaping (Result<URLRequest, any Error>) -> Void) {
  228. var pendingAdapters = adapters
  229. guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return }
  230. let adapter = pendingAdapters.removeFirst()
  231. adapter.adapt(urlRequest, for: session) { [pendingAdapters] result in
  232. switch result {
  233. case let .success(urlRequest):
  234. self.adapt(urlRequest, for: session, using: pendingAdapters, completion: completion)
  235. case .failure:
  236. completion(result)
  237. }
  238. }
  239. }
  240. @preconcurrency
  241. open func adapt(_ urlRequest: URLRequest, using state: RequestAdapterState, completion: @Sendable @escaping (Result<URLRequest, any Error>) -> Void) {
  242. adapt(urlRequest, using: state, adapters: adapters, completion: completion)
  243. }
  244. private func adapt(_ urlRequest: URLRequest,
  245. using state: RequestAdapterState,
  246. adapters: [any RequestAdapter],
  247. completion: @Sendable @escaping (Result<URLRequest, any Error>) -> Void) {
  248. var pendingAdapters = adapters
  249. guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return }
  250. let adapter = pendingAdapters.removeFirst()
  251. adapter.adapt(urlRequest, using: state) { [pendingAdapters] result in
  252. switch result {
  253. case let .success(urlRequest):
  254. self.adapt(urlRequest, using: state, adapters: pendingAdapters, completion: completion)
  255. case .failure:
  256. completion(result)
  257. }
  258. }
  259. }
  260. @preconcurrency
  261. open func retry(_ request: Request,
  262. for session: Session,
  263. dueTo error: any Error,
  264. completion: @Sendable @escaping (RetryResult) -> Void) {
  265. retry(request, for: session, dueTo: error, using: retriers, completion: completion)
  266. }
  267. private func retry(_ request: Request,
  268. for session: Session,
  269. dueTo error: any Error,
  270. using retriers: [any RequestRetrier],
  271. completion: @Sendable @escaping (RetryResult) -> Void) {
  272. var pendingRetriers = retriers
  273. guard !pendingRetriers.isEmpty else { completion(.doNotRetry); return }
  274. let retrier = pendingRetriers.removeFirst()
  275. retrier.retry(request, for: session, dueTo: error) { [pendingRetriers] result in
  276. switch result {
  277. case .retry, .retryWithDelay, .doNotRetryWithError:
  278. completion(result)
  279. case .doNotRetry:
  280. // Only continue to the next retrier if retry was not triggered and no error was encountered
  281. self.retry(request, for: session, dueTo: error, using: pendingRetriers, completion: completion)
  282. }
  283. }
  284. }
  285. }
  286. extension RequestInterceptor where Self == Interceptor {
  287. /// Creates an `Interceptor` using the provided `AdaptHandler` and `RetryHandler` closures.
  288. ///
  289. /// - Parameters:
  290. /// - adapter: `AdapterHandler`to use to adapt the request.
  291. /// - retrier: `RetryHandler` to use to retry the request.
  292. /// - Returns: The `Interceptor`.
  293. public static func interceptor(adapter: @escaping AdaptHandler, retrier: @escaping RetryHandler) -> Interceptor {
  294. Interceptor(adaptHandler: adapter, retryHandler: retrier)
  295. }
  296. /// Creates an `Interceptor` using the provided `RequestAdapter` and `RequestRetrier` instances.
  297. /// - Parameters:
  298. /// - adapter: `RequestAdapter` to use to adapt the request
  299. /// - retrier: `RequestRetrier` to use to retry the request.
  300. /// - Returns: The `Interceptor`.
  301. public static func interceptor(adapter: any RequestAdapter, retrier: any RequestRetrier) -> Interceptor {
  302. Interceptor(adapter: adapter, retrier: retrier)
  303. }
  304. /// Creates an `Interceptor` using the provided `RequestAdapter`s, `RequestRetrier`s, and `RequestInterceptor`s.
  305. /// - Parameters:
  306. /// - adapters: `RequestAdapter`s to use to adapt the request. These adapters will be run until one fails.
  307. /// - retriers: `RequestRetrier`s to use to retry the request. These retriers will be run one at a time until
  308. /// a retry is triggered.
  309. /// - interceptors: `RequestInterceptor`s to use to intercept the request.
  310. /// - Returns: The `Interceptor`.
  311. public static func interceptor(adapters: [any RequestAdapter] = [],
  312. retriers: [any RequestRetrier] = [],
  313. interceptors: [any RequestInterceptor] = []) -> Interceptor {
  314. Interceptor(adapters: adapters, retriers: retriers, interceptors: interceptors)
  315. }
  316. }