Request.swift 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  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: @unchecked Sendable {
  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. true
  51. case (_, .initialized), (.cancelled, _), (.finished, _):
  52. false
  53. case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed):
  54. true
  55. case (.suspended, .suspended), (.resumed, .resumed):
  56. false
  57. case (_, .finished):
  58. 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: (any EventMonitor)?
  71. /// The `Request`'s interceptor.
  72. public let interceptor: (any RequestInterceptor)?
  73. /// The `Request`'s delegate.
  74. public private(set) weak var delegate: (any 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: (any RedirectHandler)?
  86. /// `CachedResponseHandler` provided to handle response caching.
  87. var cachedResponseHandler: (any CachedResponseHandler)?
  88. /// Queue and closure called when the `Request` is able to create a cURL description of itself.
  89. var cURLHandler: (queue: DispatchQueue, handler: @Sendable (String) -> Void)?
  90. /// Queue and closure called when the `Request` creates a `URLRequest`.
  91. var urlRequestHandler: (queue: DispatchQueue, handler: @Sendable (URLRequest) -> Void)?
  92. /// Queue and closure called when the `Request` creates a `URLSessionTask`.
  93. var urlSessionTaskHandler: (queue: DispatchQueue, handler: @Sendable (URLSessionTask) -> Void)?
  94. /// Response serialization closures that handle response parsing.
  95. var responseSerializers: [@Sendable () -> Void] = []
  96. /// Response serialization completion closures for successful serializers, executed once all response serializers are complete.
  97. var responseSerializerCompletions: [@Sendable () -> 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.read(\.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 = @Sendable (_ progress: 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.read(\.uploadProgressHandler) }
  143. set { mutableState.write { $0.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.read(\.downloadProgressHandler) }
  148. set { mutableState.write { $0.downloadProgressHandler = newValue } }
  149. }
  150. // MARK: Redirect Handling
  151. /// `RedirectHandler` set on the instance.
  152. public internal(set) var redirectHandler: (any RedirectHandler)? {
  153. get { mutableState.read(\.redirectHandler) }
  154. set { mutableState.write { $0.redirectHandler = newValue } }
  155. }
  156. // MARK: Cached Response Handling
  157. /// `CachedResponseHandler` set on the instance.
  158. public internal(set) var cachedResponseHandler: (any CachedResponseHandler)? {
  159. get { mutableState.read(\.cachedResponseHandler) }
  160. set { mutableState.write { $0.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.read(\.credential) }
  166. set { mutableState.write { $0.credential = newValue } }
  167. }
  168. // MARK: Validators
  169. /// `Validator` callback closures that store the validation calls enqueued.
  170. let validators = Protected<[@Sendable () -> 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.read(\.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.read(\.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.read(\.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.read(\.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.read(\.error) }
  212. set { mutableState.write { $0.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: (any EventMonitor)?,
  228. interceptor: (any RequestInterceptor)?,
  229. delegate: any 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. guard let urlRequestHandler = state.urlRequestHandler else { return }
  291. urlRequestHandler.queue.async { urlRequestHandler.handler(request) }
  292. }
  293. eventMonitor?.request(self, didCreateURLRequest: request)
  294. callCURLHandlerIfNecessary()
  295. }
  296. /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`.
  297. private func callCURLHandlerIfNecessary() {
  298. mutableState.write { mutableState in
  299. guard let cURLHandler = mutableState.cURLHandler else { return }
  300. cURLHandler.queue.async { cURLHandler.handler(self.cURLDescription()) }
  301. mutableState.cURLHandler = nil
  302. }
  303. }
  304. /// Called when a `URLSessionTask` is created on behalf of the instance.
  305. ///
  306. /// - Parameter task: The `URLSessionTask` created.
  307. func didCreateTask(_ task: URLSessionTask) {
  308. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  309. mutableState.write { state in
  310. state.tasks.append(task)
  311. guard let urlSessionTaskHandler = state.urlSessionTaskHandler else { return }
  312. urlSessionTaskHandler.queue.async { urlSessionTaskHandler.handler(task) }
  313. }
  314. eventMonitor?.request(self, didCreateTask: task)
  315. }
  316. /// Called when resumption is completed.
  317. func didResume() {
  318. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  319. eventMonitor?.requestDidResume(self)
  320. }
  321. /// Called when a `URLSessionTask` is resumed on behalf of the instance.
  322. ///
  323. /// - Parameter task: The `URLSessionTask` resumed.
  324. func didResumeTask(_ task: URLSessionTask) {
  325. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  326. eventMonitor?.request(self, didResumeTask: task)
  327. }
  328. /// Called when suspension is completed.
  329. func didSuspend() {
  330. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  331. eventMonitor?.requestDidSuspend(self)
  332. }
  333. /// Called when a `URLSessionTask` is suspended on behalf of the instance.
  334. ///
  335. /// - Parameter task: The `URLSessionTask` suspended.
  336. func didSuspendTask(_ task: URLSessionTask) {
  337. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  338. eventMonitor?.request(self, didSuspendTask: task)
  339. }
  340. /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`.
  341. func didCancel() {
  342. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  343. mutableState.write { mutableState in
  344. mutableState.error = mutableState.error ?? AFError.explicitlyCancelled
  345. }
  346. eventMonitor?.requestDidCancel(self)
  347. }
  348. /// Called when a `URLSessionTask` is cancelled on behalf of the instance.
  349. ///
  350. /// - Parameter task: The `URLSessionTask` cancelled.
  351. func didCancelTask(_ task: URLSessionTask) {
  352. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  353. eventMonitor?.request(self, didCancelTask: task)
  354. }
  355. /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance.
  356. ///
  357. /// - Parameter metrics: The `URLSessionTaskMetrics` gathered.
  358. func didGatherMetrics(_ metrics: URLSessionTaskMetrics) {
  359. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  360. mutableState.write { $0.metrics.append(metrics) }
  361. eventMonitor?.request(self, didGatherMetrics: metrics)
  362. }
  363. /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning.
  364. ///
  365. /// - Parameters:
  366. /// - task: The `URLSessionTask` which failed.
  367. /// - error: The early failure `AFError`.
  368. func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) {
  369. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  370. self.error = error
  371. // Task will still complete, so didCompleteTask(_:with:) will handle retry.
  372. eventMonitor?.request(self, didFailTask: task, earlyWithError: error)
  373. }
  374. /// Called when a `URLSessionTask` completes. All tasks will eventually call this method.
  375. ///
  376. /// - Note: Response validation is synchronously triggered in this step.
  377. ///
  378. /// - Parameters:
  379. /// - task: The `URLSessionTask` which completed.
  380. /// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this
  381. /// value is ignored.
  382. func didCompleteTask(_ task: URLSessionTask, with error: AFError?) {
  383. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  384. mutableState.write { $0.error = $0.error ?? error }
  385. let validators = validators.read(\.self)
  386. validators.forEach { $0() }
  387. eventMonitor?.request(self, didCompleteTask: task, with: error)
  388. retryOrFinish(error: self.error)
  389. }
  390. /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`.
  391. func prepareForRetry() {
  392. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  393. mutableState.write { $0.retryCount += 1 }
  394. reset()
  395. eventMonitor?.requestIsRetrying(self)
  396. }
  397. /// Called to determine whether retry will be triggered for the particular error, or whether the instance should
  398. /// call `finish()`.
  399. ///
  400. /// - Parameter error: The possible `AFError` which may trigger retry.
  401. func retryOrFinish(error: AFError?) {
  402. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  403. guard !isCancelled, let error, let delegate else { finish(); return }
  404. delegate.retryResult(for: self, dueTo: error) { retryResult in
  405. switch retryResult {
  406. case .doNotRetry:
  407. self.finish()
  408. case let .doNotRetryWithError(retryError):
  409. self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
  410. case .retry, .retryWithDelay:
  411. delegate.retryRequest(self, withDelay: retryResult.delay)
  412. }
  413. }
  414. }
  415. /// Finishes this `Request` and starts the response serializers.
  416. ///
  417. /// - Parameter error: The possible `Error` with which the instance will finish.
  418. func finish(error: AFError? = nil) {
  419. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  420. let shouldStartResponseSerializers = mutableState.write { mutableState in
  421. guard !mutableState.isFinishing else { return false }
  422. mutableState.isFinishing = true
  423. if let error { mutableState.error = error }
  424. return true
  425. }
  426. guard shouldStartResponseSerializers else { return }
  427. // Start response handlers
  428. processNextResponseSerializer()
  429. eventMonitor?.requestDidFinish(self)
  430. }
  431. /// Appends the response serialization closure to the instance.
  432. ///
  433. /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`.
  434. ///
  435. /// - Parameter closure: The closure containing the response serialization call.
  436. func appendResponseSerializer(_ closure: @escaping @Sendable () -> Void) {
  437. mutableState.write { mutableState in
  438. mutableState.responseSerializers.append(closure)
  439. if mutableState.state == .finished {
  440. mutableState.state = .resumed
  441. }
  442. // If serializers have already been processed, execute the added serializer immediately.
  443. if mutableState.responseSerializerProcessingFinished {
  444. underlyingQueue.async { self.processNextResponseSerializer() }
  445. }
  446. if mutableState.state.canTransitionTo(.resumed) {
  447. underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } }
  448. }
  449. }
  450. }
  451. /// Processes the next response serializer and calls all completions if response serialization is complete.
  452. func processNextResponseSerializer() {
  453. let executeOutside: () -> Void = mutableState.write { mutableState in
  454. let responseSerializerIndex = mutableState.responseSerializerCompletions.count
  455. let isAvailableSerializer = responseSerializerIndex < mutableState.responseSerializers.count
  456. let responseSerializer = isAvailableSerializer ? mutableState.responseSerializers[responseSerializerIndex] : nil
  457. if let responseSerializer {
  458. return { self.serializationQueue.async { responseSerializer() } }
  459. } else {
  460. let completions = mutableState.responseSerializerCompletions
  461. // Clear out all response serializers and response serializer completions in mutable state since the
  462. // request is complete. It's important to do this prior to calling the completion closures in case
  463. // the completions call back into the request triggering a re-processing of the response serializers.
  464. // An example of how this can happen is by calling cancel inside a response completion closure.
  465. mutableState.responseSerializers.removeAll()
  466. mutableState.responseSerializerCompletions.removeAll()
  467. if mutableState.state.canTransitionTo(.finished) {
  468. mutableState.state = .finished
  469. }
  470. mutableState.responseSerializerProcessingFinished = true
  471. mutableState.isFinishing = false
  472. return {
  473. completions.forEach { $0() }
  474. // Cleanup the request outside the lock
  475. self.cleanup()
  476. }
  477. }
  478. }
  479. executeOutside()
  480. }
  481. /// Notifies the `Request` that the response serializer is complete.
  482. ///
  483. /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers
  484. /// are complete.
  485. func responseSerializerDidComplete(completion: @escaping @Sendable () -> Void) {
  486. mutableState.write { $0.responseSerializerCompletions.append(completion) }
  487. processNextResponseSerializer()
  488. }
  489. /// Resets all task and response serializer related state for retry.
  490. func reset() {
  491. uploadProgress.totalUnitCount = 0
  492. uploadProgress.completedUnitCount = 0
  493. downloadProgress.totalUnitCount = 0
  494. downloadProgress.completedUnitCount = 0
  495. mutableState.write { mutableState in
  496. mutableState.error = nil
  497. mutableState.isFinishing = false
  498. mutableState.responseSerializerCompletions = []
  499. }
  500. }
  501. /// Called when updating the upload progress.
  502. ///
  503. /// - Parameters:
  504. /// - totalBytesSent: Total bytes sent so far.
  505. /// - totalBytesExpectedToSend: Total bytes expected to send.
  506. func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  507. uploadProgress.totalUnitCount = totalBytesExpectedToSend
  508. uploadProgress.completedUnitCount = totalBytesSent
  509. uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
  510. }
  511. /// Perform a closure on the current `state` while locked.
  512. ///
  513. /// - Parameter perform: The closure to perform.
  514. func withState(perform: (State) -> Void) {
  515. mutableState.withState(perform: perform)
  516. }
  517. // MARK: Task Creation
  518. /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
  519. ///
  520. /// - Parameters:
  521. /// - request: `URLRequest` to use to create the `URLSessionTask`.
  522. /// - session: `URLSession` which creates the `URLSessionTask`.
  523. ///
  524. /// - Returns: The `URLSessionTask` created.
  525. func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  526. fatalError("Subclasses must override.")
  527. }
  528. // MARK: - Public API
  529. // These APIs are callable from any queue.
  530. // MARK: State
  531. /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended.
  532. ///
  533. /// - Returns: The instance.
  534. @discardableResult
  535. public func cancel() -> Self {
  536. mutableState.write { mutableState in
  537. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  538. mutableState.state = .cancelled
  539. underlyingQueue.async { self.didCancel() }
  540. guard let task = mutableState.tasks.last, task.state != .completed else {
  541. underlyingQueue.async { self.finish() }
  542. return
  543. }
  544. // Resume to ensure metrics are gathered.
  545. task.resume()
  546. task.cancel()
  547. underlyingQueue.async { self.didCancelTask(task) }
  548. }
  549. return self
  550. }
  551. /// Suspends the instance.
  552. ///
  553. /// - Returns: The instance.
  554. @discardableResult
  555. public func suspend() -> Self {
  556. mutableState.write { mutableState in
  557. guard mutableState.state.canTransitionTo(.suspended) else { return }
  558. mutableState.state = .suspended
  559. underlyingQueue.async { self.didSuspend() }
  560. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  561. task.suspend()
  562. underlyingQueue.async { self.didSuspendTask(task) }
  563. }
  564. return self
  565. }
  566. /// Resumes the instance.
  567. ///
  568. /// - Returns: The instance.
  569. @discardableResult
  570. public func resume() -> Self {
  571. mutableState.write { mutableState in
  572. guard mutableState.state.canTransitionTo(.resumed) else { return }
  573. mutableState.state = .resumed
  574. underlyingQueue.async { self.didResume() }
  575. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  576. task.resume()
  577. underlyingQueue.async { self.didResumeTask(task) }
  578. }
  579. return self
  580. }
  581. // MARK: - Closure API
  582. /// Associates a credential using the provided values with the instance.
  583. ///
  584. /// - Parameters:
  585. /// - username: The username.
  586. /// - password: The password.
  587. /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default.
  588. ///
  589. /// - Returns: The instance.
  590. @discardableResult
  591. public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
  592. let credential = URLCredential(user: username, password: password, persistence: persistence)
  593. return authenticate(with: credential)
  594. }
  595. /// Associates the provided credential with the instance.
  596. ///
  597. /// - Parameter credential: The `URLCredential`.
  598. ///
  599. /// - Returns: The instance.
  600. @discardableResult
  601. public func authenticate(with credential: URLCredential) -> Self {
  602. self.credential = credential
  603. return self
  604. }
  605. /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server.
  606. ///
  607. /// - Note: Only the last closure provided is used.
  608. ///
  609. /// - Parameters:
  610. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  611. /// - closure: The closure to be executed periodically as data is read from the server.
  612. ///
  613. /// - Returns: The instance.
  614. @preconcurrency
  615. @discardableResult
  616. public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  617. downloadProgressHandler = (handler: closure, queue: queue)
  618. return self
  619. }
  620. /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.
  621. ///
  622. /// - Note: Only the last closure provided is used.
  623. ///
  624. /// - Parameters:
  625. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  626. /// - closure: The closure to be executed periodically as data is sent to the server.
  627. ///
  628. /// - Returns: The instance.
  629. @preconcurrency
  630. @discardableResult
  631. public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  632. uploadProgressHandler = (handler: closure, queue: queue)
  633. return self
  634. }
  635. // MARK: Redirects
  636. /// Sets the redirect handler for the instance which will be used if a redirect response is encountered.
  637. ///
  638. /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash.
  639. ///
  640. /// - Parameter handler: The `RedirectHandler`.
  641. ///
  642. /// - Returns: The instance.
  643. @preconcurrency
  644. @discardableResult
  645. public func redirect(using handler: any 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. @preconcurrency
  661. @discardableResult
  662. public func cacheResponse(using handler: any CachedResponseHandler) -> Self {
  663. mutableState.write { mutableState in
  664. precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.")
  665. mutableState.cachedResponseHandler = handler
  666. }
  667. return self
  668. }
  669. // MARK: - Lifetime APIs
  670. /// Sets a handler to be called when the cURL description of the request is available.
  671. ///
  672. /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
  673. ///
  674. /// - Parameters:
  675. /// - queue: `DispatchQueue` on which `handler` will be called.
  676. /// - handler: Closure to be called when the cURL description is available.
  677. ///
  678. /// - Returns: The instance.
  679. @preconcurrency
  680. @discardableResult
  681. public func cURLDescription(on queue: DispatchQueue, calling handler: @escaping @Sendable (String) -> Void) -> Self {
  682. mutableState.write { mutableState in
  683. if mutableState.requests.last != nil {
  684. queue.async { handler(self.cURLDescription()) }
  685. } else {
  686. mutableState.cURLHandler = (queue, handler)
  687. }
  688. }
  689. return self
  690. }
  691. /// Sets a handler to be called when the cURL description of the request is available.
  692. ///
  693. /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
  694. ///
  695. /// - Parameter handler: Closure to be called when the cURL description is available. Called on the instance's
  696. /// `underlyingQueue` by default.
  697. ///
  698. /// - Returns: The instance.
  699. @preconcurrency
  700. @discardableResult
  701. public func cURLDescription(calling handler: @escaping @Sendable (String) -> Void) -> Self {
  702. cURLDescription(on: underlyingQueue, calling: handler)
  703. return self
  704. }
  705. /// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance.
  706. ///
  707. /// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried.
  708. ///
  709. /// - Parameters:
  710. /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
  711. /// - handler: Closure to be called when a `URLRequest` is available.
  712. ///
  713. /// - Returns: The instance.
  714. @preconcurrency
  715. @discardableResult
  716. public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping @Sendable (URLRequest) -> Void) -> Self {
  717. mutableState.write { state in
  718. if let request = state.requests.last {
  719. queue.async { handler(request) }
  720. }
  721. state.urlRequestHandler = (queue, handler)
  722. }
  723. return self
  724. }
  725. /// Sets a closure to be called whenever the instance creates a `URLSessionTask`.
  726. ///
  727. /// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It
  728. /// **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features.
  729. /// Additionally, this closure may be called multiple times if the instance is retried.
  730. ///
  731. /// - Parameters:
  732. /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
  733. /// - handler: Closure to be called when the `URLSessionTask` is available.
  734. ///
  735. /// - Returns: The instance.
  736. @preconcurrency
  737. @discardableResult
  738. public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping @Sendable (URLSessionTask) -> Void) -> Self {
  739. mutableState.write { state in
  740. if let task = state.tasks.last {
  741. queue.async { handler(task) }
  742. }
  743. state.urlSessionTaskHandler = (queue, handler)
  744. }
  745. return self
  746. }
  747. // MARK: Cleanup
  748. /// Adds a `finishHandler` closure to be called when the request completes.
  749. ///
  750. /// - Parameter closure: Closure to be called when the request finishes.
  751. func onFinish(perform finishHandler: @escaping () -> Void) {
  752. let shouldImmediatelyExecute = mutableState.write { mutableState in
  753. if mutableState.state == .finished {
  754. return true
  755. } else {
  756. mutableState.finishHandlers.append(finishHandler)
  757. return false
  758. }
  759. }
  760. if shouldImmediatelyExecute {
  761. finishHandler()
  762. }
  763. }
  764. /// Final cleanup step executed when the instance finishes response serialization.
  765. func cleanup() {
  766. let finishHandlers = mutableState.write { mutableState in
  767. let handlers = mutableState.finishHandlers
  768. mutableState.finishHandlers.removeAll()
  769. return handlers
  770. }
  771. finishHandlers.forEach { $0() }
  772. delegate?.cleanup(after: self)
  773. }
  774. }
  775. extension Request {
  776. /// Type indicating how a `DataRequest` or `DataStreamRequest` should proceed after receiving an `HTTPURLResponse`.
  777. public enum ResponseDisposition: Sendable {
  778. /// Allow the request to continue normally.
  779. case allow
  780. /// Cancel the request, similar to calling `cancel()`.
  781. case cancel
  782. var sessionDisposition: URLSession.ResponseDisposition {
  783. switch self {
  784. case .allow: .allow
  785. case .cancel: .cancel
  786. }
  787. }
  788. }
  789. }
  790. // MARK: - Protocol Conformances
  791. extension Request: Equatable {
  792. public static func ==(lhs: Request, rhs: Request) -> Bool {
  793. lhs.id == rhs.id
  794. }
  795. }
  796. extension Request: Hashable {
  797. public func hash(into hasher: inout Hasher) {
  798. hasher.combine(id)
  799. }
  800. }
  801. extension Request: CustomStringConvertible {
  802. /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
  803. /// created, as well as the response status code, if a response has been received.
  804. public var description: String {
  805. guard let request = performedRequests.last ?? lastRequest,
  806. let url = request.url,
  807. let method = request.httpMethod else { return "No request created yet." }
  808. let requestDescription = "\(method) \(url.absoluteString)"
  809. return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
  810. }
  811. }
  812. extension Request {
  813. /// cURL representation of the instance.
  814. ///
  815. /// - Returns: The cURL equivalent of the instance.
  816. public func cURLDescription() -> String {
  817. guard
  818. let request = lastRequest,
  819. let url = request.url,
  820. let host = url.host,
  821. let method = request.httpMethod else { return "$ curl command could not be created" }
  822. var components = ["$ curl -v"]
  823. components.append("-X \(method)")
  824. if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
  825. let protectionSpace = URLProtectionSpace(host: host,
  826. port: url.port ?? 0,
  827. protocol: url.scheme,
  828. realm: host,
  829. authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  830. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  831. for credential in credentials {
  832. guard let user = credential.user, let password = credential.password else { continue }
  833. components.append("-u \(user):\(password)")
  834. }
  835. } else {
  836. if let credential, let user = credential.user, let password = credential.password {
  837. components.append("-u \(user):\(password)")
  838. }
  839. }
  840. }
  841. if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
  842. if
  843. let cookieStorage = configuration.httpCookieStorage,
  844. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty {
  845. let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
  846. components.append("-b \"\(allCookies)\"")
  847. }
  848. }
  849. var headers = HTTPHeaders()
  850. if let sessionHeaders = delegate?.sessionConfiguration.headers {
  851. for header in sessionHeaders where header.name != "Cookie" {
  852. headers[header.name] = header.value
  853. }
  854. }
  855. for header in request.headers where header.name != "Cookie" {
  856. headers[header.name] = header.value
  857. }
  858. for header in headers {
  859. let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"")
  860. components.append("-H \"\(header.name): \(escapedValue)\"")
  861. }
  862. if let httpBodyData = request.httpBody {
  863. let httpBody = String(decoding: httpBodyData, as: UTF8.self)
  864. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  865. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  866. components.append("-d \"\(escapedBody)\"")
  867. }
  868. components.append("\"\(url.absoluteString)\"")
  869. return components.joined(separator: " \\\n\t")
  870. }
  871. }
  872. /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
  873. public protocol RequestDelegate: AnyObject, Sendable {
  874. /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s.
  875. var sessionConfiguration: URLSessionConfiguration { get }
  876. /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler.
  877. var startImmediately: Bool { get }
  878. /// Notifies the delegate the `Request` has reached a point where it needs cleanup.
  879. ///
  880. /// - Parameter request: The `Request` to cleanup after.
  881. func cleanup(after request: Request)
  882. /// Asynchronously ask the delegate whether a `Request` will be retried.
  883. ///
  884. /// - Parameters:
  885. /// - request: `Request` which failed.
  886. /// - error: `Error` which produced the failure.
  887. /// - completion: Closure taking the `RetryResult` for evaluation.
  888. func retryResult(for request: Request, dueTo error: AFError, completion: @escaping @Sendable (RetryResult) -> Void)
  889. /// Asynchronously retry the `Request`.
  890. ///
  891. /// - Parameters:
  892. /// - request: `Request` which will be retried.
  893. /// - timeDelay: `TimeInterval` after which the retry will be triggered.
  894. func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
  895. }