Request.swift 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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 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.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.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: (any 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: (any 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: (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. self.error = self.error ?? error
  385. let validators = validators.read { $0 }
  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. guard !mutableState.isFinishing else { return }
  421. mutableState.isFinishing = true
  422. if let error { self.error = error }
  423. // Start response handlers
  424. processNextResponseSerializer()
  425. eventMonitor?.requestDidFinish(self)
  426. }
  427. /// Appends the response serialization closure to the instance.
  428. ///
  429. /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`.
  430. ///
  431. /// - Parameter closure: The closure containing the response serialization call.
  432. func appendResponseSerializer(_ closure: @escaping @Sendable () -> Void) {
  433. mutableState.write { mutableState in
  434. mutableState.responseSerializers.append(closure)
  435. if mutableState.state == .finished {
  436. mutableState.state = .resumed
  437. }
  438. if mutableState.responseSerializerProcessingFinished {
  439. underlyingQueue.async { self.processNextResponseSerializer() }
  440. }
  441. if mutableState.state.canTransitionTo(.resumed) {
  442. underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } }
  443. }
  444. }
  445. }
  446. /// Returns the next response serializer closure to execute if there's one left.
  447. ///
  448. /// - Returns: The next response serialization closure, if there is one.
  449. func nextResponseSerializer() -> (@Sendable () -> Void)? {
  450. var responseSerializer: (@Sendable () -> Void)?
  451. mutableState.write { mutableState in
  452. let responseSerializerIndex = mutableState.responseSerializerCompletions.count
  453. if responseSerializerIndex < mutableState.responseSerializers.count {
  454. responseSerializer = mutableState.responseSerializers[responseSerializerIndex]
  455. }
  456. }
  457. return responseSerializer
  458. }
  459. /// Processes the next response serializer and calls all completions if response serialization is complete.
  460. func processNextResponseSerializer() {
  461. guard let responseSerializer = nextResponseSerializer() else {
  462. // Execute all response serializer completions and clear them
  463. var completions: [@Sendable () -> Void] = []
  464. mutableState.write { mutableState in
  465. completions = mutableState.responseSerializerCompletions
  466. // Clear out all response serializers and response serializer completions in mutable state since the
  467. // request is complete. It's important to do this prior to calling the completion closures in case
  468. // the completions call back into the request triggering a re-processing of the response serializers.
  469. // An example of how this can happen is by calling cancel inside a response completion closure.
  470. mutableState.responseSerializers.removeAll()
  471. mutableState.responseSerializerCompletions.removeAll()
  472. if mutableState.state.canTransitionTo(.finished) {
  473. mutableState.state = .finished
  474. }
  475. mutableState.responseSerializerProcessingFinished = true
  476. mutableState.isFinishing = false
  477. }
  478. completions.forEach { $0() }
  479. // Cleanup the request
  480. cleanup()
  481. return
  482. }
  483. serializationQueue.async { responseSerializer() }
  484. }
  485. /// Notifies the `Request` that the response serializer is complete.
  486. ///
  487. /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers
  488. /// are complete.
  489. func responseSerializerDidComplete(completion: @escaping @Sendable () -> Void) {
  490. mutableState.write { $0.responseSerializerCompletions.append(completion) }
  491. processNextResponseSerializer()
  492. }
  493. /// Resets all task and response serializer related state for retry.
  494. func reset() {
  495. error = nil
  496. uploadProgress.totalUnitCount = 0
  497. uploadProgress.completedUnitCount = 0
  498. downloadProgress.totalUnitCount = 0
  499. downloadProgress.completedUnitCount = 0
  500. mutableState.write { state in
  501. state.isFinishing = false
  502. state.responseSerializerCompletions = []
  503. }
  504. }
  505. /// Called when updating the upload progress.
  506. ///
  507. /// - Parameters:
  508. /// - totalBytesSent: Total bytes sent so far.
  509. /// - totalBytesExpectedToSend: Total bytes expected to send.
  510. func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  511. uploadProgress.totalUnitCount = totalBytesExpectedToSend
  512. uploadProgress.completedUnitCount = totalBytesSent
  513. uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
  514. }
  515. /// Perform a closure on the current `state` while locked.
  516. ///
  517. /// - Parameter perform: The closure to perform.
  518. func withState(perform: (State) -> Void) {
  519. mutableState.withState(perform: perform)
  520. }
  521. // MARK: Task Creation
  522. /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
  523. ///
  524. /// - Parameters:
  525. /// - request: `URLRequest` to use to create the `URLSessionTask`.
  526. /// - session: `URLSession` which creates the `URLSessionTask`.
  527. ///
  528. /// - Returns: The `URLSessionTask` created.
  529. func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  530. fatalError("Subclasses must override.")
  531. }
  532. // MARK: - Public API
  533. // These APIs are callable from any queue.
  534. // MARK: State
  535. /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended.
  536. ///
  537. /// - Returns: The instance.
  538. @discardableResult
  539. public func cancel() -> Self {
  540. mutableState.write { mutableState in
  541. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  542. mutableState.state = .cancelled
  543. underlyingQueue.async { self.didCancel() }
  544. guard let task = mutableState.tasks.last, task.state != .completed else {
  545. underlyingQueue.async { self.finish() }
  546. return
  547. }
  548. // Resume to ensure metrics are gathered.
  549. task.resume()
  550. task.cancel()
  551. underlyingQueue.async { self.didCancelTask(task) }
  552. }
  553. return self
  554. }
  555. /// Suspends the instance.
  556. ///
  557. /// - Returns: The instance.
  558. @discardableResult
  559. public func suspend() -> Self {
  560. mutableState.write { mutableState in
  561. guard mutableState.state.canTransitionTo(.suspended) else { return }
  562. mutableState.state = .suspended
  563. underlyingQueue.async { self.didSuspend() }
  564. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  565. task.suspend()
  566. underlyingQueue.async { self.didSuspendTask(task) }
  567. }
  568. return self
  569. }
  570. /// Resumes the instance.
  571. ///
  572. /// - Returns: The instance.
  573. @discardableResult
  574. public func resume() -> Self {
  575. mutableState.write { mutableState in
  576. guard mutableState.state.canTransitionTo(.resumed) else { return }
  577. mutableState.state = .resumed
  578. underlyingQueue.async { self.didResume() }
  579. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  580. task.resume()
  581. underlyingQueue.async { self.didResumeTask(task) }
  582. }
  583. return self
  584. }
  585. // MARK: - Closure API
  586. /// Associates a credential using the provided values with the instance.
  587. ///
  588. /// - Parameters:
  589. /// - username: The username.
  590. /// - password: The password.
  591. /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default.
  592. ///
  593. /// - Returns: The instance.
  594. @discardableResult
  595. public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
  596. let credential = URLCredential(user: username, password: password, persistence: persistence)
  597. return authenticate(with: credential)
  598. }
  599. /// Associates the provided credential with the instance.
  600. ///
  601. /// - Parameter credential: The `URLCredential`.
  602. ///
  603. /// - Returns: The instance.
  604. @discardableResult
  605. public func authenticate(with credential: URLCredential) -> Self {
  606. mutableState.credential = credential
  607. return self
  608. }
  609. /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server.
  610. ///
  611. /// - Note: Only the last closure provided is used.
  612. ///
  613. /// - Parameters:
  614. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  615. /// - closure: The closure to be executed periodically as data is read from the server.
  616. ///
  617. /// - Returns: The instance.
  618. @preconcurrency
  619. @discardableResult
  620. public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  621. mutableState.downloadProgressHandler = (handler: closure, queue: queue)
  622. return self
  623. }
  624. /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.
  625. ///
  626. /// - Note: Only the last closure provided is used.
  627. ///
  628. /// - Parameters:
  629. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  630. /// - closure: The closure to be executed periodically as data is sent to the server.
  631. ///
  632. /// - Returns: The instance.
  633. @preconcurrency
  634. @discardableResult
  635. public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  636. mutableState.uploadProgressHandler = (handler: closure, queue: queue)
  637. return self
  638. }
  639. // MARK: Redirects
  640. /// Sets the redirect handler for the instance which will be used if a redirect response is encountered.
  641. ///
  642. /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash.
  643. ///
  644. /// - Parameter handler: The `RedirectHandler`.
  645. ///
  646. /// - Returns: The instance.
  647. @preconcurrency
  648. @discardableResult
  649. public func redirect(using handler: any RedirectHandler) -> Self {
  650. mutableState.write { mutableState in
  651. precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.")
  652. mutableState.redirectHandler = handler
  653. }
  654. return self
  655. }
  656. // MARK: Cached Responses
  657. /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response.
  658. ///
  659. /// - Note: Attempting to set the cache handler more than once is a logic error and will crash.
  660. ///
  661. /// - Parameter handler: The `CachedResponseHandler`.
  662. ///
  663. /// - Returns: The instance.
  664. @preconcurrency
  665. @discardableResult
  666. public func cacheResponse(using handler: any CachedResponseHandler) -> Self {
  667. mutableState.write { mutableState in
  668. precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.")
  669. mutableState.cachedResponseHandler = handler
  670. }
  671. return self
  672. }
  673. // MARK: - Lifetime APIs
  674. /// Sets a handler to be called when the cURL description of the request is available.
  675. ///
  676. /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
  677. ///
  678. /// - Parameters:
  679. /// - queue: `DispatchQueue` on which `handler` will be called.
  680. /// - handler: Closure to be called when the cURL description is available.
  681. ///
  682. /// - Returns: The instance.
  683. @preconcurrency
  684. @discardableResult
  685. public func cURLDescription(on queue: DispatchQueue, calling handler: @escaping @Sendable (String) -> Void) -> Self {
  686. mutableState.write { mutableState in
  687. if mutableState.requests.last != nil {
  688. queue.async { handler(self.cURLDescription()) }
  689. } else {
  690. mutableState.cURLHandler = (queue, handler)
  691. }
  692. }
  693. return self
  694. }
  695. /// Sets a handler to be called when the cURL description of the request is available.
  696. ///
  697. /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
  698. ///
  699. /// - Parameter handler: Closure to be called when the cURL description is available. Called on the instance's
  700. /// `underlyingQueue` by default.
  701. ///
  702. /// - Returns: The instance.
  703. @preconcurrency
  704. @discardableResult
  705. public func cURLDescription(calling handler: @escaping @Sendable (String) -> Void) -> Self {
  706. cURLDescription(on: underlyingQueue, calling: handler)
  707. return self
  708. }
  709. /// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance.
  710. ///
  711. /// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried.
  712. ///
  713. /// - Parameters:
  714. /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
  715. /// - handler: Closure to be called when a `URLRequest` is available.
  716. ///
  717. /// - Returns: The instance.
  718. @preconcurrency
  719. @discardableResult
  720. public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping @Sendable (URLRequest) -> Void) -> Self {
  721. mutableState.write { state in
  722. if let request = state.requests.last {
  723. queue.async { handler(request) }
  724. }
  725. state.urlRequestHandler = (queue, handler)
  726. }
  727. return self
  728. }
  729. /// Sets a closure to be called whenever the instance creates a `URLSessionTask`.
  730. ///
  731. /// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It
  732. /// **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features.
  733. /// Additionally, this closure may be called multiple times if the instance is retried.
  734. ///
  735. /// - Parameters:
  736. /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
  737. /// - handler: Closure to be called when the `URLSessionTask` is available.
  738. ///
  739. /// - Returns: The instance.
  740. @preconcurrency
  741. @discardableResult
  742. public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping @Sendable (URLSessionTask) -> Void) -> Self {
  743. mutableState.write { state in
  744. if let task = state.tasks.last {
  745. queue.async { handler(task) }
  746. }
  747. state.urlSessionTaskHandler = (queue, handler)
  748. }
  749. return self
  750. }
  751. // MARK: Cleanup
  752. /// Adds a `finishHandler` closure to be called when the request completes.
  753. ///
  754. /// - Parameter closure: Closure to be called when the request finishes.
  755. func onFinish(perform finishHandler: @escaping () -> Void) {
  756. guard !isFinished else { finishHandler(); return }
  757. mutableState.write { state in
  758. state.finishHandlers.append(finishHandler)
  759. }
  760. }
  761. /// Final cleanup step executed when the instance finishes response serialization.
  762. func cleanup() {
  763. let handlers = mutableState.finishHandlers
  764. handlers.forEach { $0() }
  765. mutableState.write { state in
  766. state.finishHandlers.removeAll()
  767. }
  768. delegate?.cleanup(after: self)
  769. }
  770. }
  771. extension Request {
  772. /// Type indicating how a `DataRequest` or `DataStreamRequest` should proceed after receiving an `HTTPURLResponse`.
  773. public enum ResponseDisposition: Sendable {
  774. /// Allow the request to continue normally.
  775. case allow
  776. /// Cancel the request, similar to calling `cancel()`.
  777. case cancel
  778. var sessionDisposition: URLSession.ResponseDisposition {
  779. switch self {
  780. case .allow: .allow
  781. case .cancel: .cancel
  782. }
  783. }
  784. }
  785. }
  786. // MARK: - Protocol Conformances
  787. extension Request: Equatable {
  788. public static func ==(lhs: Request, rhs: Request) -> Bool {
  789. lhs.id == rhs.id
  790. }
  791. }
  792. extension Request: Hashable {
  793. public func hash(into hasher: inout Hasher) {
  794. hasher.combine(id)
  795. }
  796. }
  797. extension Request: CustomStringConvertible {
  798. /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
  799. /// created, as well as the response status code, if a response has been received.
  800. public var description: String {
  801. guard let request = performedRequests.last ?? lastRequest,
  802. let url = request.url,
  803. let method = request.httpMethod else { return "No request created yet." }
  804. let requestDescription = "\(method) \(url.absoluteString)"
  805. return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
  806. }
  807. }
  808. extension Request {
  809. /// cURL representation of the instance.
  810. ///
  811. /// - Returns: The cURL equivalent of the instance.
  812. public func cURLDescription() -> String {
  813. guard
  814. let request = lastRequest,
  815. let url = request.url,
  816. let host = url.host,
  817. let method = request.httpMethod else { return "$ curl command could not be created" }
  818. var components = ["$ curl -v"]
  819. components.append("-X \(method)")
  820. if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
  821. let protectionSpace = URLProtectionSpace(host: host,
  822. port: url.port ?? 0,
  823. protocol: url.scheme,
  824. realm: host,
  825. authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  826. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  827. for credential in credentials {
  828. guard let user = credential.user, let password = credential.password else { continue }
  829. components.append("-u \(user):\(password)")
  830. }
  831. } else {
  832. if let credential, let user = credential.user, let password = credential.password {
  833. components.append("-u \(user):\(password)")
  834. }
  835. }
  836. }
  837. if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
  838. if
  839. let cookieStorage = configuration.httpCookieStorage,
  840. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty {
  841. let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
  842. components.append("-b \"\(allCookies)\"")
  843. }
  844. }
  845. var headers = HTTPHeaders()
  846. if let sessionHeaders = delegate?.sessionConfiguration.headers {
  847. for header in sessionHeaders where header.name != "Cookie" {
  848. headers[header.name] = header.value
  849. }
  850. }
  851. for header in request.headers where header.name != "Cookie" {
  852. headers[header.name] = header.value
  853. }
  854. for header in headers {
  855. let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"")
  856. components.append("-H \"\(header.name): \(escapedValue)\"")
  857. }
  858. if let httpBodyData = request.httpBody {
  859. let httpBody = String(decoding: httpBodyData, as: UTF8.self)
  860. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  861. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  862. components.append("-d \"\(escapedBody)\"")
  863. }
  864. components.append("\"\(url.absoluteString)\"")
  865. return components.joined(separator: " \\\n\t")
  866. }
  867. }
  868. /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
  869. public protocol RequestDelegate: AnyObject, Sendable {
  870. /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s.
  871. var sessionConfiguration: URLSessionConfiguration { get }
  872. /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler.
  873. var startImmediately: Bool { get }
  874. /// Notifies the delegate the `Request` has reached a point where it needs cleanup.
  875. ///
  876. /// - Parameter request: The `Request` to cleanup after.
  877. func cleanup(after request: Request)
  878. /// Asynchronously ask the delegate whether a `Request` will be retried.
  879. ///
  880. /// - Parameters:
  881. /// - request: `Request` which failed.
  882. /// - error: `Error` which produced the failure.
  883. /// - completion: Closure taking the `RetryResult` for evaluation.
  884. func retryResult(for request: Request, dueTo error: AFError, completion: @escaping @Sendable (RetryResult) -> Void)
  885. /// Asynchronously retry the `Request`.
  886. ///
  887. /// - Parameters:
  888. /// - request: `Request` which will be retried.
  889. /// - timeDelay: `TimeInterval` after which the retry will be triggered.
  890. func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
  891. }