Request.swift 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  1. //
  2. // Request.swift
  3. //
  4. // Copyright (c) 2014-2024 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. /// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback
  26. /// handling.
  27. public class Request {
  28. /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or
  29. /// `cancel()` on the `Request`.
  30. public enum State {
  31. /// Initial state of the `Request`.
  32. case initialized
  33. /// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on
  34. /// them in this state.
  35. case resumed
  36. /// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on
  37. /// them in this state.
  38. case suspended
  39. /// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on
  40. /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition
  41. /// to any other state.
  42. case cancelled
  43. /// `State` set when all response serialization completion closures have been cleared on the `Request` and
  44. /// enqueued on their respective queues.
  45. case finished
  46. /// Determines whether `self` can be transitioned to the provided `State`.
  47. func canTransitionTo(_ state: State) -> Bool {
  48. switch (self, state) {
  49. case (.initialized, _):
  50. return true
  51. case (_, .initialized), (.cancelled, _), (.finished, _):
  52. return false
  53. case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed):
  54. return true
  55. case (.suspended, .suspended), (.resumed, .resumed):
  56. return false
  57. case (_, .finished):
  58. return true
  59. }
  60. }
  61. }
  62. // MARK: - Initial State
  63. /// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances.
  64. public let id: UUID
  65. /// The serial queue for all internal async actions.
  66. public let underlyingQueue: DispatchQueue
  67. /// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`.
  68. public let serializationQueue: DispatchQueue
  69. /// `EventMonitor` used for event callbacks.
  70. public let eventMonitor: EventMonitor?
  71. /// The `Request`'s interceptor.
  72. public let interceptor: RequestInterceptor?
  73. /// The `Request`'s delegate.
  74. public private(set) weak var delegate: RequestDelegate?
  75. // MARK: - Mutable State
  76. /// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`.
  77. struct MutableState {
  78. /// State of the `Request`.
  79. var state: State = .initialized
  80. /// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks.
  81. var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
  82. /// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks.
  83. var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
  84. /// `RedirectHandler` provided for to handle request redirection.
  85. var redirectHandler: RedirectHandler?
  86. /// `CachedResponseHandler` provided to handle response caching.
  87. var cachedResponseHandler: CachedResponseHandler?
  88. /// Queue and closure called when the `Request` is able to create a cURL description of itself.
  89. var cURLHandler: (queue: DispatchQueue, handler: (String) -> Void)?
  90. /// Queue and closure called when the `Request` creates a `URLRequest`.
  91. var urlRequestHandler: (queue: DispatchQueue, handler: (URLRequest) -> Void)?
  92. /// Queue and closure called when the `Request` creates a `URLSessionTask`.
  93. var urlSessionTaskHandler: (queue: DispatchQueue, handler: (URLSessionTask) -> Void)?
  94. /// Response serialization closures that handle response parsing.
  95. var responseSerializers: [() -> Void] = []
  96. /// Response serialization completion closures executed once all response serializers are complete.
  97. var responseSerializerCompletions: [() -> Void] = []
  98. /// Whether response serializer processing is finished.
  99. var responseSerializerProcessingFinished = false
  100. /// `URLCredential` used for authentication challenges.
  101. var credential: URLCredential?
  102. /// All `URLRequest`s created by Alamofire on behalf of the `Request`.
  103. var requests: [URLRequest] = []
  104. /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`.
  105. var tasks: [URLSessionTask] = []
  106. /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond
  107. /// exactly the the `tasks` created.
  108. var metrics: [URLSessionTaskMetrics] = []
  109. /// Number of times any retriers provided retried the `Request`.
  110. var retryCount = 0
  111. /// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`.
  112. var error: AFError?
  113. /// Whether the instance has had `finish()` called and is running the serializers. Should be replaced with a
  114. /// representation in the state machine in the future.
  115. var isFinishing = false
  116. /// Actions to run when requests are finished. Use for concurrency support.
  117. var finishHandlers: [() -> Void] = []
  118. }
  119. /// Protected `MutableState` value that provides thread-safe access to state values.
  120. let mutableState = Protected(MutableState())
  121. /// `State` of the `Request`.
  122. public var state: State { mutableState.state }
  123. /// Returns whether `state` is `.initialized`.
  124. public var isInitialized: Bool { state == .initialized }
  125. /// Returns whether `state` is `.resumed`.
  126. public var isResumed: Bool { state == .resumed }
  127. /// Returns whether `state` is `.suspended`.
  128. public var isSuspended: Bool { state == .suspended }
  129. /// Returns whether `state` is `.cancelled`.
  130. public var isCancelled: Bool { state == .cancelled }
  131. /// Returns whether `state` is `.finished`.
  132. public var isFinished: Bool { state == .finished }
  133. // MARK: Progress
  134. /// Closure type executed when monitoring the upload or download progress of a request.
  135. public typealias ProgressHandler = (Progress) -> Void
  136. /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried.
  137. public let uploadProgress = Progress(totalUnitCount: 0)
  138. /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried.
  139. public let downloadProgress = Progress(totalUnitCount: 0)
  140. /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`.
  141. public internal(set) var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
  142. get { mutableState.uploadProgressHandler }
  143. set { mutableState.uploadProgressHandler = newValue }
  144. }
  145. /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`.
  146. public internal(set) var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
  147. get { mutableState.downloadProgressHandler }
  148. set { mutableState.downloadProgressHandler = newValue }
  149. }
  150. // MARK: Redirect Handling
  151. /// `RedirectHandler` set on the instance.
  152. public internal(set) var redirectHandler: RedirectHandler? {
  153. get { mutableState.redirectHandler }
  154. set { mutableState.redirectHandler = newValue }
  155. }
  156. // MARK: Cached Response Handling
  157. /// `CachedResponseHandler` set on the instance.
  158. public internal(set) var cachedResponseHandler: CachedResponseHandler? {
  159. get { mutableState.cachedResponseHandler }
  160. set { mutableState.cachedResponseHandler = newValue }
  161. }
  162. // MARK: URLCredential
  163. /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods.
  164. public internal(set) var credential: URLCredential? {
  165. get { mutableState.credential }
  166. set { mutableState.credential = newValue }
  167. }
  168. // MARK: Validators
  169. /// `Validator` callback closures that store the validation calls enqueued.
  170. let validators = Protected<[() -> Void]>([])
  171. // MARK: URLRequests
  172. /// All `URLRequest`s created on behalf of the `Request`, including original and adapted requests.
  173. public var requests: [URLRequest] { mutableState.requests }
  174. /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed.
  175. public var firstRequest: URLRequest? { requests.first }
  176. /// Last `URLRequest` created on behalf of the `Request`.
  177. public var lastRequest: URLRequest? { requests.last }
  178. /// Current `URLRequest` created on behalf of the `Request`.
  179. public var request: URLRequest? { lastRequest }
  180. /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from
  181. /// `requests` due to `URLSession` manipulation.
  182. public var performedRequests: [URLRequest] { mutableState.read { $0.tasks.compactMap(\.currentRequest) } }
  183. // MARK: HTTPURLResponse
  184. /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the
  185. /// last `URLSessionTask`.
  186. public var response: HTTPURLResponse? { lastTask?.response as? HTTPURLResponse }
  187. // MARK: Tasks
  188. /// All `URLSessionTask`s created on behalf of the `Request`.
  189. public var tasks: [URLSessionTask] { mutableState.tasks }
  190. /// First `URLSessionTask` created on behalf of the `Request`.
  191. public var firstTask: URLSessionTask? { tasks.first }
  192. /// Last `URLSessionTask` created on behalf of the `Request`.
  193. public var lastTask: URLSessionTask? { tasks.last }
  194. /// Current `URLSessionTask` created on behalf of the `Request`.
  195. public var task: URLSessionTask? { lastTask }
  196. // MARK: Metrics
  197. /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created.
  198. public var allMetrics: [URLSessionTaskMetrics] { mutableState.metrics }
  199. /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  200. public var firstMetrics: URLSessionTaskMetrics? { allMetrics.first }
  201. /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  202. public var lastMetrics: URLSessionTaskMetrics? { allMetrics.last }
  203. /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  204. public var metrics: URLSessionTaskMetrics? { lastMetrics }
  205. // MARK: Retry Count
  206. /// Number of times the `Request` has been retried.
  207. public var retryCount: Int { mutableState.retryCount }
  208. // MARK: Error
  209. /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed.
  210. public internal(set) var error: AFError? {
  211. get { mutableState.error }
  212. set { mutableState.error = newValue }
  213. }
  214. /// Default initializer for the `Request` superclass.
  215. ///
  216. /// - Parameters:
  217. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  218. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  219. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  220. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  221. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  222. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  223. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  224. init(id: UUID = UUID(),
  225. underlyingQueue: DispatchQueue,
  226. serializationQueue: DispatchQueue,
  227. eventMonitor: EventMonitor?,
  228. interceptor: RequestInterceptor?,
  229. delegate: RequestDelegate) {
  230. self.id = id
  231. self.underlyingQueue = underlyingQueue
  232. self.serializationQueue = serializationQueue
  233. self.eventMonitor = eventMonitor
  234. self.interceptor = interceptor
  235. self.delegate = delegate
  236. }
  237. // MARK: - Internal Event API
  238. // All API must be called from underlyingQueue.
  239. /// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active,
  240. /// the `URLRequest` will be adapted before being issued.
  241. ///
  242. /// - Parameter request: The `URLRequest` created.
  243. func didCreateInitialURLRequest(_ request: URLRequest) {
  244. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  245. mutableState.write { $0.requests.append(request) }
  246. eventMonitor?.request(self, didCreateInitialURLRequest: request)
  247. }
  248. /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`.
  249. ///
  250. /// - Note: Triggers retry.
  251. ///
  252. /// - Parameter error: `AFError` thrown from the failed creation.
  253. func didFailToCreateURLRequest(with error: AFError) {
  254. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  255. self.error = error
  256. eventMonitor?.request(self, didFailToCreateURLRequestWithError: error)
  257. callCURLHandlerIfNecessary()
  258. retryOrFinish(error: error)
  259. }
  260. /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`.
  261. ///
  262. /// - Parameters:
  263. /// - initialRequest: The `URLRequest` that was adapted.
  264. /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`.
  265. func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) {
  266. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  267. mutableState.write { $0.requests.append(adaptedRequest) }
  268. eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest)
  269. }
  270. /// Called when a `RequestAdapter` fails to adapt a `URLRequest`.
  271. ///
  272. /// - Note: Triggers retry.
  273. ///
  274. /// - Parameters:
  275. /// - request: The `URLRequest` the adapter was called with.
  276. /// - error: The `AFError` returned by the `RequestAdapter`.
  277. func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) {
  278. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  279. self.error = error
  280. eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error)
  281. callCURLHandlerIfNecessary()
  282. retryOrFinish(error: error)
  283. }
  284. /// Final `URLRequest` has been created for the instance.
  285. ///
  286. /// - Parameter request: The `URLRequest` created.
  287. func didCreateURLRequest(_ request: URLRequest) {
  288. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  289. mutableState.read { state in
  290. state.urlRequestHandler?.queue.async { state.urlRequestHandler?.handler(request) }
  291. }
  292. eventMonitor?.request(self, didCreateURLRequest: request)
  293. callCURLHandlerIfNecessary()
  294. }
  295. /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`.
  296. private func callCURLHandlerIfNecessary() {
  297. mutableState.write { mutableState in
  298. guard let cURLHandler = mutableState.cURLHandler else { return }
  299. cURLHandler.queue.async { cURLHandler.handler(self.cURLDescription()) }
  300. mutableState.cURLHandler = nil
  301. }
  302. }
  303. /// Called when a `URLSessionTask` is created on behalf of the instance.
  304. ///
  305. /// - Parameter task: The `URLSessionTask` created.
  306. func didCreateTask(_ task: URLSessionTask) {
  307. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  308. mutableState.write { state in
  309. state.tasks.append(task)
  310. guard let urlSessionTaskHandler = state.urlSessionTaskHandler else { return }
  311. urlSessionTaskHandler.queue.async { urlSessionTaskHandler.handler(task) }
  312. }
  313. eventMonitor?.request(self, didCreateTask: task)
  314. }
  315. /// Called when resumption is completed.
  316. func didResume() {
  317. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  318. eventMonitor?.requestDidResume(self)
  319. }
  320. /// Called when a `URLSessionTask` is resumed on behalf of the instance.
  321. ///
  322. /// - Parameter task: The `URLSessionTask` resumed.
  323. func didResumeTask(_ task: URLSessionTask) {
  324. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  325. eventMonitor?.request(self, didResumeTask: task)
  326. }
  327. /// Called when suspension is completed.
  328. func didSuspend() {
  329. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  330. eventMonitor?.requestDidSuspend(self)
  331. }
  332. /// Called when a `URLSessionTask` is suspended on behalf of the instance.
  333. ///
  334. /// - Parameter task: The `URLSessionTask` suspended.
  335. func didSuspendTask(_ task: URLSessionTask) {
  336. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  337. eventMonitor?.request(self, didSuspendTask: task)
  338. }
  339. /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`.
  340. func didCancel() {
  341. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  342. mutableState.write { mutableState in
  343. mutableState.error = mutableState.error ?? AFError.explicitlyCancelled
  344. }
  345. eventMonitor?.requestDidCancel(self)
  346. }
  347. /// Called when a `URLSessionTask` is cancelled on behalf of the instance.
  348. ///
  349. /// - Parameter task: The `URLSessionTask` cancelled.
  350. func didCancelTask(_ task: URLSessionTask) {
  351. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  352. eventMonitor?.request(self, didCancelTask: task)
  353. }
  354. /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance.
  355. ///
  356. /// - Parameter metrics: The `URLSessionTaskMetrics` gathered.
  357. func didGatherMetrics(_ metrics: URLSessionTaskMetrics) {
  358. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  359. mutableState.write { $0.metrics.append(metrics) }
  360. eventMonitor?.request(self, didGatherMetrics: metrics)
  361. }
  362. /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning.
  363. ///
  364. /// - Parameters:
  365. /// - task: The `URLSessionTask` which failed.
  366. /// - error: The early failure `AFError`.
  367. func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) {
  368. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  369. self.error = error
  370. // Task will still complete, so didCompleteTask(_:with:) will handle retry.
  371. eventMonitor?.request(self, didFailTask: task, earlyWithError: error)
  372. }
  373. /// Called when a `URLSessionTask` completes. All tasks will eventually call this method.
  374. ///
  375. /// - Note: Response validation is synchronously triggered in this step.
  376. ///
  377. /// - Parameters:
  378. /// - task: The `URLSessionTask` which completed.
  379. /// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this
  380. /// value is ignored.
  381. func didCompleteTask(_ task: URLSessionTask, with error: AFError?) {
  382. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  383. self.error = self.error ?? error
  384. let validators = validators.read { $0 }
  385. validators.forEach { $0() }
  386. eventMonitor?.request(self, didCompleteTask: task, with: error)
  387. retryOrFinish(error: self.error)
  388. }
  389. /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`.
  390. func prepareForRetry() {
  391. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  392. mutableState.write { $0.retryCount += 1 }
  393. reset()
  394. eventMonitor?.requestIsRetrying(self)
  395. }
  396. /// Called to determine whether retry will be triggered for the particular error, or whether the instance should
  397. /// call `finish()`.
  398. ///
  399. /// - Parameter error: The possible `AFError` which may trigger retry.
  400. func retryOrFinish(error: AFError?) {
  401. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  402. guard !isCancelled, let error, let delegate else { finish(); return }
  403. delegate.retryResult(for: self, dueTo: error) { retryResult in
  404. switch retryResult {
  405. case .doNotRetry:
  406. self.finish()
  407. case let .doNotRetryWithError(retryError):
  408. self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
  409. case .retry, .retryWithDelay:
  410. delegate.retryRequest(self, withDelay: retryResult.delay)
  411. }
  412. }
  413. }
  414. /// Finishes this `Request` and starts the response serializers.
  415. ///
  416. /// - Parameter error: The possible `Error` with which the instance will finish.
  417. func finish(error: AFError? = nil) {
  418. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  419. guard !mutableState.isFinishing else { return }
  420. mutableState.isFinishing = true
  421. if let error { self.error = error }
  422. // Start response handlers
  423. processNextResponseSerializer()
  424. eventMonitor?.requestDidFinish(self)
  425. }
  426. /// Appends the response serialization closure to the instance.
  427. ///
  428. /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`.
  429. ///
  430. /// - Parameter closure: The closure containing the response serialization call.
  431. func appendResponseSerializer(_ closure: @escaping () -> Void) {
  432. mutableState.write { mutableState in
  433. mutableState.responseSerializers.append(closure)
  434. if mutableState.state == .finished {
  435. mutableState.state = .resumed
  436. }
  437. if mutableState.responseSerializerProcessingFinished {
  438. underlyingQueue.async { self.processNextResponseSerializer() }
  439. }
  440. if mutableState.state.canTransitionTo(.resumed) {
  441. underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } }
  442. }
  443. }
  444. }
  445. /// Returns the next response serializer closure to execute if there's one left.
  446. ///
  447. /// - Returns: The next response serialization closure, if there is one.
  448. func nextResponseSerializer() -> (() -> Void)? {
  449. var responseSerializer: (() -> Void)?
  450. mutableState.write { mutableState in
  451. let responseSerializerIndex = mutableState.responseSerializerCompletions.count
  452. if responseSerializerIndex < mutableState.responseSerializers.count {
  453. responseSerializer = mutableState.responseSerializers[responseSerializerIndex]
  454. }
  455. }
  456. return responseSerializer
  457. }
  458. /// Processes the next response serializer and calls all completions if response serialization is complete.
  459. func processNextResponseSerializer() {
  460. guard let responseSerializer = nextResponseSerializer() else {
  461. // Execute all response serializer completions and clear them
  462. var completions: [() -> Void] = []
  463. mutableState.write { mutableState in
  464. completions = mutableState.responseSerializerCompletions
  465. // Clear out all response serializers and response serializer completions in mutable state since the
  466. // request is complete. It's important to do this prior to calling the completion closures in case
  467. // the completions call back into the request triggering a re-processing of the response serializers.
  468. // An example of how this can happen is by calling cancel inside a response completion closure.
  469. mutableState.responseSerializers.removeAll()
  470. mutableState.responseSerializerCompletions.removeAll()
  471. if mutableState.state.canTransitionTo(.finished) {
  472. mutableState.state = .finished
  473. }
  474. mutableState.responseSerializerProcessingFinished = true
  475. mutableState.isFinishing = false
  476. }
  477. completions.forEach { $0() }
  478. // Cleanup the request
  479. cleanup()
  480. return
  481. }
  482. serializationQueue.async { responseSerializer() }
  483. }
  484. /// Notifies the `Request` that the response serializer is complete.
  485. ///
  486. /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers
  487. /// are complete.
  488. func responseSerializerDidComplete(completion: @escaping () -> Void) {
  489. mutableState.write { $0.responseSerializerCompletions.append(completion) }
  490. processNextResponseSerializer()
  491. }
  492. /// Resets all task and response serializer related state for retry.
  493. func reset() {
  494. error = nil
  495. uploadProgress.totalUnitCount = 0
  496. uploadProgress.completedUnitCount = 0
  497. downloadProgress.totalUnitCount = 0
  498. downloadProgress.completedUnitCount = 0
  499. mutableState.write { state in
  500. state.isFinishing = false
  501. state.responseSerializerCompletions = []
  502. }
  503. }
  504. /// Called when updating the upload progress.
  505. ///
  506. /// - Parameters:
  507. /// - totalBytesSent: Total bytes sent so far.
  508. /// - totalBytesExpectedToSend: Total bytes expected to send.
  509. func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  510. uploadProgress.totalUnitCount = totalBytesExpectedToSend
  511. uploadProgress.completedUnitCount = totalBytesSent
  512. uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
  513. }
  514. /// Perform a closure on the current `state` while locked.
  515. ///
  516. /// - Parameter perform: The closure to perform.
  517. func withState(perform: (State) -> Void) {
  518. mutableState.withState(perform: perform)
  519. }
  520. // MARK: Task Creation
  521. /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
  522. ///
  523. /// - Parameters:
  524. /// - request: `URLRequest` to use to create the `URLSessionTask`.
  525. /// - session: `URLSession` which creates the `URLSessionTask`.
  526. ///
  527. /// - Returns: The `URLSessionTask` created.
  528. func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  529. fatalError("Subclasses must override.")
  530. }
  531. // MARK: - Public API
  532. // These APIs are callable from any queue.
  533. // MARK: State
  534. /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended.
  535. ///
  536. /// - Returns: The instance.
  537. @discardableResult
  538. public func cancel() -> Self {
  539. mutableState.write { mutableState in
  540. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  541. mutableState.state = .cancelled
  542. underlyingQueue.async { self.didCancel() }
  543. guard let task = mutableState.tasks.last, task.state != .completed else {
  544. underlyingQueue.async { self.finish() }
  545. return
  546. }
  547. // Resume to ensure metrics are gathered.
  548. task.resume()
  549. task.cancel()
  550. underlyingQueue.async { self.didCancelTask(task) }
  551. }
  552. return self
  553. }
  554. /// Suspends the instance.
  555. ///
  556. /// - Returns: The instance.
  557. @discardableResult
  558. public func suspend() -> Self {
  559. mutableState.write { mutableState in
  560. guard mutableState.state.canTransitionTo(.suspended) else { return }
  561. mutableState.state = .suspended
  562. underlyingQueue.async { self.didSuspend() }
  563. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  564. task.suspend()
  565. underlyingQueue.async { self.didSuspendTask(task) }
  566. }
  567. return self
  568. }
  569. /// Resumes the instance.
  570. ///
  571. /// - Returns: The instance.
  572. @discardableResult
  573. public func resume() -> Self {
  574. mutableState.write { mutableState in
  575. guard mutableState.state.canTransitionTo(.resumed) else { return }
  576. mutableState.state = .resumed
  577. underlyingQueue.async { self.didResume() }
  578. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  579. task.resume()
  580. underlyingQueue.async { self.didResumeTask(task) }
  581. }
  582. return self
  583. }
  584. // MARK: - Closure API
  585. /// Associates a credential using the provided values with the instance.
  586. ///
  587. /// - Parameters:
  588. /// - username: The username.
  589. /// - password: The password.
  590. /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default.
  591. ///
  592. /// - Returns: The instance.
  593. @discardableResult
  594. public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
  595. let credential = URLCredential(user: username, password: password, persistence: persistence)
  596. return authenticate(with: credential)
  597. }
  598. /// Associates the provided credential with the instance.
  599. ///
  600. /// - Parameter credential: The `URLCredential`.
  601. ///
  602. /// - Returns: The instance.
  603. @discardableResult
  604. public func authenticate(with credential: URLCredential) -> Self {
  605. mutableState.credential = credential
  606. return self
  607. }
  608. /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server.
  609. ///
  610. /// - Note: Only the last closure provided is used.
  611. ///
  612. /// - Parameters:
  613. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  614. /// - closure: The closure to be executed periodically as data is read from the server.
  615. ///
  616. /// - Returns: The instance.
  617. @discardableResult
  618. public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  619. mutableState.downloadProgressHandler = (handler: closure, queue: queue)
  620. return self
  621. }
  622. /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.
  623. ///
  624. /// - Note: Only the last closure provided is used.
  625. ///
  626. /// - Parameters:
  627. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  628. /// - closure: The closure to be executed periodically as data is sent to the server.
  629. ///
  630. /// - Returns: The instance.
  631. @discardableResult
  632. public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  633. mutableState.uploadProgressHandler = (handler: closure, queue: queue)
  634. return self
  635. }
  636. // MARK: Redirects
  637. /// Sets the redirect handler for the instance which will be used if a redirect response is encountered.
  638. ///
  639. /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash.
  640. ///
  641. /// - Parameter handler: The `RedirectHandler`.
  642. ///
  643. /// - Returns: The instance.
  644. @discardableResult
  645. public func redirect(using handler: RedirectHandler) -> Self {
  646. mutableState.write { mutableState in
  647. precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.")
  648. mutableState.redirectHandler = handler
  649. }
  650. return self
  651. }
  652. // MARK: Cached Responses
  653. /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response.
  654. ///
  655. /// - Note: Attempting to set the cache handler more than once is a logic error and will crash.
  656. ///
  657. /// - Parameter handler: The `CachedResponseHandler`.
  658. ///
  659. /// - Returns: The instance.
  660. @discardableResult
  661. public func cacheResponse(using handler: CachedResponseHandler) -> Self {
  662. mutableState.write { mutableState in
  663. precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.")
  664. mutableState.cachedResponseHandler = handler
  665. }
  666. return self
  667. }
  668. // MARK: - Lifetime APIs
  669. /// Sets a handler to be called when the cURL description of the request is available.
  670. ///
  671. /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
  672. ///
  673. /// - Parameters:
  674. /// - queue: `DispatchQueue` on which `handler` will be called.
  675. /// - handler: Closure to be called when the cURL description is available.
  676. ///
  677. /// - Returns: The instance.
  678. @discardableResult
  679. public func cURLDescription(on queue: DispatchQueue, calling handler: @escaping (String) -> Void) -> Self {
  680. mutableState.write { mutableState in
  681. if mutableState.requests.last != nil {
  682. queue.async { handler(self.cURLDescription()) }
  683. } else {
  684. mutableState.cURLHandler = (queue, handler)
  685. }
  686. }
  687. return self
  688. }
  689. /// Sets a handler to be called when the cURL description of the request is available.
  690. ///
  691. /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
  692. ///
  693. /// - Parameter handler: Closure to be called when the cURL description is available. Called on the instance's
  694. /// `underlyingQueue` by default.
  695. ///
  696. /// - Returns: The instance.
  697. @discardableResult
  698. public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self {
  699. cURLDescription(on: underlyingQueue, calling: handler)
  700. return self
  701. }
  702. /// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance.
  703. ///
  704. /// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried.
  705. ///
  706. /// - Parameters:
  707. /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
  708. /// - handler: Closure to be called when a `URLRequest` is available.
  709. ///
  710. /// - Returns: The instance.
  711. @discardableResult
  712. public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLRequest) -> Void) -> Self {
  713. mutableState.write { state in
  714. if let request = state.requests.last {
  715. queue.async { handler(request) }
  716. }
  717. state.urlRequestHandler = (queue, handler)
  718. }
  719. return self
  720. }
  721. /// Sets a closure to be called whenever the instance creates a `URLSessionTask`.
  722. ///
  723. /// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It
  724. /// **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features.
  725. /// Additionally, this closure may be called multiple times if the instance is retried.
  726. ///
  727. /// - Parameters:
  728. /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
  729. /// - handler: Closure to be called when the `URLSessionTask` is available.
  730. ///
  731. /// - Returns: The instance.
  732. @discardableResult
  733. public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLSessionTask) -> Void) -> Self {
  734. mutableState.write { state in
  735. if let task = state.tasks.last {
  736. queue.async { handler(task) }
  737. }
  738. state.urlSessionTaskHandler = (queue, handler)
  739. }
  740. return self
  741. }
  742. // MARK: Cleanup
  743. /// Adds a `finishHandler` closure to be called when the request completes.
  744. ///
  745. /// - Parameter closure: Closure to be called when the request finishes.
  746. func onFinish(perform finishHandler: @escaping () -> Void) {
  747. guard !isFinished else { finishHandler(); return }
  748. mutableState.write { state in
  749. state.finishHandlers.append(finishHandler)
  750. }
  751. }
  752. /// Final cleanup step executed when the instance finishes response serialization.
  753. func cleanup() {
  754. let handlers = mutableState.finishHandlers
  755. handlers.forEach { $0() }
  756. mutableState.write { state in
  757. state.finishHandlers.removeAll()
  758. }
  759. delegate?.cleanup(after: self)
  760. }
  761. }
  762. extension Request {
  763. /// Type indicating how a `DataRequest` or `DataStreamRequest` should proceed after receiving an `HTTPURLResponse`.
  764. public enum ResponseDisposition {
  765. /// Allow the request to continue normally.
  766. case allow
  767. /// Cancel the request, similar to calling `cancel()`.
  768. case cancel
  769. var sessionDisposition: URLSession.ResponseDisposition {
  770. switch self {
  771. case .allow: return .allow
  772. case .cancel: return .cancel
  773. }
  774. }
  775. }
  776. }
  777. // MARK: - Protocol Conformances
  778. extension Request: Equatable {
  779. public static func ==(lhs: Request, rhs: Request) -> Bool {
  780. lhs.id == rhs.id
  781. }
  782. }
  783. extension Request: Hashable {
  784. public func hash(into hasher: inout Hasher) {
  785. hasher.combine(id)
  786. }
  787. }
  788. extension Request: CustomStringConvertible {
  789. /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
  790. /// created, as well as the response status code, if a response has been received.
  791. public var description: String {
  792. guard let request = performedRequests.last ?? lastRequest,
  793. let url = request.url,
  794. let method = request.httpMethod else { return "No request created yet." }
  795. let requestDescription = "\(method) \(url.absoluteString)"
  796. return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
  797. }
  798. }
  799. extension Request {
  800. /// cURL representation of the instance.
  801. ///
  802. /// - Returns: The cURL equivalent of the instance.
  803. public func cURLDescription() -> String {
  804. guard
  805. let request = lastRequest,
  806. let url = request.url,
  807. let host = url.host,
  808. let method = request.httpMethod else { return "$ curl command could not be created" }
  809. var components = ["$ curl -v"]
  810. components.append("-X \(method)")
  811. if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
  812. let protectionSpace = URLProtectionSpace(host: host,
  813. port: url.port ?? 0,
  814. protocol: url.scheme,
  815. realm: host,
  816. authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  817. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  818. for credential in credentials {
  819. guard let user = credential.user, let password = credential.password else { continue }
  820. components.append("-u \(user):\(password)")
  821. }
  822. } else {
  823. if let credential, let user = credential.user, let password = credential.password {
  824. components.append("-u \(user):\(password)")
  825. }
  826. }
  827. }
  828. if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
  829. if
  830. let cookieStorage = configuration.httpCookieStorage,
  831. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty {
  832. let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
  833. components.append("-b \"\(allCookies)\"")
  834. }
  835. }
  836. var headers = HTTPHeaders()
  837. if let sessionHeaders = delegate?.sessionConfiguration.headers {
  838. for header in sessionHeaders where header.name != "Cookie" {
  839. headers[header.name] = header.value
  840. }
  841. }
  842. for header in request.headers where header.name != "Cookie" {
  843. headers[header.name] = header.value
  844. }
  845. for header in headers {
  846. let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"")
  847. components.append("-H \"\(header.name): \(escapedValue)\"")
  848. }
  849. if let httpBodyData = request.httpBody {
  850. let httpBody = String(decoding: httpBodyData, as: UTF8.self)
  851. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  852. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  853. components.append("-d \"\(escapedBody)\"")
  854. }
  855. components.append("\"\(url.absoluteString)\"")
  856. return components.joined(separator: " \\\n\t")
  857. }
  858. }
  859. /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
  860. public protocol RequestDelegate: AnyObject {
  861. /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s.
  862. var sessionConfiguration: URLSessionConfiguration { get }
  863. /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler.
  864. var startImmediately: Bool { get }
  865. /// Notifies the delegate the `Request` has reached a point where it needs cleanup.
  866. ///
  867. /// - Parameter request: The `Request` to cleanup after.
  868. func cleanup(after request: Request)
  869. /// Asynchronously ask the delegate whether a `Request` will be retried.
  870. ///
  871. /// - Parameters:
  872. /// - request: `Request` which failed.
  873. /// - error: `Error` which produced the failure.
  874. /// - completion: Closure taking the `RetryResult` for evaluation.
  875. func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void)
  876. /// Asynchronously retry the `Request`.
  877. ///
  878. /// - Parameters:
  879. /// - request: `Request` which will be retried.
  880. /// - timeDelay: `TimeInterval` after which the retry will be triggered.
  881. func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
  882. }