Request.swift 77 KB

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