RequestInterceptor.swift 15 KB

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