Request.swift 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912
  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. $mutableState.write { mutableState in
  699. if mutableState.requests.last != nil {
  700. underlyingQueue.async { handler(self.cURLDescription()) }
  701. } else {
  702. mutableState.cURLHandler = (underlyingQueue, handler)
  703. }
  704. }
  705. return self
  706. }
  707. /// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance.
  708. ///
  709. /// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried.
  710. ///
  711. /// - Parameters:
  712. /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
  713. /// - handler: Closure to be called when a `URLRequest` is available.
  714. ///
  715. /// - Returns: The instance.
  716. @discardableResult
  717. public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLRequest) -> Void) -> Self {
  718. $mutableState.write { state in
  719. if let request = state.requests.last {
  720. queue.async { handler(request) }
  721. }
  722. state.urlRequestHandler = (queue, handler)
  723. }
  724. return self
  725. }
  726. /// Sets a closure to be called whenever the instance creates a `URLSessionTask`.
  727. ///
  728. /// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It
  729. /// **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features.
  730. /// Additionally, this closure may be called multiple times if the instance is retried.
  731. ///
  732. /// - Parameters:
  733. /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
  734. /// - handler: Closure to be called when the `URLSessionTask` is available.
  735. ///
  736. /// - Returns: The instance.
  737. @discardableResult
  738. public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLSessionTask) -> Void) -> Self {
  739. $mutableState.write { state in
  740. if let task = state.tasks.last {
  741. queue.async { handler(task) }
  742. }
  743. state.urlSessionTaskHandler = (queue, handler)
  744. }
  745. return self
  746. }
  747. // MARK: Cleanup
  748. /// Adds a `finishHandler` closure to be called when the request completes.
  749. ///
  750. /// - Parameter closure: Closure to be called when the request finishes.
  751. func onFinish(perform finishHandler: @escaping () -> Void) {
  752. guard !isFinished else { finishHandler(); return }
  753. $mutableState.write { state in
  754. state.finishHandlers.append(finishHandler)
  755. }
  756. }
  757. /// Final cleanup step executed when the instance finishes response serialization.
  758. func cleanup() {
  759. delegate?.cleanup(after: self)
  760. let handlers = $mutableState.finishHandlers
  761. handlers.forEach { $0() }
  762. $mutableState.write { state in
  763. state.finishHandlers.removeAll()
  764. }
  765. }
  766. }
  767. // MARK: - Protocol Conformances
  768. extension Request: Equatable {
  769. public static func ==(lhs: Request, rhs: Request) -> Bool {
  770. lhs.id == rhs.id
  771. }
  772. }
  773. extension Request: Hashable {
  774. public func hash(into hasher: inout Hasher) {
  775. hasher.combine(id)
  776. }
  777. }
  778. extension Request: CustomStringConvertible {
  779. /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
  780. /// created, as well as the response status code, if a response has been received.
  781. public var description: String {
  782. guard let request = performedRequests.last ?? lastRequest,
  783. let url = request.url,
  784. let method = request.httpMethod else { return "No request created yet." }
  785. let requestDescription = "\(method) \(url.absoluteString)"
  786. return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
  787. }
  788. }
  789. extension Request {
  790. /// cURL representation of the instance.
  791. ///
  792. /// - Returns: The cURL equivalent of the instance.
  793. public func cURLDescription() -> String {
  794. guard
  795. let request = lastRequest,
  796. let url = request.url,
  797. let host = url.host,
  798. let method = request.httpMethod else { return "$ curl command could not be created" }
  799. var components = ["$ curl -v"]
  800. components.append("-X \(method)")
  801. if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
  802. let protectionSpace = URLProtectionSpace(host: host,
  803. port: url.port ?? 0,
  804. protocol: url.scheme,
  805. realm: host,
  806. authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  807. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  808. for credential in credentials {
  809. guard let user = credential.user, let password = credential.password else { continue }
  810. components.append("-u \(user):\(password)")
  811. }
  812. } else {
  813. if let credential = credential, let user = credential.user, let password = credential.password {
  814. components.append("-u \(user):\(password)")
  815. }
  816. }
  817. }
  818. if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
  819. if
  820. let cookieStorage = configuration.httpCookieStorage,
  821. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty {
  822. let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
  823. components.append("-b \"\(allCookies)\"")
  824. }
  825. }
  826. var headers = HTTPHeaders()
  827. if let sessionHeaders = delegate?.sessionConfiguration.headers {
  828. for header in sessionHeaders where header.name != "Cookie" {
  829. headers[header.name] = header.value
  830. }
  831. }
  832. for header in request.headers where header.name != "Cookie" {
  833. headers[header.name] = header.value
  834. }
  835. for header in headers {
  836. let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"")
  837. components.append("-H \"\(header.name): \(escapedValue)\"")
  838. }
  839. if let httpBodyData = request.httpBody {
  840. let httpBody = String(decoding: httpBodyData, as: UTF8.self)
  841. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  842. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  843. components.append("-d \"\(escapedBody)\"")
  844. }
  845. components.append("\"\(url.absoluteString)\"")
  846. return components.joined(separator: " \\\n\t")
  847. }
  848. }
  849. /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
  850. public protocol RequestDelegate: AnyObject {
  851. /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s.
  852. var sessionConfiguration: URLSessionConfiguration { get }
  853. /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler.
  854. var startImmediately: Bool { get }
  855. /// Notifies the delegate the `Request` has reached a point where it needs cleanup.
  856. ///
  857. /// - Parameter request: The `Request` to cleanup after.
  858. func cleanup(after request: Request)
  859. /// Asynchronously ask the delegate whether a `Request` will be retried.
  860. ///
  861. /// - Parameters:
  862. /// - request: `Request` which failed.
  863. /// - error: `Error` which produced the failure.
  864. /// - completion: Closure taking the `RetryResult` for evaluation.
  865. func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void)
  866. /// Asynchronously retry the `Request`.
  867. ///
  868. /// - Parameters:
  869. /// - request: `Request` which will be retried.
  870. /// - timeDelay: `TimeInterval` after which the retry will be triggered.
  871. func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
  872. }
  873. // MARK: - Subclasses
  874. // MARK: - DataRequest
  875. /// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`.
  876. public class DataRequest: Request {
  877. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  878. public let convertible: URLRequestConvertible
  879. /// `Data` read from the server so far.
  880. public var data: Data? { mutableData }
  881. /// Protected storage for the `Data` read by the instance.
  882. @Protected
  883. private var mutableData: Data? = nil
  884. /// Creates a `DataRequest` using the provided parameters.
  885. ///
  886. /// - Parameters:
  887. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  888. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  889. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  890. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  891. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  892. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  893. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  894. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  895. init(id: UUID = UUID(),
  896. convertible: URLRequestConvertible,
  897. underlyingQueue: DispatchQueue,
  898. serializationQueue: DispatchQueue,
  899. eventMonitor: EventMonitor?,
  900. interceptor: RequestInterceptor?,
  901. delegate: RequestDelegate) {
  902. self.convertible = convertible
  903. super.init(id: id,
  904. underlyingQueue: underlyingQueue,
  905. serializationQueue: serializationQueue,
  906. eventMonitor: eventMonitor,
  907. interceptor: interceptor,
  908. delegate: delegate)
  909. }
  910. override func reset() {
  911. super.reset()
  912. mutableData = nil
  913. }
  914. /// Called when `Data` is received by this instance.
  915. ///
  916. /// - Note: Also calls `updateDownloadProgress`.
  917. ///
  918. /// - Parameter data: The `Data` received.
  919. func didReceive(data: Data) {
  920. if self.data == nil {
  921. mutableData = data
  922. } else {
  923. $mutableData.write { $0?.append(data) }
  924. }
  925. updateDownloadProgress()
  926. }
  927. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  928. let copiedRequest = request
  929. return session.dataTask(with: copiedRequest)
  930. }
  931. /// Called to update the `downloadProgress` of the instance.
  932. func updateDownloadProgress() {
  933. let totalBytesReceived = Int64(data?.count ?? 0)
  934. let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  935. downloadProgress.totalUnitCount = totalBytesExpected
  936. downloadProgress.completedUnitCount = totalBytesReceived
  937. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  938. }
  939. /// Validates the request, using the specified closure.
  940. ///
  941. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  942. ///
  943. /// - Parameter validation: `Validation` closure used to validate the response.
  944. ///
  945. /// - Returns: The instance.
  946. @discardableResult
  947. public func validate(_ validation: @escaping Validation) -> Self {
  948. let validator: () -> Void = { [unowned self] in
  949. guard error == nil, let response = response else { return }
  950. let result = validation(request, response, data)
  951. if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) }
  952. eventMonitor?.request(self,
  953. didValidateRequest: request,
  954. response: response,
  955. data: data,
  956. withResult: result)
  957. }
  958. $validators.write { $0.append(validator) }
  959. return self
  960. }
  961. }
  962. // MARK: - DataStreamRequest
  963. /// `Request` subclass which streams HTTP response `Data` through a `Handler` closure.
  964. public final class DataStreamRequest: Request {
  965. /// Closure type handling `DataStreamRequest.Stream` values.
  966. public typealias Handler<Success, Failure: Error> = (Stream<Success, Failure>) throws -> Void
  967. /// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used
  968. /// to stop the stream at any time.
  969. public struct Stream<Success, Failure: Error> {
  970. /// Latest `Event` from the stream.
  971. public let event: Event<Success, Failure>
  972. /// Token used to cancel the stream.
  973. public let token: CancellationToken
  974. /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
  975. public func cancel() {
  976. token.cancel()
  977. }
  978. }
  979. /// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed
  980. /// `Data` or the completion of the stream.
  981. public enum Event<Success, Failure: Error> {
  982. /// Output produced every time the instance receives additional `Data`. The associated value contains the
  983. /// `Result` of processing the incoming `Data`.
  984. case stream(Result<Success, Failure>)
  985. /// Output produced when the instance has completed, whether due to stream end, cancellation, or an error.
  986. /// Associated `Completion` value contains the final state.
  987. case complete(Completion)
  988. }
  989. /// Value containing the state of a `DataStreamRequest` when the stream was completed.
  990. public struct Completion {
  991. /// Last `URLRequest` issued by the instance.
  992. public let request: URLRequest?
  993. /// Last `HTTPURLResponse` received by the instance.
  994. public let response: HTTPURLResponse?
  995. /// Last `URLSessionTaskMetrics` produced for the instance.
  996. public let metrics: URLSessionTaskMetrics?
  997. /// `AFError` produced for the instance, if any.
  998. public let error: AFError?
  999. }
  1000. /// Type used to cancel an ongoing stream.
  1001. public struct CancellationToken {
  1002. weak var request: DataStreamRequest?
  1003. init(_ request: DataStreamRequest) {
  1004. self.request = request
  1005. }
  1006. /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
  1007. public func cancel() {
  1008. request?.cancel()
  1009. }
  1010. }
  1011. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  1012. public let convertible: URLRequestConvertible
  1013. /// Whether or not the instance will be cancelled if stream parsing encounters an error.
  1014. public let automaticallyCancelOnStreamError: Bool
  1015. /// Internal mutable state specific to this type.
  1016. struct StreamMutableState {
  1017. /// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called.
  1018. var outputStream: OutputStream?
  1019. /// Stream closures called as `Data` is received.
  1020. var streams: [(_ data: Data) -> Void] = []
  1021. /// Number of currently executing streams. Used to ensure completions are only fired after all streams are
  1022. /// enqueued.
  1023. var numberOfExecutingStreams = 0
  1024. /// Completion calls enqueued while streams are still executing.
  1025. var enqueuedCompletionEvents: [() -> Void] = []
  1026. }
  1027. @Protected
  1028. var streamMutableState = StreamMutableState()
  1029. /// Creates a `DataStreamRequest` using the provided parameters.
  1030. ///
  1031. /// - Parameters:
  1032. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()`
  1033. /// by default.
  1034. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this
  1035. /// instance.
  1036. /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error`
  1037. /// is thrown while serializing stream `Data`.
  1038. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1039. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default
  1040. /// targets
  1041. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1042. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1043. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1044. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by
  1045. /// the `Request`.
  1046. init(id: UUID = UUID(),
  1047. convertible: URLRequestConvertible,
  1048. automaticallyCancelOnStreamError: Bool,
  1049. underlyingQueue: DispatchQueue,
  1050. serializationQueue: DispatchQueue,
  1051. eventMonitor: EventMonitor?,
  1052. interceptor: RequestInterceptor?,
  1053. delegate: RequestDelegate) {
  1054. self.convertible = convertible
  1055. self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError
  1056. super.init(id: id,
  1057. underlyingQueue: underlyingQueue,
  1058. serializationQueue: serializationQueue,
  1059. eventMonitor: eventMonitor,
  1060. interceptor: interceptor,
  1061. delegate: delegate)
  1062. }
  1063. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1064. let copiedRequest = request
  1065. return session.dataTask(with: copiedRequest)
  1066. }
  1067. override func finish(error: AFError? = nil) {
  1068. $streamMutableState.write { state in
  1069. state.outputStream?.close()
  1070. }
  1071. super.finish(error: error)
  1072. }
  1073. func didReceive(data: Data) {
  1074. $streamMutableState.write { state in
  1075. #if !(os(Linux) || os(Windows))
  1076. if let stream = state.outputStream {
  1077. underlyingQueue.async {
  1078. var bytes = Array(data)
  1079. stream.write(&bytes, maxLength: bytes.count)
  1080. }
  1081. }
  1082. #endif
  1083. state.numberOfExecutingStreams += state.streams.count
  1084. let localState = state
  1085. underlyingQueue.async { localState.streams.forEach { $0(data) } }
  1086. }
  1087. }
  1088. /// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure.
  1089. ///
  1090. /// - Parameter validation: `Validation` closure used to validate the request and response.
  1091. ///
  1092. /// - Returns: The `DataStreamRequest`.
  1093. @discardableResult
  1094. public func validate(_ validation: @escaping Validation) -> Self {
  1095. let validator: () -> Void = { [unowned self] in
  1096. guard error == nil, let response = response else { return }
  1097. let result = validation(request, response)
  1098. if case let .failure(error) = result {
  1099. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  1100. }
  1101. eventMonitor?.request(self,
  1102. didValidateRequest: request,
  1103. response: response,
  1104. withResult: result)
  1105. }
  1106. $validators.write { $0.append(validator) }
  1107. return self
  1108. }
  1109. #if !(os(Linux) || os(Windows))
  1110. /// Produces an `InputStream` that receives the `Data` received by the instance.
  1111. ///
  1112. /// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`.
  1113. /// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or
  1114. /// not the creating session has `startRequestsImmediately` set to `true`.
  1115. ///
  1116. /// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`.
  1117. ///
  1118. /// - Returns: The `InputStream` bound to the internal `OutboundStream`.
  1119. public func asInputStream(bufferSize: Int = 1024) -> InputStream? {
  1120. defer { resume() }
  1121. var inputStream: InputStream?
  1122. $streamMutableState.write { state in
  1123. Foundation.Stream.getBoundStreams(withBufferSize: bufferSize,
  1124. inputStream: &inputStream,
  1125. outputStream: &state.outputStream)
  1126. state.outputStream?.open()
  1127. }
  1128. return inputStream
  1129. }
  1130. #endif
  1131. func capturingError(from closure: () throws -> Void) {
  1132. do {
  1133. try closure()
  1134. } catch {
  1135. self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
  1136. cancel()
  1137. }
  1138. }
  1139. func appendStreamCompletion<Success, Failure>(on queue: DispatchQueue,
  1140. stream: @escaping Handler<Success, Failure>) {
  1141. appendResponseSerializer {
  1142. self.underlyingQueue.async {
  1143. self.responseSerializerDidComplete {
  1144. self.$streamMutableState.write { state in
  1145. guard state.numberOfExecutingStreams == 0 else {
  1146. state.enqueuedCompletionEvents.append {
  1147. self.enqueueCompletion(on: queue, stream: stream)
  1148. }
  1149. return
  1150. }
  1151. self.enqueueCompletion(on: queue, stream: stream)
  1152. }
  1153. }
  1154. }
  1155. }
  1156. }
  1157. func enqueueCompletion<Success, Failure>(on queue: DispatchQueue,
  1158. stream: @escaping Handler<Success, Failure>) {
  1159. queue.async {
  1160. do {
  1161. let completion = Completion(request: self.request,
  1162. response: self.response,
  1163. metrics: self.metrics,
  1164. error: self.error)
  1165. try stream(.init(event: .complete(completion), token: .init(self)))
  1166. } catch {
  1167. // Ignore error, as errors on Completion can't be handled anyway.
  1168. }
  1169. }
  1170. }
  1171. }
  1172. extension DataStreamRequest.Stream {
  1173. /// Incoming `Result` values from `Event.stream`.
  1174. public var result: Result<Success, Failure>? {
  1175. guard case let .stream(result) = event else { return nil }
  1176. return result
  1177. }
  1178. /// `Success` value of the instance, if any.
  1179. public var value: Success? {
  1180. guard case let .success(value) = result else { return nil }
  1181. return value
  1182. }
  1183. /// `Failure` value of the instance, if any.
  1184. public var error: Failure? {
  1185. guard case let .failure(error) = result else { return nil }
  1186. return error
  1187. }
  1188. /// `Completion` value of the instance, if any.
  1189. public var completion: DataStreamRequest.Completion? {
  1190. guard case let .complete(completion) = event else { return nil }
  1191. return completion
  1192. }
  1193. }
  1194. // MARK: - DownloadRequest
  1195. /// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`.
  1196. public class DownloadRequest: Request {
  1197. /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination
  1198. /// `URL`.
  1199. public struct Options: OptionSet {
  1200. /// Specifies that intermediate directories for the destination URL should be created.
  1201. public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
  1202. /// Specifies that any previous file at the destination `URL` should be removed.
  1203. public static let removePreviousFile = Options(rawValue: 1 << 1)
  1204. public let rawValue: Int
  1205. public init(rawValue: Int) {
  1206. self.rawValue = rawValue
  1207. }
  1208. }
  1209. // MARK: Destination
  1210. /// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the
  1211. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  1212. /// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and
  1213. /// the options defining how the file should be moved.
  1214. ///
  1215. /// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not
  1216. /// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory.
  1217. public typealias Destination = (_ temporaryURL: URL,
  1218. _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
  1219. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  1220. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  1221. ///
  1222. /// - Parameters:
  1223. /// - directory: The search path directory. `.documentDirectory` by default.
  1224. /// - domain: The search path domain mask. `.userDomainMask` by default.
  1225. /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by
  1226. /// default.
  1227. /// - Returns: The `Destination` closure.
  1228. public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
  1229. in domain: FileManager.SearchPathDomainMask = .userDomainMask,
  1230. options: Options = []) -> Destination {
  1231. { temporaryURL, response in
  1232. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  1233. let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
  1234. return (url, options)
  1235. }
  1236. }
  1237. /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends
  1238. /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files
  1239. /// with this destination must be additionally moved if they should survive the system reclamation of temporary
  1240. /// space.
  1241. static let defaultDestination: Destination = { url, _ in
  1242. (defaultDestinationURL(url), [])
  1243. }
  1244. /// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the
  1245. /// provided file name.
  1246. static let defaultDestinationURL: (URL) -> URL = { url in
  1247. let filename = "Alamofire_\(url.lastPathComponent)"
  1248. let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
  1249. return destination
  1250. }
  1251. // MARK: Downloadable
  1252. /// Type describing the source used to create the underlying `URLSessionDownloadTask`.
  1253. public enum Downloadable {
  1254. /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value.
  1255. case request(URLRequestConvertible)
  1256. /// Download should be started from the associated resume `Data` value.
  1257. case resumeData(Data)
  1258. }
  1259. // MARK: Mutable State
  1260. /// Type containing all mutable state for `DownloadRequest` instances.
  1261. private struct DownloadRequestMutableState {
  1262. /// Possible resume `Data` produced when cancelling the instance.
  1263. var resumeData: Data?
  1264. /// `URL` to which `Data` is being downloaded.
  1265. var fileURL: URL?
  1266. }
  1267. /// Protected mutable state specific to `DownloadRequest`.
  1268. @Protected
  1269. private var mutableDownloadState = DownloadRequestMutableState()
  1270. /// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download
  1271. /// using the `download(resumingWith data:)` API.
  1272. ///
  1273. /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel).
  1274. public var resumeData: Data? {
  1275. #if !(os(Linux) || os(Windows))
  1276. return $mutableDownloadState.resumeData ?? error?.downloadResumeData
  1277. #else
  1278. return $mutableDownloadState.resumeData
  1279. #endif
  1280. }
  1281. /// If the download is successful, the `URL` where the file was downloaded.
  1282. public var fileURL: URL? { $mutableDownloadState.fileURL }
  1283. // MARK: Initial State
  1284. /// `Downloadable` value used for this instance.
  1285. public let downloadable: Downloadable
  1286. /// The `Destination` to which the downloaded file is moved.
  1287. let destination: Destination
  1288. /// Creates a `DownloadRequest` using the provided parameters.
  1289. ///
  1290. /// - Parameters:
  1291. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  1292. /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance.
  1293. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1294. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  1295. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1296. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1297. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1298. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`
  1299. /// - destination: `Destination` closure used to move the downloaded file to its final location.
  1300. init(id: UUID = UUID(),
  1301. downloadable: Downloadable,
  1302. underlyingQueue: DispatchQueue,
  1303. serializationQueue: DispatchQueue,
  1304. eventMonitor: EventMonitor?,
  1305. interceptor: RequestInterceptor?,
  1306. delegate: RequestDelegate,
  1307. destination: @escaping Destination) {
  1308. self.downloadable = downloadable
  1309. self.destination = destination
  1310. super.init(id: id,
  1311. underlyingQueue: underlyingQueue,
  1312. serializationQueue: serializationQueue,
  1313. eventMonitor: eventMonitor,
  1314. interceptor: interceptor,
  1315. delegate: delegate)
  1316. }
  1317. override func reset() {
  1318. super.reset()
  1319. $mutableDownloadState.write {
  1320. $0.resumeData = nil
  1321. $0.fileURL = nil
  1322. }
  1323. }
  1324. /// Called when a download has finished.
  1325. ///
  1326. /// - Parameters:
  1327. /// - task: `URLSessionTask` that finished the download.
  1328. /// - result: `Result` of the automatic move to `destination`.
  1329. func didFinishDownloading(using task: URLSessionTask, with result: Result<URL, AFError>) {
  1330. eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
  1331. switch result {
  1332. case let .success(url): $mutableDownloadState.fileURL = url
  1333. case let .failure(error): self.error = error
  1334. }
  1335. }
  1336. /// Updates the `downloadProgress` using the provided values.
  1337. ///
  1338. /// - Parameters:
  1339. /// - bytesWritten: Total bytes written so far.
  1340. /// - totalBytesExpectedToWrite: Total bytes expected to write.
  1341. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  1342. downloadProgress.totalUnitCount = totalBytesExpectedToWrite
  1343. downloadProgress.completedUnitCount += bytesWritten
  1344. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  1345. }
  1346. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1347. session.downloadTask(with: request)
  1348. }
  1349. /// Creates a `URLSessionTask` from the provided resume data.
  1350. ///
  1351. /// - Parameters:
  1352. /// - data: `Data` used to resume the download.
  1353. /// - session: `URLSession` used to create the `URLSessionTask`.
  1354. ///
  1355. /// - Returns: The `URLSessionTask` created.
  1356. public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
  1357. session.downloadTask(withResumeData: data)
  1358. }
  1359. /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended.
  1360. ///
  1361. /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use
  1362. /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`.
  1363. ///
  1364. /// - Returns: The instance.
  1365. @discardableResult
  1366. override public func cancel() -> Self {
  1367. cancel(producingResumeData: false)
  1368. }
  1369. /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be
  1370. /// resumed or suspended.
  1371. ///
  1372. /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if
  1373. /// available.
  1374. ///
  1375. /// - Returns: The instance.
  1376. @discardableResult
  1377. public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self {
  1378. cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil)
  1379. }
  1380. /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed
  1381. /// or suspended.
  1382. ///
  1383. /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData`
  1384. /// property.
  1385. ///
  1386. /// - Parameter completionHandler: The completion handler that is called when the download has been successfully
  1387. /// cancelled. It is not guaranteed to be called on a particular queue, so you may
  1388. /// want use an appropriate queue to perform your work.
  1389. ///
  1390. /// - Returns: The instance.
  1391. @discardableResult
  1392. public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self {
  1393. cancel(optionallyProducingResumeData: completionHandler)
  1394. }
  1395. /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed,
  1396. /// cancellation is performed without producing resume data.
  1397. ///
  1398. /// - Parameter completionHandler: Optional resume data handler.
  1399. ///
  1400. /// - Returns: The instance.
  1401. private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self {
  1402. $mutableState.write { mutableState in
  1403. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  1404. mutableState.state = .cancelled
  1405. underlyingQueue.async { self.didCancel() }
  1406. guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
  1407. underlyingQueue.async { self.finish() }
  1408. return
  1409. }
  1410. if let completionHandler = completionHandler {
  1411. // Resume to ensure metrics are gathered.
  1412. task.resume()
  1413. task.cancel { resumeData in
  1414. self.$mutableDownloadState.resumeData = resumeData
  1415. self.underlyingQueue.async { self.didCancelTask(task) }
  1416. completionHandler(resumeData)
  1417. }
  1418. } else {
  1419. // Resume to ensure metrics are gathered.
  1420. task.resume()
  1421. task.cancel()
  1422. self.underlyingQueue.async { self.didCancelTask(task) }
  1423. }
  1424. }
  1425. return self
  1426. }
  1427. /// Validates the request, using the specified closure.
  1428. ///
  1429. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  1430. ///
  1431. /// - Parameter validation: `Validation` closure to validate the response.
  1432. ///
  1433. /// - Returns: The instance.
  1434. @discardableResult
  1435. public func validate(_ validation: @escaping Validation) -> Self {
  1436. let validator: () -> Void = { [unowned self] in
  1437. guard error == nil, let response = response else { return }
  1438. let result = validation(request, response, fileURL)
  1439. if case let .failure(error) = result {
  1440. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  1441. }
  1442. eventMonitor?.request(self,
  1443. didValidateRequest: request,
  1444. response: response,
  1445. fileURL: fileURL,
  1446. withResult: result)
  1447. }
  1448. $validators.write { $0.append(validator) }
  1449. return self
  1450. }
  1451. }
  1452. // MARK: - UploadRequest
  1453. /// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`.
  1454. public class UploadRequest: DataRequest {
  1455. /// Type describing the origin of the upload, whether `Data`, file, or stream.
  1456. public enum Uploadable {
  1457. /// Upload from the provided `Data` value.
  1458. case data(Data)
  1459. /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be
  1460. /// automatically removed once uploaded.
  1461. case file(URL, shouldRemove: Bool)
  1462. /// Upload from the provided `InputStream`.
  1463. case stream(InputStream)
  1464. }
  1465. // MARK: Initial State
  1466. /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance.
  1467. public let upload: UploadableConvertible
  1468. /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written
  1469. /// to disk.
  1470. public let fileManager: FileManager
  1471. // MARK: Mutable State
  1472. /// `Uploadable` value used by the instance.
  1473. public var uploadable: Uploadable?
  1474. /// Creates an `UploadRequest` using the provided parameters.
  1475. ///
  1476. /// - Parameters:
  1477. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  1478. /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed.
  1479. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1480. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  1481. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1482. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1483. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1484. /// - fileManager: `FileManager` used to perform cleanup tasks, including the removal of multipart form
  1485. /// encoded payloads written to disk.
  1486. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  1487. init(id: UUID = UUID(),
  1488. convertible: UploadConvertible,
  1489. underlyingQueue: DispatchQueue,
  1490. serializationQueue: DispatchQueue,
  1491. eventMonitor: EventMonitor?,
  1492. interceptor: RequestInterceptor?,
  1493. fileManager: FileManager,
  1494. delegate: RequestDelegate) {
  1495. upload = convertible
  1496. self.fileManager = fileManager
  1497. super.init(id: id,
  1498. convertible: convertible,
  1499. underlyingQueue: underlyingQueue,
  1500. serializationQueue: serializationQueue,
  1501. eventMonitor: eventMonitor,
  1502. interceptor: interceptor,
  1503. delegate: delegate)
  1504. }
  1505. /// Called when the `Uploadable` value has been created from the `UploadConvertible`.
  1506. ///
  1507. /// - Parameter uploadable: The `Uploadable` that was created.
  1508. func didCreateUploadable(_ uploadable: Uploadable) {
  1509. self.uploadable = uploadable
  1510. eventMonitor?.request(self, didCreateUploadable: uploadable)
  1511. }
  1512. /// Called when the `Uploadable` value could not be created.
  1513. ///
  1514. /// - Parameter error: `AFError` produced by the failure.
  1515. func didFailToCreateUploadable(with error: AFError) {
  1516. self.error = error
  1517. eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
  1518. retryOrFinish(error: error)
  1519. }
  1520. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1521. guard let uploadable = uploadable else {
  1522. fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
  1523. }
  1524. switch uploadable {
  1525. case let .data(data): return session.uploadTask(with: request, from: data)
  1526. case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
  1527. case .stream: return session.uploadTask(withStreamedRequest: request)
  1528. }
  1529. }
  1530. override func reset() {
  1531. // Uploadable must be recreated on every retry.
  1532. uploadable = nil
  1533. super.reset()
  1534. }
  1535. /// Produces the `InputStream` from `uploadable`, if it can.
  1536. ///
  1537. /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash.
  1538. ///
  1539. /// - Returns: The `InputStream`.
  1540. func inputStream() -> InputStream {
  1541. guard let uploadable = uploadable else {
  1542. fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
  1543. }
  1544. guard case let .stream(stream) = uploadable else {
  1545. fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
  1546. }
  1547. eventMonitor?.request(self, didProvideInputStream: stream)
  1548. return stream
  1549. }
  1550. override public func cleanup() {
  1551. defer { super.cleanup() }
  1552. guard
  1553. let uploadable = uploadable,
  1554. case let .file(url, shouldRemove) = uploadable,
  1555. shouldRemove
  1556. else { return }
  1557. try? fileManager.removeItem(at: url)
  1558. }
  1559. }
  1560. /// A type that can produce an `UploadRequest.Uploadable` value.
  1561. public protocol UploadableConvertible {
  1562. /// Produces an `UploadRequest.Uploadable` value from the instance.
  1563. ///
  1564. /// - Returns: The `UploadRequest.Uploadable`.
  1565. /// - Throws: Any `Error` produced during creation.
  1566. func createUploadable() throws -> UploadRequest.Uploadable
  1567. }
  1568. extension UploadRequest.Uploadable: UploadableConvertible {
  1569. public func createUploadable() throws -> UploadRequest.Uploadable {
  1570. self
  1571. }
  1572. }
  1573. /// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`.
  1574. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {}