Request.swift 50 KB

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