Request.swift 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066
  1. //
  2. // Request.swift
  3. //
  4. // Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback
  26. /// handling.
  27. public class Request {
  28. /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or
  29. /// `cancel()` on the `Request`.
  30. public enum State {
  31. /// Initial state of the `Request`.
  32. case initialized
  33. /// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on
  34. /// them in this state.
  35. case resumed
  36. /// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on
  37. /// them in this state.
  38. case suspended
  39. /// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on
  40. /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition
  41. /// to any other state.
  42. case cancelled
  43. /// `State` set when all response serialization completion closures have been cleared on the `Request` and
  44. /// enqueued on their respective queues.
  45. case finished
  46. /// Determines whether `self` can be transitioned to the provided `State`.
  47. func canTransitionTo(_ state: State) -> Bool {
  48. switch (self, state) {
  49. case (.initialized, _):
  50. return true
  51. case (_, .initialized), (.cancelled, _), (.finished, _):
  52. return false
  53. case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed):
  54. return true
  55. case (.suspended, .suspended), (.resumed, .resumed):
  56. return false
  57. case (_, .finished):
  58. return true
  59. }
  60. }
  61. }
  62. // MARK: - Initial State
  63. /// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances.
  64. public let id: UUID
  65. /// The serial queue for all internal async actions.
  66. public let underlyingQueue: DispatchQueue
  67. /// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`.
  68. public let serializationQueue: DispatchQueue
  69. /// `EventMonitor` used for event callbacks.
  70. public let eventMonitor: EventMonitor?
  71. /// The `Request`'s interceptor.
  72. public let interceptor: RequestInterceptor?
  73. /// The `Request`'s delegate.
  74. public private(set) weak var delegate: RequestDelegate?
  75. // MARK: - Mutable State
  76. /// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`.
  77. struct MutableState {
  78. /// State of the `Request`.
  79. var state: State = .initialized
  80. /// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks.
  81. var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
  82. /// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks.
  83. var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
  84. /// `RedirectHandler` provided for to handle request redirection.
  85. var redirectHandler: RedirectHandler?
  86. /// `CachedResponseHandler` provided to handle response caching.
  87. var cachedResponseHandler: CachedResponseHandler?
  88. /// Queue and closure called when the `Request` is able to create a cURL description of itself.
  89. var cURLHandler: (queue: DispatchQueue, handler: (String) -> Void)?
  90. /// Queue and closure called when the `Request` creates a `URLRequest`.
  91. var urlRequestHandler: (queue: DispatchQueue, handler: (URLRequest) -> Void)?
  92. /// Queue and closure called when the `Request` creates a `URLSessionTask`.
  93. var urlSessionTaskHandler: (queue: DispatchQueue, handler: (URLSessionTask) -> Void)?
  94. /// Response serialization closures that handle response parsing.
  95. var responseSerializers: [() -> Void] = []
  96. /// Response serialization completion closures executed once all response serializers are complete.
  97. var responseSerializerCompletions: [() -> Void] = []
  98. /// Whether response serializer processing is finished.
  99. var responseSerializerProcessingFinished = false
  100. /// `URLCredential` used for authentication challenges.
  101. var credential: URLCredential?
  102. /// All `URLRequest`s created by Alamofire on behalf of the `Request`.
  103. var requests: [URLRequest] = []
  104. /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`.
  105. var tasks: [URLSessionTask] = []
  106. /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond
  107. /// exactly the the `tasks` created.
  108. var metrics: [URLSessionTaskMetrics] = []
  109. /// Number of times any retriers provided retried the `Request`.
  110. var retryCount = 0
  111. /// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`.
  112. var error: AFError?
  113. /// Whether the instance has had `finish()` called and is running the serializers. Should be replaced with a
  114. /// representation in the state machine in the future.
  115. var isFinishing = false
  116. /// Actions to run when requests are finished. Use for concurrency support.
  117. var finishHandlers: [() -> Void] = []
  118. }
  119. /// Protected `MutableState` value that provides thread-safe access to state values.
  120. fileprivate let mutableState = Protected(MutableState())
  121. /// `State` of the `Request`.
  122. public var state: State { mutableState.state }
  123. /// Returns whether `state` is `.initialized`.
  124. public var isInitialized: Bool { state == .initialized }
  125. /// Returns whether `state is `.resumed`.
  126. public var isResumed: Bool { state == .resumed }
  127. /// Returns whether `state` is `.suspended`.
  128. public var isSuspended: Bool { state == .suspended }
  129. /// Returns whether `state` is `.cancelled`.
  130. public var isCancelled: Bool { state == .cancelled }
  131. /// Returns whether `state` is `.finished`.
  132. public var isFinished: Bool { state == .finished }
  133. // MARK: Progress
  134. /// Closure type executed when monitoring the upload or download progress of a request.
  135. public typealias ProgressHandler = (Progress) -> Void
  136. /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried.
  137. public let uploadProgress = Progress(totalUnitCount: 0)
  138. /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried.
  139. public let downloadProgress = Progress(totalUnitCount: 0)
  140. /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`.
  141. private 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. fileprivate 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 private(set) var redirectHandler: RedirectHandler? {
  153. get { mutableState.redirectHandler }
  154. set { mutableState.redirectHandler = newValue }
  155. }
  156. // MARK: Cached Response Handling
  157. /// `CachedResponseHandler` set on the instance.
  158. public private(set) var cachedResponseHandler: CachedResponseHandler? {
  159. get { mutableState.cachedResponseHandler }
  160. set { mutableState.cachedResponseHandler = newValue }
  161. }
  162. // MARK: URLCredential
  163. /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods.
  164. public private(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. fileprivate let validators = Protected<[() -> Void]>([])
  171. // MARK: URLRequests
  172. /// All `URLRequests` 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 fileprivate(set) var error: AFError? {
  211. get { mutableState.error }
  212. set { mutableState.error = newValue }
  213. }
  214. /// Default initializer for the `Request` superclass.
  215. ///
  216. /// - Parameters:
  217. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  218. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  219. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  220. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  221. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  222. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  223. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  224. init(id: UUID = UUID(),
  225. underlyingQueue: DispatchQueue,
  226. serializationQueue: DispatchQueue,
  227. eventMonitor: EventMonitor?,
  228. interceptor: RequestInterceptor?,
  229. delegate: RequestDelegate) {
  230. self.id = id
  231. self.underlyingQueue = underlyingQueue
  232. self.serializationQueue = serializationQueue
  233. self.eventMonitor = eventMonitor
  234. self.interceptor = interceptor
  235. self.delegate = delegate
  236. }
  237. // MARK: - Internal Event API
  238. // All API must be called from underlyingQueue.
  239. /// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active,
  240. /// the `URLRequest` will be adapted before being issued.
  241. ///
  242. /// - Parameter request: The `URLRequest` created.
  243. func didCreateInitialURLRequest(_ request: URLRequest) {
  244. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  245. mutableState.write { $0.requests.append(request) }
  246. eventMonitor?.request(self, didCreateInitialURLRequest: request)
  247. }
  248. /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`.
  249. ///
  250. /// - Note: Triggers retry.
  251. ///
  252. /// - Parameter error: `AFError` thrown from the failed creation.
  253. func didFailToCreateURLRequest(with error: AFError) {
  254. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  255. self.error = error
  256. eventMonitor?.request(self, didFailToCreateURLRequestWithError: error)
  257. callCURLHandlerIfNecessary()
  258. retryOrFinish(error: error)
  259. }
  260. /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`.
  261. ///
  262. /// - Parameters:
  263. /// - initialRequest: The `URLRequest` that was adapted.
  264. /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`.
  265. func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) {
  266. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  267. mutableState.write { $0.requests.append(adaptedRequest) }
  268. eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest)
  269. }
  270. /// Called when a `RequestAdapter` fails to adapt a `URLRequest`.
  271. ///
  272. /// - Note: Triggers retry.
  273. ///
  274. /// - Parameters:
  275. /// - request: The `URLRequest` the adapter was called with.
  276. /// - error: The `AFError` returned by the `RequestAdapter`.
  277. func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) {
  278. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  279. self.error = error
  280. eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error)
  281. callCURLHandlerIfNecessary()
  282. retryOrFinish(error: error)
  283. }
  284. /// Final `URLRequest` has been created for the instance.
  285. ///
  286. /// - Parameter request: The `URLRequest` created.
  287. func didCreateURLRequest(_ request: URLRequest) {
  288. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  289. mutableState.read { state in
  290. state.urlRequestHandler?.queue.async { state.urlRequestHandler?.handler(request) }
  291. }
  292. eventMonitor?.request(self, didCreateURLRequest: request)
  293. callCURLHandlerIfNecessary()
  294. }
  295. /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`.
  296. private func callCURLHandlerIfNecessary() {
  297. mutableState.write { mutableState in
  298. guard let cURLHandler = mutableState.cURLHandler else { return }
  299. cURLHandler.queue.async { cURLHandler.handler(self.cURLDescription()) }
  300. mutableState.cURLHandler = nil
  301. }
  302. }
  303. /// Called when a `URLSessionTask` is created on behalf of the instance.
  304. ///
  305. /// - Parameter task: The `URLSessionTask` created.
  306. func didCreateTask(_ task: URLSessionTask) {
  307. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  308. mutableState.write { state in
  309. state.tasks.append(task)
  310. guard let urlSessionTaskHandler = state.urlSessionTaskHandler else { return }
  311. urlSessionTaskHandler.queue.async { urlSessionTaskHandler.handler(task) }
  312. }
  313. eventMonitor?.request(self, didCreateTask: task)
  314. }
  315. /// Called when resumption is completed.
  316. func didResume() {
  317. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  318. eventMonitor?.requestDidResume(self)
  319. }
  320. /// Called when a `URLSessionTask` is resumed on behalf of the instance.
  321. ///
  322. /// - Parameter task: The `URLSessionTask` resumed.
  323. func didResumeTask(_ task: URLSessionTask) {
  324. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  325. eventMonitor?.request(self, didResumeTask: task)
  326. }
  327. /// Called when suspension is completed.
  328. func didSuspend() {
  329. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  330. eventMonitor?.requestDidSuspend(self)
  331. }
  332. /// Called when a `URLSessionTask` is suspended on behalf of the instance.
  333. ///
  334. /// - Parameter task: The `URLSessionTask` suspended.
  335. func didSuspendTask(_ task: URLSessionTask) {
  336. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  337. eventMonitor?.request(self, didSuspendTask: task)
  338. }
  339. /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`.
  340. func didCancel() {
  341. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  342. mutableState.write { mutableState in
  343. mutableState.error = mutableState.error ?? AFError.explicitlyCancelled
  344. }
  345. eventMonitor?.requestDidCancel(self)
  346. }
  347. /// Called when a `URLSessionTask` is cancelled on behalf of the instance.
  348. ///
  349. /// - Parameter task: The `URLSessionTask` cancelled.
  350. func didCancelTask(_ task: URLSessionTask) {
  351. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  352. eventMonitor?.request(self, didCancelTask: task)
  353. }
  354. /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance.
  355. ///
  356. /// - Parameter metrics: The `URLSessionTaskMetrics` gathered.
  357. func didGatherMetrics(_ metrics: URLSessionTaskMetrics) {
  358. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  359. mutableState.write { $0.metrics.append(metrics) }
  360. eventMonitor?.request(self, didGatherMetrics: metrics)
  361. }
  362. /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning.
  363. ///
  364. /// - Parameters:
  365. /// - task: The `URLSessionTask` which failed.
  366. /// - error: The early failure `AFError`.
  367. func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) {
  368. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  369. self.error = error
  370. // Task will still complete, so didCompleteTask(_:with:) will handle retry.
  371. eventMonitor?.request(self, didFailTask: task, earlyWithError: error)
  372. }
  373. /// Called when a `URLSessionTask` completes. All tasks will eventually call this method.
  374. ///
  375. /// - Note: Response validation is synchronously triggered in this step.
  376. ///
  377. /// - Parameters:
  378. /// - task: The `URLSessionTask` which completed.
  379. /// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this
  380. /// value is ignored.
  381. func didCompleteTask(_ task: URLSessionTask, with error: AFError?) {
  382. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  383. self.error = self.error ?? error
  384. let validators = validators.read { $0 }
  385. validators.forEach { $0() }
  386. eventMonitor?.request(self, didCompleteTask: task, with: error)
  387. retryOrFinish(error: self.error)
  388. }
  389. /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`.
  390. func prepareForRetry() {
  391. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  392. mutableState.write { $0.retryCount += 1 }
  393. reset()
  394. eventMonitor?.requestIsRetrying(self)
  395. }
  396. /// Called to determine whether retry will be triggered for the particular error, or whether the instance should
  397. /// call `finish()`.
  398. ///
  399. /// - Parameter error: The possible `AFError` which may trigger retry.
  400. func retryOrFinish(error: AFError?) {
  401. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  402. guard !isCancelled, let error = error, let delegate = delegate else { finish(); return }
  403. delegate.retryResult(for: self, dueTo: error) { retryResult in
  404. switch retryResult {
  405. case .doNotRetry:
  406. self.finish()
  407. case let .doNotRetryWithError(retryError):
  408. self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
  409. case .retry, .retryWithDelay:
  410. delegate.retryRequest(self, withDelay: retryResult.delay)
  411. }
  412. }
  413. }
  414. /// Finishes this `Request` and starts the response serializers.
  415. ///
  416. /// - Parameter error: The possible `Error` with which the instance will finish.
  417. func finish(error: AFError? = nil) {
  418. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  419. guard !mutableState.isFinishing else { return }
  420. mutableState.isFinishing = true
  421. if let error = error { self.error = error }
  422. // Start response handlers
  423. processNextResponseSerializer()
  424. eventMonitor?.requestDidFinish(self)
  425. }
  426. /// Appends the response serialization closure to the instance.
  427. ///
  428. /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`.
  429. ///
  430. /// - Parameter closure: The closure containing the response serialization call.
  431. func appendResponseSerializer(_ closure: @escaping () -> Void) {
  432. mutableState.write { mutableState in
  433. mutableState.responseSerializers.append(closure)
  434. if mutableState.state == .finished {
  435. mutableState.state = .resumed
  436. }
  437. if mutableState.responseSerializerProcessingFinished {
  438. underlyingQueue.async { self.processNextResponseSerializer() }
  439. }
  440. if mutableState.state.canTransitionTo(.resumed) {
  441. underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } }
  442. }
  443. }
  444. }
  445. /// Returns the next response serializer closure to execute if there's one left.
  446. ///
  447. /// - Returns: The next response serialization closure, if there is one.
  448. func nextResponseSerializer() -> (() -> Void)? {
  449. var responseSerializer: (() -> Void)?
  450. mutableState.write { mutableState in
  451. let responseSerializerIndex = mutableState.responseSerializerCompletions.count
  452. if responseSerializerIndex < mutableState.responseSerializers.count {
  453. responseSerializer = mutableState.responseSerializers[responseSerializerIndex]
  454. }
  455. }
  456. return responseSerializer
  457. }
  458. /// Processes the next response serializer and calls all completions if response serialization is complete.
  459. func processNextResponseSerializer() {
  460. guard let responseSerializer = nextResponseSerializer() else {
  461. // Execute all response serializer completions and clear them
  462. var completions: [() -> Void] = []
  463. mutableState.write { mutableState in
  464. completions = mutableState.responseSerializerCompletions
  465. // Clear out all response serializers and response serializer completions in mutable state since the
  466. // request is complete. It's important to do this prior to calling the completion closures in case
  467. // the completions call back into the request triggering a re-processing of the response serializers.
  468. // An example of how this can happen is by calling cancel inside a response completion closure.
  469. mutableState.responseSerializers.removeAll()
  470. mutableState.responseSerializerCompletions.removeAll()
  471. if mutableState.state.canTransitionTo(.finished) {
  472. mutableState.state = .finished
  473. }
  474. mutableState.responseSerializerProcessingFinished = true
  475. mutableState.isFinishing = false
  476. }
  477. completions.forEach { $0() }
  478. // Cleanup the request
  479. cleanup()
  480. return
  481. }
  482. serializationQueue.async { responseSerializer() }
  483. }
  484. /// Notifies the `Request` that the response serializer is complete.
  485. ///
  486. /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers
  487. /// are complete.
  488. func responseSerializerDidComplete(completion: @escaping () -> Void) {
  489. mutableState.write { $0.responseSerializerCompletions.append(completion) }
  490. processNextResponseSerializer()
  491. }
  492. /// Resets all task and response serializer related state for retry.
  493. func reset() {
  494. error = nil
  495. uploadProgress.totalUnitCount = 0
  496. uploadProgress.completedUnitCount = 0
  497. downloadProgress.totalUnitCount = 0
  498. downloadProgress.completedUnitCount = 0
  499. mutableState.write { state in
  500. state.isFinishing = false
  501. state.responseSerializerCompletions = []
  502. }
  503. }
  504. /// Called when updating the upload progress.
  505. ///
  506. /// - Parameters:
  507. /// - totalBytesSent: Total bytes sent so far.
  508. /// - totalBytesExpectedToSend: Total bytes expected to send.
  509. func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  510. uploadProgress.totalUnitCount = totalBytesExpectedToSend
  511. uploadProgress.completedUnitCount = totalBytesSent
  512. uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
  513. }
  514. /// Perform a closure on the current `state` while locked.
  515. ///
  516. /// - Parameter perform: The closure to perform.
  517. func withState(perform: (State) -> Void) {
  518. mutableState.withState(perform: perform)
  519. }
  520. // MARK: Task Creation
  521. /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
  522. ///
  523. /// - Parameters:
  524. /// - request: `URLRequest` to use to create the `URLSessionTask`.
  525. /// - session: `URLSession` which creates the `URLSessionTask`.
  526. ///
  527. /// - Returns: The `URLSessionTask` created.
  528. func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  529. fatalError("Subclasses must override.")
  530. }
  531. // MARK: - Public API
  532. // These APIs are callable from any queue.
  533. // MARK: State
  534. /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended.
  535. ///
  536. /// - Returns: The instance.
  537. @discardableResult
  538. public func cancel() -> Self {
  539. mutableState.write { mutableState in
  540. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  541. mutableState.state = .cancelled
  542. underlyingQueue.async { self.didCancel() }
  543. guard let task = mutableState.tasks.last, task.state != .completed else {
  544. underlyingQueue.async { self.finish() }
  545. return
  546. }
  547. // Resume to ensure metrics are gathered.
  548. task.resume()
  549. task.cancel()
  550. underlyingQueue.async { self.didCancelTask(task) }
  551. }
  552. return self
  553. }
  554. /// Suspends the instance.
  555. ///
  556. /// - Returns: The instance.
  557. @discardableResult
  558. public func suspend() -> Self {
  559. mutableState.write { mutableState in
  560. guard mutableState.state.canTransitionTo(.suspended) else { return }
  561. mutableState.state = .suspended
  562. underlyingQueue.async { self.didSuspend() }
  563. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  564. task.suspend()
  565. underlyingQueue.async { self.didSuspendTask(task) }
  566. }
  567. return self
  568. }
  569. /// Resumes the instance.
  570. ///
  571. /// - Returns: The instance.
  572. @discardableResult
  573. public func resume() -> Self {
  574. mutableState.write { mutableState in
  575. guard mutableState.state.canTransitionTo(.resumed) else { return }
  576. mutableState.state = .resumed
  577. underlyingQueue.async { self.didResume() }
  578. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  579. task.resume()
  580. underlyingQueue.async { self.didResumeTask(task) }
  581. }
  582. return self
  583. }
  584. // MARK: - Closure API
  585. /// Associates a credential using the provided values with the instance.
  586. ///
  587. /// - Parameters:
  588. /// - username: The username.
  589. /// - password: The password.
  590. /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default.
  591. ///
  592. /// - Returns: The instance.
  593. @discardableResult
  594. public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
  595. let credential = URLCredential(user: username, password: password, persistence: persistence)
  596. return authenticate(with: credential)
  597. }
  598. /// Associates the provided credential with the instance.
  599. ///
  600. /// - Parameter credential: The `URLCredential`.
  601. ///
  602. /// - Returns: The instance.
  603. @discardableResult
  604. public func authenticate(with credential: URLCredential) -> Self {
  605. mutableState.credential = credential
  606. return self
  607. }
  608. /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server.
  609. ///
  610. /// - Note: Only the last closure provided is used.
  611. ///
  612. /// - Parameters:
  613. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  614. /// - closure: The closure to be executed periodically as data is read from the server.
  615. ///
  616. /// - Returns: The instance.
  617. @discardableResult
  618. public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  619. mutableState.downloadProgressHandler = (handler: closure, queue: queue)
  620. return self
  621. }
  622. /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.
  623. ///
  624. /// - Note: Only the last closure provided is used.
  625. ///
  626. /// - Parameters:
  627. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  628. /// - closure: The closure to be executed periodically as data is sent to the server.
  629. ///
  630. /// - Returns: The instance.
  631. @discardableResult
  632. public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  633. mutableState.uploadProgressHandler = (handler: closure, queue: queue)
  634. return self
  635. }
  636. // MARK: Redirects
  637. /// Sets the redirect handler for the instance which will be used if a redirect response is encountered.
  638. ///
  639. /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash.
  640. ///
  641. /// - Parameter handler: The `RedirectHandler`.
  642. ///
  643. /// - Returns: The instance.
  644. @discardableResult
  645. public func redirect(using handler: RedirectHandler) -> Self {
  646. mutableState.write { mutableState in
  647. precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.")
  648. mutableState.redirectHandler = handler
  649. }
  650. return self
  651. }
  652. // MARK: Cached Responses
  653. /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response.
  654. ///
  655. /// - Note: Attempting to set the cache handler more than once is a logic error and will crash.
  656. ///
  657. /// - Parameter handler: The `CachedResponseHandler`.
  658. ///
  659. /// - Returns: The instance.
  660. @discardableResult
  661. public func cacheResponse(using handler: CachedResponseHandler) -> Self {
  662. mutableState.write { mutableState in
  663. precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.")
  664. mutableState.cachedResponseHandler = handler
  665. }
  666. return self
  667. }
  668. // MARK: - Lifetime APIs
  669. /// Sets a handler to be called when the cURL description of the request is available.
  670. ///
  671. /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
  672. ///
  673. /// - Parameters:
  674. /// - queue: `DispatchQueue` on which `handler` will be called.
  675. /// - handler: Closure to be called when the cURL description is available.
  676. ///
  677. /// - Returns: The instance.
  678. @discardableResult
  679. public func cURLDescription(on queue: DispatchQueue, calling handler: @escaping (String) -> Void) -> Self {
  680. mutableState.write { mutableState in
  681. if mutableState.requests.last != nil {
  682. queue.async { handler(self.cURLDescription()) }
  683. } else {
  684. mutableState.cURLHandler = (queue, handler)
  685. }
  686. }
  687. return self
  688. }
  689. /// Sets a handler to be called when the cURL description of the request is available.
  690. ///
  691. /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
  692. ///
  693. /// - Parameter handler: Closure to be called when the cURL description is available. Called on the instance's
  694. /// `underlyingQueue` by default.
  695. ///
  696. /// - Returns: The instance.
  697. @discardableResult
  698. public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self {
  699. cURLDescription(on: underlyingQueue, calling: handler)
  700. return self
  701. }
  702. /// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance.
  703. ///
  704. /// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried.
  705. ///
  706. /// - Parameters:
  707. /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
  708. /// - handler: Closure to be called when a `URLRequest` is available.
  709. ///
  710. /// - Returns: The instance.
  711. @discardableResult
  712. public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLRequest) -> Void) -> Self {
  713. mutableState.write { state in
  714. if let request = state.requests.last {
  715. queue.async { handler(request) }
  716. }
  717. state.urlRequestHandler = (queue, handler)
  718. }
  719. return self
  720. }
  721. /// Sets a closure to be called whenever the instance creates a `URLSessionTask`.
  722. ///
  723. /// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It
  724. /// **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features.
  725. /// Additionally, this closure may be called multiple times if the instance is retried.
  726. ///
  727. /// - Parameters:
  728. /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
  729. /// - handler: Closure to be called when the `URLSessionTask` is available.
  730. ///
  731. /// - Returns: The instance.
  732. @discardableResult
  733. public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLSessionTask) -> Void) -> Self {
  734. mutableState.write { state in
  735. if let task = state.tasks.last {
  736. queue.async { handler(task) }
  737. }
  738. state.urlSessionTaskHandler = (queue, handler)
  739. }
  740. return self
  741. }
  742. // MARK: Cleanup
  743. /// Adds a `finishHandler` closure to be called when the request completes.
  744. ///
  745. /// - Parameter closure: Closure to be called when the request finishes.
  746. func onFinish(perform finishHandler: @escaping () -> Void) {
  747. guard !isFinished else { finishHandler(); return }
  748. mutableState.write { state in
  749. state.finishHandlers.append(finishHandler)
  750. }
  751. }
  752. /// Final cleanup step executed when the instance finishes response serialization.
  753. func cleanup() {
  754. let handlers = mutableState.finishHandlers
  755. handlers.forEach { $0() }
  756. mutableState.write { state in
  757. state.finishHandlers.removeAll()
  758. }
  759. delegate?.cleanup(after: self)
  760. }
  761. }
  762. extension Request {
  763. /// Type indicating how a `DataRequest` or `DataStreamRequest` should proceed after receiving an `HTTPURLResponse`.
  764. public enum ResponseDisposition {
  765. /// Allow the request to continue normally.
  766. case allow
  767. /// Cancel the request, similar to calling `cancel()`.
  768. case cancel
  769. var sessionDisposition: URLSession.ResponseDisposition {
  770. switch self {
  771. case .allow: return .allow
  772. case .cancel: return .cancel
  773. }
  774. }
  775. }
  776. }
  777. // MARK: - Protocol Conformances
  778. extension Request: Equatable {
  779. public static func ==(lhs: Request, rhs: Request) -> Bool {
  780. lhs.id == rhs.id
  781. }
  782. }
  783. extension Request: Hashable {
  784. public func hash(into hasher: inout Hasher) {
  785. hasher.combine(id)
  786. }
  787. }
  788. extension Request: CustomStringConvertible {
  789. /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
  790. /// created, as well as the response status code, if a response has been received.
  791. public var description: String {
  792. guard let request = performedRequests.last ?? lastRequest,
  793. let url = request.url,
  794. let method = request.httpMethod else { return "No request created yet." }
  795. let requestDescription = "\(method) \(url.absoluteString)"
  796. return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
  797. }
  798. }
  799. extension Request {
  800. /// cURL representation of the instance.
  801. ///
  802. /// - Returns: The cURL equivalent of the instance.
  803. public func cURLDescription() -> String {
  804. guard
  805. let request = lastRequest,
  806. let url = request.url,
  807. let host = url.host,
  808. let method = request.httpMethod else { return "$ curl command could not be created" }
  809. var components = ["$ curl -v"]
  810. components.append("-X \(method)")
  811. if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
  812. let protectionSpace = URLProtectionSpace(host: host,
  813. port: url.port ?? 0,
  814. protocol: url.scheme,
  815. realm: host,
  816. authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  817. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  818. for credential in credentials {
  819. guard let user = credential.user, let password = credential.password else { continue }
  820. components.append("-u \(user):\(password)")
  821. }
  822. } else {
  823. if let credential = credential, let user = credential.user, let password = credential.password {
  824. components.append("-u \(user):\(password)")
  825. }
  826. }
  827. }
  828. if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
  829. if
  830. let cookieStorage = configuration.httpCookieStorage,
  831. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty {
  832. let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
  833. components.append("-b \"\(allCookies)\"")
  834. }
  835. }
  836. var headers = HTTPHeaders()
  837. if let sessionHeaders = delegate?.sessionConfiguration.headers {
  838. for header in sessionHeaders where header.name != "Cookie" {
  839. headers[header.name] = header.value
  840. }
  841. }
  842. for header in request.headers where header.name != "Cookie" {
  843. headers[header.name] = header.value
  844. }
  845. for header in headers {
  846. let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"")
  847. components.append("-H \"\(header.name): \(escapedValue)\"")
  848. }
  849. if let httpBodyData = request.httpBody {
  850. let httpBody = String(decoding: httpBodyData, as: UTF8.self)
  851. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  852. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  853. components.append("-d \"\(escapedBody)\"")
  854. }
  855. components.append("\"\(url.absoluteString)\"")
  856. return components.joined(separator: " \\\n\t")
  857. }
  858. }
  859. /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
  860. public protocol RequestDelegate: AnyObject {
  861. /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s.
  862. var sessionConfiguration: URLSessionConfiguration { get }
  863. /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler.
  864. var startImmediately: Bool { get }
  865. /// Notifies the delegate the `Request` has reached a point where it needs cleanup.
  866. ///
  867. /// - Parameter request: The `Request` to cleanup after.
  868. func cleanup(after request: Request)
  869. /// Asynchronously ask the delegate whether a `Request` will be retried.
  870. ///
  871. /// - Parameters:
  872. /// - request: `Request` which failed.
  873. /// - error: `Error` which produced the failure.
  874. /// - completion: Closure taking the `RetryResult` for evaluation.
  875. func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void)
  876. /// Asynchronously retry the `Request`.
  877. ///
  878. /// - Parameters:
  879. /// - request: `Request` which will be retried.
  880. /// - timeDelay: `TimeInterval` after which the retry will be triggered.
  881. func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
  882. }
  883. // MARK: - Subclasses
  884. // MARK: - DataRequest
  885. /// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`.
  886. public class DataRequest: Request {
  887. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  888. public let convertible: URLRequestConvertible
  889. /// `Data` read from the server so far.
  890. public var data: Data? { dataMutableState.data }
  891. private struct DataMutableState {
  892. var data: Data?
  893. var httpResponseHandler: (queue: DispatchQueue,
  894. handler: (_ response: HTTPURLResponse,
  895. _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void)?
  896. }
  897. private let dataMutableState = Protected(DataMutableState())
  898. /// Creates a `DataRequest` using the provided parameters.
  899. ///
  900. /// - Parameters:
  901. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  902. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  903. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  904. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  905. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  906. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  907. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  908. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  909. init(id: UUID = UUID(),
  910. convertible: URLRequestConvertible,
  911. underlyingQueue: DispatchQueue,
  912. serializationQueue: DispatchQueue,
  913. eventMonitor: EventMonitor?,
  914. interceptor: RequestInterceptor?,
  915. delegate: RequestDelegate) {
  916. self.convertible = convertible
  917. super.init(id: id,
  918. underlyingQueue: underlyingQueue,
  919. serializationQueue: serializationQueue,
  920. eventMonitor: eventMonitor,
  921. interceptor: interceptor,
  922. delegate: delegate)
  923. }
  924. override func reset() {
  925. super.reset()
  926. dataMutableState.write { mutableState in
  927. mutableState.data = nil
  928. }
  929. }
  930. /// Called when `Data` is received by this instance.
  931. ///
  932. /// - Note: Also calls `updateDownloadProgress`.
  933. ///
  934. /// - Parameter data: The `Data` received.
  935. func didReceive(data: Data) {
  936. dataMutableState.write { mutableState in
  937. if mutableState.data == nil {
  938. mutableState.data = data
  939. } else {
  940. mutableState.data?.append(data)
  941. }
  942. }
  943. updateDownloadProgress()
  944. }
  945. func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
  946. dataMutableState.read { dataMutableState in
  947. guard let httpResponseHandler = dataMutableState.httpResponseHandler else {
  948. underlyingQueue.async { completionHandler(.allow) }
  949. return
  950. }
  951. httpResponseHandler.queue.async {
  952. httpResponseHandler.handler(response) { disposition in
  953. if disposition == .cancel {
  954. self.mutableState.write { mutableState in
  955. mutableState.state = .cancelled
  956. mutableState.error = mutableState.error ?? AFError.explicitlyCancelled
  957. }
  958. }
  959. self.underlyingQueue.async {
  960. completionHandler(disposition.sessionDisposition)
  961. }
  962. }
  963. }
  964. }
  965. }
  966. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  967. let copiedRequest = request
  968. return session.dataTask(with: copiedRequest)
  969. }
  970. /// Called to update the `downloadProgress` of the instance.
  971. func updateDownloadProgress() {
  972. let totalBytesReceived = Int64(data?.count ?? 0)
  973. let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  974. downloadProgress.totalUnitCount = totalBytesExpected
  975. downloadProgress.completedUnitCount = totalBytesReceived
  976. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  977. }
  978. /// Validates the request, using the specified closure.
  979. ///
  980. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  981. ///
  982. /// - Parameter validation: `Validation` closure used to validate the response.
  983. ///
  984. /// - Returns: The instance.
  985. @discardableResult
  986. public func validate(_ validation: @escaping Validation) -> Self {
  987. let validator: () -> Void = { [unowned self] in
  988. guard error == nil, let response = response else { return }
  989. let result = validation(request, response, data)
  990. if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) }
  991. eventMonitor?.request(self,
  992. didValidateRequest: request,
  993. response: response,
  994. data: data,
  995. withResult: result)
  996. }
  997. validators.write { $0.append(validator) }
  998. return self
  999. }
  1000. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion
  1001. /// handler to return a `ResponseDisposition` value.
  1002. ///
  1003. /// - Parameters:
  1004. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  1005. /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided
  1006. /// MUST be called, otherwise the request will never complete.
  1007. ///
  1008. /// - Returns: The instance.
  1009. @_disfavoredOverload
  1010. @discardableResult
  1011. public func onHTTPResponse(
  1012. on queue: DispatchQueue = .main,
  1013. perform handler: @escaping (_ response: HTTPURLResponse,
  1014. _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void
  1015. ) -> Self {
  1016. dataMutableState.write { mutableState in
  1017. mutableState.httpResponseHandler = (queue, handler)
  1018. }
  1019. return self
  1020. }
  1021. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`.
  1022. ///
  1023. /// - Parameters:
  1024. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  1025. /// - handler: Closure called when the instance produces an `HTTPURLResponse`.
  1026. ///
  1027. /// - Returns: The instance.
  1028. @discardableResult
  1029. public func onHTTPResponse(on queue: DispatchQueue = .main,
  1030. perform handler: @escaping (HTTPURLResponse) -> Void) -> Self {
  1031. onHTTPResponse(on: queue) { response, completionHandler in
  1032. handler(response)
  1033. completionHandler(.allow)
  1034. }
  1035. return self
  1036. }
  1037. }
  1038. // MARK: - DataStreamRequest
  1039. /// `Request` subclass which streams HTTP response `Data` through a `Handler` closure.
  1040. public final class DataStreamRequest: Request {
  1041. /// Closure type handling `DataStreamRequest.Stream` values.
  1042. public typealias Handler<Success, Failure: Error> = (Stream<Success, Failure>) throws -> Void
  1043. /// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used
  1044. /// to stop the stream at any time.
  1045. public struct Stream<Success, Failure: Error> {
  1046. /// Latest `Event` from the stream.
  1047. public let event: Event<Success, Failure>
  1048. /// Token used to cancel the stream.
  1049. public let token: CancellationToken
  1050. /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
  1051. public func cancel() {
  1052. token.cancel()
  1053. }
  1054. }
  1055. /// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed
  1056. /// `Data` or the completion of the stream.
  1057. public enum Event<Success, Failure: Error> {
  1058. /// Output produced every time the instance receives additional `Data`. The associated value contains the
  1059. /// `Result` of processing the incoming `Data`.
  1060. case stream(Result<Success, Failure>)
  1061. /// Output produced when the instance has completed, whether due to stream end, cancellation, or an error.
  1062. /// Associated `Completion` value contains the final state.
  1063. case complete(Completion)
  1064. }
  1065. /// Value containing the state of a `DataStreamRequest` when the stream was completed.
  1066. public struct Completion {
  1067. /// Last `URLRequest` issued by the instance.
  1068. public let request: URLRequest?
  1069. /// Last `HTTPURLResponse` received by the instance.
  1070. public let response: HTTPURLResponse?
  1071. /// Last `URLSessionTaskMetrics` produced for the instance.
  1072. public let metrics: URLSessionTaskMetrics?
  1073. /// `AFError` produced for the instance, if any.
  1074. public let error: AFError?
  1075. }
  1076. /// Type used to cancel an ongoing stream.
  1077. public struct CancellationToken {
  1078. weak var request: DataStreamRequest?
  1079. init(_ request: DataStreamRequest) {
  1080. self.request = request
  1081. }
  1082. /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
  1083. public func cancel() {
  1084. request?.cancel()
  1085. }
  1086. }
  1087. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  1088. public let convertible: URLRequestConvertible
  1089. /// Whether or not the instance will be cancelled if stream parsing encounters an error.
  1090. public let automaticallyCancelOnStreamError: Bool
  1091. /// Internal mutable state specific to this type.
  1092. struct StreamMutableState {
  1093. /// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called.
  1094. var outputStream: OutputStream?
  1095. /// Stream closures called as `Data` is received.
  1096. var streams: [(_ data: Data) -> Void] = []
  1097. /// Number of currently executing streams. Used to ensure completions are only fired after all streams are
  1098. /// enqueued.
  1099. var numberOfExecutingStreams = 0
  1100. /// Completion calls enqueued while streams are still executing.
  1101. var enqueuedCompletionEvents: [() -> Void] = []
  1102. /// Handler for any `HTTPURLResponse`s received.
  1103. var httpResponseHandler: (queue: DispatchQueue,
  1104. handler: (_ response: HTTPURLResponse,
  1105. _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void)?
  1106. }
  1107. let streamMutableState = Protected(StreamMutableState())
  1108. /// Creates a `DataStreamRequest` using the provided parameters.
  1109. ///
  1110. /// - Parameters:
  1111. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()`
  1112. /// by default.
  1113. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this
  1114. /// instance.
  1115. /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error`
  1116. /// is thrown while serializing stream `Data`.
  1117. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1118. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default
  1119. /// targets
  1120. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1121. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1122. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1123. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by
  1124. /// the `Request`.
  1125. init(id: UUID = UUID(),
  1126. convertible: URLRequestConvertible,
  1127. automaticallyCancelOnStreamError: Bool,
  1128. underlyingQueue: DispatchQueue,
  1129. serializationQueue: DispatchQueue,
  1130. eventMonitor: EventMonitor?,
  1131. interceptor: RequestInterceptor?,
  1132. delegate: RequestDelegate) {
  1133. self.convertible = convertible
  1134. self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError
  1135. super.init(id: id,
  1136. underlyingQueue: underlyingQueue,
  1137. serializationQueue: serializationQueue,
  1138. eventMonitor: eventMonitor,
  1139. interceptor: interceptor,
  1140. delegate: delegate)
  1141. }
  1142. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1143. let copiedRequest = request
  1144. return session.dataTask(with: copiedRequest)
  1145. }
  1146. override func finish(error: AFError? = nil) {
  1147. streamMutableState.write { state in
  1148. state.outputStream?.close()
  1149. }
  1150. super.finish(error: error)
  1151. }
  1152. func didReceive(data: Data) {
  1153. streamMutableState.write { state in
  1154. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  1155. if let stream = state.outputStream {
  1156. underlyingQueue.async {
  1157. var bytes = Array(data)
  1158. stream.write(&bytes, maxLength: bytes.count)
  1159. }
  1160. }
  1161. #endif
  1162. state.numberOfExecutingStreams += state.streams.count
  1163. let localState = state
  1164. underlyingQueue.async { localState.streams.forEach { $0(data) } }
  1165. }
  1166. }
  1167. func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
  1168. streamMutableState.read { dataMutableState in
  1169. guard let httpResponseHandler = dataMutableState.httpResponseHandler else {
  1170. underlyingQueue.async { completionHandler(.allow) }
  1171. return
  1172. }
  1173. httpResponseHandler.queue.async {
  1174. httpResponseHandler.handler(response) { disposition in
  1175. if disposition == .cancel {
  1176. self.mutableState.write { mutableState in
  1177. mutableState.state = .cancelled
  1178. mutableState.error = mutableState.error ?? AFError.explicitlyCancelled
  1179. }
  1180. }
  1181. self.underlyingQueue.async {
  1182. completionHandler(disposition.sessionDisposition)
  1183. }
  1184. }
  1185. }
  1186. }
  1187. }
  1188. /// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure.
  1189. ///
  1190. /// - Parameter validation: `Validation` closure used to validate the request and response.
  1191. ///
  1192. /// - Returns: The `DataStreamRequest`.
  1193. @discardableResult
  1194. public func validate(_ validation: @escaping Validation) -> Self {
  1195. let validator: () -> Void = { [unowned self] in
  1196. guard error == nil, let response = response else { return }
  1197. let result = validation(request, response)
  1198. if case let .failure(error) = result {
  1199. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  1200. }
  1201. eventMonitor?.request(self,
  1202. didValidateRequest: request,
  1203. response: response,
  1204. withResult: result)
  1205. }
  1206. validators.write { $0.append(validator) }
  1207. return self
  1208. }
  1209. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  1210. /// Produces an `InputStream` that receives the `Data` received by the instance.
  1211. ///
  1212. /// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`.
  1213. /// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or
  1214. /// not the creating session has `startRequestsImmediately` set to `true`.
  1215. ///
  1216. /// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`.
  1217. ///
  1218. /// - Returns: The `InputStream` bound to the internal `OutboundStream`.
  1219. public func asInputStream(bufferSize: Int = 1024) -> InputStream? {
  1220. defer { resume() }
  1221. var inputStream: InputStream?
  1222. streamMutableState.write { state in
  1223. Foundation.Stream.getBoundStreams(withBufferSize: bufferSize,
  1224. inputStream: &inputStream,
  1225. outputStream: &state.outputStream)
  1226. state.outputStream?.open()
  1227. }
  1228. return inputStream
  1229. }
  1230. #endif
  1231. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion
  1232. /// handler to return a `ResponseDisposition` value.
  1233. ///
  1234. /// - Parameters:
  1235. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  1236. /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided
  1237. /// MUST be called, otherwise the request will never complete.
  1238. ///
  1239. /// - Returns: The instance.
  1240. @_disfavoredOverload
  1241. @discardableResult
  1242. public func onHTTPResponse(
  1243. on queue: DispatchQueue = .main,
  1244. perform handler: @escaping (_ response: HTTPURLResponse,
  1245. _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void
  1246. ) -> Self {
  1247. streamMutableState.write { mutableState in
  1248. mutableState.httpResponseHandler = (queue, handler)
  1249. }
  1250. return self
  1251. }
  1252. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`.
  1253. ///
  1254. /// - Parameters:
  1255. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  1256. /// - handler: Closure called when the instance produces an `HTTPURLResponse`.
  1257. ///
  1258. /// - Returns: The instance.
  1259. @discardableResult
  1260. public func onHTTPResponse(on queue: DispatchQueue = .main,
  1261. perform handler: @escaping (HTTPURLResponse) -> Void) -> Self {
  1262. onHTTPResponse(on: queue) { response, completionHandler in
  1263. handler(response)
  1264. completionHandler(.allow)
  1265. }
  1266. return self
  1267. }
  1268. func capturingError(from closure: () throws -> Void) {
  1269. do {
  1270. try closure()
  1271. } catch {
  1272. self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
  1273. cancel()
  1274. }
  1275. }
  1276. func appendStreamCompletion<Success, Failure>(on queue: DispatchQueue,
  1277. stream: @escaping Handler<Success, Failure>) {
  1278. appendResponseSerializer {
  1279. self.underlyingQueue.async {
  1280. self.responseSerializerDidComplete {
  1281. self.streamMutableState.write { state in
  1282. guard state.numberOfExecutingStreams == 0 else {
  1283. state.enqueuedCompletionEvents.append {
  1284. self.enqueueCompletion(on: queue, stream: stream)
  1285. }
  1286. return
  1287. }
  1288. self.enqueueCompletion(on: queue, stream: stream)
  1289. }
  1290. }
  1291. }
  1292. }
  1293. }
  1294. func enqueueCompletion<Success, Failure>(on queue: DispatchQueue,
  1295. stream: @escaping Handler<Success, Failure>) {
  1296. queue.async {
  1297. do {
  1298. let completion = Completion(request: self.request,
  1299. response: self.response,
  1300. metrics: self.metrics,
  1301. error: self.error)
  1302. try stream(.init(event: .complete(completion), token: .init(self)))
  1303. } catch {
  1304. // Ignore error, as errors on Completion can't be handled anyway.
  1305. }
  1306. }
  1307. }
  1308. }
  1309. extension DataStreamRequest.Stream {
  1310. /// Incoming `Result` values from `Event.stream`.
  1311. public var result: Result<Success, Failure>? {
  1312. guard case let .stream(result) = event else { return nil }
  1313. return result
  1314. }
  1315. /// `Success` value of the instance, if any.
  1316. public var value: Success? {
  1317. guard case let .success(value) = result else { return nil }
  1318. return value
  1319. }
  1320. /// `Failure` value of the instance, if any.
  1321. public var error: Failure? {
  1322. guard case let .failure(error) = result else { return nil }
  1323. return error
  1324. }
  1325. /// `Completion` value of the instance, if any.
  1326. public var completion: DataStreamRequest.Completion? {
  1327. guard case let .complete(completion) = event else { return nil }
  1328. return completion
  1329. }
  1330. }
  1331. // MARK: - DownloadRequest
  1332. /// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`.
  1333. public class DownloadRequest: Request {
  1334. /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination
  1335. /// `URL`.
  1336. public struct Options: OptionSet {
  1337. /// Specifies that intermediate directories for the destination URL should be created.
  1338. public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
  1339. /// Specifies that any previous file at the destination `URL` should be removed.
  1340. public static let removePreviousFile = Options(rawValue: 1 << 1)
  1341. public let rawValue: Int
  1342. public init(rawValue: Int) {
  1343. self.rawValue = rawValue
  1344. }
  1345. }
  1346. // MARK: Destination
  1347. /// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the
  1348. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  1349. /// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and
  1350. /// the options defining how the file should be moved.
  1351. ///
  1352. /// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not
  1353. /// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory.
  1354. public typealias Destination = (_ temporaryURL: URL,
  1355. _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
  1356. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  1357. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  1358. ///
  1359. /// - Parameters:
  1360. /// - directory: The search path directory. `.documentDirectory` by default.
  1361. /// - domain: The search path domain mask. `.userDomainMask` by default.
  1362. /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by
  1363. /// default.
  1364. /// - Returns: The `Destination` closure.
  1365. public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
  1366. in domain: FileManager.SearchPathDomainMask = .userDomainMask,
  1367. options: Options = []) -> Destination {
  1368. { temporaryURL, response in
  1369. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  1370. let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
  1371. return (url, options)
  1372. }
  1373. }
  1374. /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends
  1375. /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files
  1376. /// with this destination must be additionally moved if they should survive the system reclamation of temporary
  1377. /// space.
  1378. static let defaultDestination: Destination = { url, _ in
  1379. (defaultDestinationURL(url), [])
  1380. }
  1381. /// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the
  1382. /// provided file name.
  1383. static let defaultDestinationURL: (URL) -> URL = { url in
  1384. let filename = "Alamofire_\(url.lastPathComponent)"
  1385. let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
  1386. return destination
  1387. }
  1388. // MARK: Downloadable
  1389. /// Type describing the source used to create the underlying `URLSessionDownloadTask`.
  1390. public enum Downloadable {
  1391. /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value.
  1392. case request(URLRequestConvertible)
  1393. /// Download should be started from the associated resume `Data` value.
  1394. case resumeData(Data)
  1395. }
  1396. // MARK: Mutable State
  1397. /// Type containing all mutable state for `DownloadRequest` instances.
  1398. private struct DownloadRequestMutableState {
  1399. /// Possible resume `Data` produced when cancelling the instance.
  1400. var resumeData: Data?
  1401. /// `URL` to which `Data` is being downloaded.
  1402. var fileURL: URL?
  1403. }
  1404. /// Protected mutable state specific to `DownloadRequest`.
  1405. private let mutableDownloadState = Protected(DownloadRequestMutableState())
  1406. /// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download
  1407. /// using the `download(resumingWith data:)` API.
  1408. ///
  1409. /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel).
  1410. public var resumeData: Data? {
  1411. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  1412. return mutableDownloadState.resumeData ?? error?.downloadResumeData
  1413. #else
  1414. return mutableDownloadState.resumeData
  1415. #endif
  1416. }
  1417. /// If the download is successful, the `URL` where the file was downloaded.
  1418. public var fileURL: URL? { mutableDownloadState.fileURL }
  1419. // MARK: Initial State
  1420. /// `Downloadable` value used for this instance.
  1421. public let downloadable: Downloadable
  1422. /// The `Destination` to which the downloaded file is moved.
  1423. let destination: Destination
  1424. /// Creates a `DownloadRequest` using the provided parameters.
  1425. ///
  1426. /// - Parameters:
  1427. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  1428. /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance.
  1429. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1430. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  1431. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1432. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1433. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1434. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`
  1435. /// - destination: `Destination` closure used to move the downloaded file to its final location.
  1436. init(id: UUID = UUID(),
  1437. downloadable: Downloadable,
  1438. underlyingQueue: DispatchQueue,
  1439. serializationQueue: DispatchQueue,
  1440. eventMonitor: EventMonitor?,
  1441. interceptor: RequestInterceptor?,
  1442. delegate: RequestDelegate,
  1443. destination: @escaping Destination) {
  1444. self.downloadable = downloadable
  1445. self.destination = destination
  1446. super.init(id: id,
  1447. underlyingQueue: underlyingQueue,
  1448. serializationQueue: serializationQueue,
  1449. eventMonitor: eventMonitor,
  1450. interceptor: interceptor,
  1451. delegate: delegate)
  1452. }
  1453. override func reset() {
  1454. super.reset()
  1455. mutableDownloadState.write {
  1456. $0.resumeData = nil
  1457. $0.fileURL = nil
  1458. }
  1459. }
  1460. /// Called when a download has finished.
  1461. ///
  1462. /// - Parameters:
  1463. /// - task: `URLSessionTask` that finished the download.
  1464. /// - result: `Result` of the automatic move to `destination`.
  1465. func didFinishDownloading(using task: URLSessionTask, with result: Result<URL, AFError>) {
  1466. eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
  1467. switch result {
  1468. case let .success(url): mutableDownloadState.fileURL = url
  1469. case let .failure(error): self.error = error
  1470. }
  1471. }
  1472. /// Updates the `downloadProgress` using the provided values.
  1473. ///
  1474. /// - Parameters:
  1475. /// - bytesWritten: Total bytes written so far.
  1476. /// - totalBytesExpectedToWrite: Total bytes expected to write.
  1477. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  1478. downloadProgress.totalUnitCount = totalBytesExpectedToWrite
  1479. downloadProgress.completedUnitCount += bytesWritten
  1480. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  1481. }
  1482. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1483. session.downloadTask(with: request)
  1484. }
  1485. /// Creates a `URLSessionTask` from the provided resume data.
  1486. ///
  1487. /// - Parameters:
  1488. /// - data: `Data` used to resume the download.
  1489. /// - session: `URLSession` used to create the `URLSessionTask`.
  1490. ///
  1491. /// - Returns: The `URLSessionTask` created.
  1492. public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
  1493. session.downloadTask(withResumeData: data)
  1494. }
  1495. /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended.
  1496. ///
  1497. /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use
  1498. /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`.
  1499. ///
  1500. /// - Returns: The instance.
  1501. @discardableResult
  1502. override public func cancel() -> Self {
  1503. cancel(producingResumeData: false)
  1504. }
  1505. /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be
  1506. /// resumed or suspended.
  1507. ///
  1508. /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if
  1509. /// available.
  1510. ///
  1511. /// - Returns: The instance.
  1512. @discardableResult
  1513. public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self {
  1514. cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil)
  1515. }
  1516. /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed
  1517. /// or suspended.
  1518. ///
  1519. /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData`
  1520. /// property.
  1521. ///
  1522. /// - Parameter completionHandler: The completion handler that is called when the download has been successfully
  1523. /// cancelled. It is not guaranteed to be called on a particular queue, so you may
  1524. /// want use an appropriate queue to perform your work.
  1525. ///
  1526. /// - Returns: The instance.
  1527. @discardableResult
  1528. public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self {
  1529. cancel(optionallyProducingResumeData: completionHandler)
  1530. }
  1531. /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed,
  1532. /// cancellation is performed without producing resume data.
  1533. ///
  1534. /// - Parameter completionHandler: Optional resume data handler.
  1535. ///
  1536. /// - Returns: The instance.
  1537. private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self {
  1538. mutableState.write { mutableState in
  1539. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  1540. mutableState.state = .cancelled
  1541. underlyingQueue.async { self.didCancel() }
  1542. guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
  1543. underlyingQueue.async { self.finish() }
  1544. return
  1545. }
  1546. if let completionHandler = completionHandler {
  1547. // Resume to ensure metrics are gathered.
  1548. task.resume()
  1549. task.cancel { resumeData in
  1550. self.mutableDownloadState.resumeData = resumeData
  1551. self.underlyingQueue.async { self.didCancelTask(task) }
  1552. completionHandler(resumeData)
  1553. }
  1554. } else {
  1555. // Resume to ensure metrics are gathered.
  1556. task.resume()
  1557. task.cancel()
  1558. self.underlyingQueue.async { self.didCancelTask(task) }
  1559. }
  1560. }
  1561. return self
  1562. }
  1563. /// Validates the request, using the specified closure.
  1564. ///
  1565. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  1566. ///
  1567. /// - Parameter validation: `Validation` closure to validate the response.
  1568. ///
  1569. /// - Returns: The instance.
  1570. @discardableResult
  1571. public func validate(_ validation: @escaping Validation) -> Self {
  1572. let validator: () -> Void = { [unowned self] in
  1573. guard error == nil, let response = response else { return }
  1574. let result = validation(request, response, fileURL)
  1575. if case let .failure(error) = result {
  1576. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  1577. }
  1578. eventMonitor?.request(self,
  1579. didValidateRequest: request,
  1580. response: response,
  1581. fileURL: fileURL,
  1582. withResult: result)
  1583. }
  1584. validators.write { $0.append(validator) }
  1585. return self
  1586. }
  1587. }
  1588. // MARK: - UploadRequest
  1589. /// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`.
  1590. public class UploadRequest: DataRequest {
  1591. /// Type describing the origin of the upload, whether `Data`, file, or stream.
  1592. public enum Uploadable {
  1593. /// Upload from the provided `Data` value.
  1594. case data(Data)
  1595. /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be
  1596. /// automatically removed once uploaded.
  1597. case file(URL, shouldRemove: Bool)
  1598. /// Upload from the provided `InputStream`.
  1599. case stream(InputStream)
  1600. }
  1601. // MARK: Initial State
  1602. /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance.
  1603. public let upload: UploadableConvertible
  1604. /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written
  1605. /// to disk.
  1606. public let fileManager: FileManager
  1607. // MARK: Mutable State
  1608. /// `Uploadable` value used by the instance.
  1609. public var uploadable: Uploadable?
  1610. /// Creates an `UploadRequest` using the provided parameters.
  1611. ///
  1612. /// - Parameters:
  1613. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  1614. /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed.
  1615. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1616. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  1617. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1618. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1619. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1620. /// - fileManager: `FileManager` used to perform cleanup tasks, including the removal of multipart form
  1621. /// encoded payloads written to disk.
  1622. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  1623. init(id: UUID = UUID(),
  1624. convertible: UploadConvertible,
  1625. underlyingQueue: DispatchQueue,
  1626. serializationQueue: DispatchQueue,
  1627. eventMonitor: EventMonitor?,
  1628. interceptor: RequestInterceptor?,
  1629. fileManager: FileManager,
  1630. delegate: RequestDelegate) {
  1631. upload = convertible
  1632. self.fileManager = fileManager
  1633. super.init(id: id,
  1634. convertible: convertible,
  1635. underlyingQueue: underlyingQueue,
  1636. serializationQueue: serializationQueue,
  1637. eventMonitor: eventMonitor,
  1638. interceptor: interceptor,
  1639. delegate: delegate)
  1640. }
  1641. /// Called when the `Uploadable` value has been created from the `UploadConvertible`.
  1642. ///
  1643. /// - Parameter uploadable: The `Uploadable` that was created.
  1644. func didCreateUploadable(_ uploadable: Uploadable) {
  1645. self.uploadable = uploadable
  1646. eventMonitor?.request(self, didCreateUploadable: uploadable)
  1647. }
  1648. /// Called when the `Uploadable` value could not be created.
  1649. ///
  1650. /// - Parameter error: `AFError` produced by the failure.
  1651. func didFailToCreateUploadable(with error: AFError) {
  1652. self.error = error
  1653. eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
  1654. retryOrFinish(error: error)
  1655. }
  1656. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1657. guard let uploadable = uploadable else {
  1658. fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
  1659. }
  1660. switch uploadable {
  1661. case let .data(data): return session.uploadTask(with: request, from: data)
  1662. case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
  1663. case .stream: return session.uploadTask(withStreamedRequest: request)
  1664. }
  1665. }
  1666. override func reset() {
  1667. // Uploadable must be recreated on every retry.
  1668. uploadable = nil
  1669. super.reset()
  1670. }
  1671. /// Produces the `InputStream` from `uploadable`, if it can.
  1672. ///
  1673. /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash.
  1674. ///
  1675. /// - Returns: The `InputStream`.
  1676. func inputStream() -> InputStream {
  1677. guard let uploadable = uploadable else {
  1678. fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
  1679. }
  1680. guard case let .stream(stream) = uploadable else {
  1681. fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
  1682. }
  1683. eventMonitor?.request(self, didProvideInputStream: stream)
  1684. return stream
  1685. }
  1686. override public func cleanup() {
  1687. defer { super.cleanup() }
  1688. guard
  1689. let uploadable = uploadable,
  1690. case let .file(url, shouldRemove) = uploadable,
  1691. shouldRemove
  1692. else { return }
  1693. try? fileManager.removeItem(at: url)
  1694. }
  1695. }
  1696. /// A type that can produce an `UploadRequest.Uploadable` value.
  1697. public protocol UploadableConvertible {
  1698. /// Produces an `UploadRequest.Uploadable` value from the instance.
  1699. ///
  1700. /// - Returns: The `UploadRequest.Uploadable`.
  1701. /// - Throws: Any `Error` produced during creation.
  1702. func createUploadable() throws -> UploadRequest.Uploadable
  1703. }
  1704. extension UploadRequest.Uploadable: UploadableConvertible {
  1705. public func createUploadable() throws -> UploadRequest.Uploadable {
  1706. self
  1707. }
  1708. }
  1709. /// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`.
  1710. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {}