Request.swift 77 KB

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