2
0

RequestInterceptor.swift 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 AFResult.
  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 (AFResult<URLRequest>) -> Void)
  34. }
  35. // MARK: -
  36. public enum RetryResult {
  37. case retry
  38. case retryWithDelay(TimeInterval)
  39. case doNotRetry
  40. case doNotRetryWithError(Error)
  41. }
  42. extension RetryResult {
  43. var retryRequired: Bool {
  44. switch self {
  45. case .retry, .retryWithDelay: return true
  46. default: return false
  47. }
  48. }
  49. var delay: TimeInterval? {
  50. switch self {
  51. case .retryWithDelay(let delay): return delay
  52. default: return nil
  53. }
  54. }
  55. var error: Error? {
  56. guard case .doNotRetryWithError(let error) = self else { return nil }
  57. return error
  58. }
  59. }
  60. /// A type that determines whether a request should be retried after being executed by the specified session manager
  61. /// and encountering an error.
  62. public protocol RequestRetrier {
  63. /// Determines whether the `Request` should be retried by calling the `completion` closure.
  64. ///
  65. /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs
  66. /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly
  67. /// cleaned up after.
  68. ///
  69. /// - parameter request: The `Request` that failed due to the encountered error.
  70. /// - parameter session: The `Session` the request was executed on.
  71. /// - parameter error: The `Error` encountered when executing the request.
  72. /// - parameter completion: The completion closure to be executed when retry decision has been determined.
  73. func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void)
  74. }
  75. // MARK: -
  76. /// A type that intercepts requests to potentially adapt and retry them.
  77. public protocol RequestInterceptor: RequestAdapter, RequestRetrier {}
  78. extension RequestInterceptor {
  79. public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (AFResult<URLRequest>) -> Void) {
  80. completion(.success(urlRequest))
  81. }
  82. public func retry(
  83. _ request: Request,
  84. for session: Session,
  85. dueTo error: Error,
  86. completion: @escaping (RetryResult) -> Void)
  87. {
  88. completion(.doNotRetry)
  89. }
  90. }
  91. public typealias AdaptHandler = (URLRequest, Session, _ completion: @escaping (AFResult<URLRequest>) -> Void) -> Void
  92. public typealias RetryHandler = (Request, Session, Error, _ completion: @escaping (RetryResult) -> Void) -> Void
  93. // MARK: -
  94. open class Adapter: RequestInterceptor {
  95. private let adaptHandler: AdaptHandler
  96. public init(_ adaptHandler: @escaping AdaptHandler) {
  97. self.adaptHandler = adaptHandler
  98. }
  99. open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (AFResult<URLRequest>) -> Void) {
  100. adaptHandler(urlRequest, session, completion)
  101. }
  102. }
  103. // MARK: -
  104. open class Retrier: RequestInterceptor {
  105. private let retryHandler: RetryHandler
  106. public init(_ retryHandler: @escaping RetryHandler) {
  107. self.retryHandler = retryHandler
  108. }
  109. open func retry(
  110. _ request: Request,
  111. for session: Session,
  112. dueTo error: Error,
  113. completion: @escaping (RetryResult) -> Void)
  114. {
  115. retryHandler(request, session, error, completion)
  116. }
  117. }
  118. // MARK: -
  119. open class Interceptor: RequestInterceptor {
  120. public let adapters: [RequestAdapter]
  121. public let retriers: [RequestRetrier]
  122. public init(adaptHandler: @escaping AdaptHandler, retryHandler: @escaping RetryHandler) {
  123. self.adapters = [Adapter(adaptHandler)]
  124. self.retriers = [Retrier(retryHandler)]
  125. }
  126. public init(adapter: RequestAdapter, retrier: RequestRetrier) {
  127. self.adapters = [adapter]
  128. self.retriers = [retrier]
  129. }
  130. public init(adapters: [RequestAdapter] = [], retriers: [RequestRetrier] = []) {
  131. self.adapters = adapters
  132. self.retriers = retriers
  133. }
  134. open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (AFResult<URLRequest>) -> Void) {
  135. adapt(urlRequest, for: session, using: adapters, completion: completion)
  136. }
  137. private func adapt(
  138. _ urlRequest: URLRequest,
  139. for session: Session,
  140. using adapters: [RequestAdapter],
  141. completion: @escaping (AFResult<URLRequest>) -> Void)
  142. {
  143. var pendingAdapters = adapters
  144. guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return }
  145. let adapter = pendingAdapters.removeFirst()
  146. adapter.adapt(urlRequest, for: session) { result in
  147. switch result {
  148. case .success(let urlRequest):
  149. self.adapt(urlRequest, for: session, using: pendingAdapters, completion: completion)
  150. case .failure:
  151. completion(result)
  152. }
  153. }
  154. }
  155. open func retry(
  156. _ request: Request,
  157. for session: Session,
  158. dueTo error: Error,
  159. completion: @escaping (RetryResult) -> Void)
  160. {
  161. retry(request, for: session, dueTo: error, using: retriers, completion: completion)
  162. }
  163. private func retry(
  164. _ request: Request,
  165. for session: Session,
  166. dueTo error: Error,
  167. using retriers: [RequestRetrier],
  168. completion: @escaping (RetryResult) -> Void)
  169. {
  170. var pendingRetriers = retriers
  171. guard !pendingRetriers.isEmpty else { completion(.doNotRetry); return }
  172. let retrier = pendingRetriers.removeFirst()
  173. retrier.retry(request, for: session, dueTo: error) { result in
  174. switch result {
  175. case .retry, .retryWithDelay, .doNotRetryWithError:
  176. completion(result)
  177. case .doNotRetry:
  178. // Only continue to the next retrier if retry was not triggered and no error was encountered
  179. self.retry(request, for: session, dueTo: error, using: pendingRetriers, completion: completion)
  180. }
  181. }
  182. }
  183. }