2
0

Request.swift 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  1. //
  2. // Request.swift
  3. //
  4. // Copyright (c) 2014-2018 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` prividing 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. /// Closure called when the `Request` is able to create a cURL description of itself.
  89. var cURLHandler: ((String) -> Void)?
  90. /// Response serialization closures that handle response parsing.
  91. var responseSerializers: [() -> Void] = []
  92. /// Response serialization completion closures executed once all response serializers are complete.
  93. var responseSerializerCompletions: [() -> Void] = []
  94. /// Whether response serializer processing is finished.
  95. var responseSerializerProcessingFinished = false
  96. /// `URLCredential` used for authentication challenges.
  97. var credential: URLCredential?
  98. /// All `URLRequest`s created by Alamofire on behalf of the `Request`.
  99. var requests: [URLRequest] = []
  100. /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`.
  101. var tasks: [URLSessionTask] = []
  102. /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond
  103. /// exactly the the `tasks` created.
  104. var metrics: [URLSessionTaskMetrics] = []
  105. /// Number of times any retriers provided retried the `Request`.
  106. var retryCount = 0
  107. /// Final `Error` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`.
  108. var error: Error?
  109. }
  110. /// Protected `MutableState` value that provides threadsafe access to state values.
  111. fileprivate let protectedMutableState: Protector<MutableState> = Protector(MutableState())
  112. /// `State` of the `Request`.
  113. public var state: State { return protectedMutableState.directValue.state }
  114. /// Returns whether `state` is `.initialized`.
  115. public var isInitialized: Bool { return state == .initialized }
  116. /// Returns whether `state is `.resumed`.
  117. public var isResumed: Bool { return state == .resumed }
  118. /// Returns whether `state` is `.suspended`.
  119. public var isSuspended: Bool { return state == .suspended }
  120. /// Returns whether `state` is `.cancelled`.
  121. public var isCancelled: Bool { return state == .cancelled }
  122. /// Returns whether `state` is `.finished`.
  123. public var isFinished: Bool { return state == .finished }
  124. // MARK: Progress
  125. /// Closure type executed when monitoring the upload or download progress of a request.
  126. public typealias ProgressHandler = (Progress) -> Void
  127. /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried.
  128. public let uploadProgress = Progress(totalUnitCount: 0)
  129. /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried.
  130. public let downloadProgress = Progress(totalUnitCount: 0)
  131. /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`.
  132. fileprivate var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
  133. get { return protectedMutableState.directValue.uploadProgressHandler }
  134. set { protectedMutableState.write { $0.uploadProgressHandler = newValue } }
  135. }
  136. /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`.
  137. fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
  138. get { return protectedMutableState.directValue.downloadProgressHandler }
  139. set { protectedMutableState.write { $0.downloadProgressHandler = newValue } }
  140. }
  141. // MARK: Redirect Handling
  142. /// `RedirectHandler` set on the instance.
  143. public private(set) var redirectHandler: RedirectHandler? {
  144. get { return protectedMutableState.directValue.redirectHandler }
  145. set { protectedMutableState.write { $0.redirectHandler = newValue } }
  146. }
  147. // MARK: Cached Response Handling
  148. /// `CachedResponseHandler` set on the instance.
  149. public private(set) var cachedResponseHandler: CachedResponseHandler? {
  150. get { return protectedMutableState.directValue.cachedResponseHandler }
  151. set { protectedMutableState.write { $0.cachedResponseHandler = newValue } }
  152. }
  153. // MARK: URLCredential
  154. /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods.
  155. public private(set) var credential: URLCredential? {
  156. get { return protectedMutableState.directValue.credential }
  157. set { protectedMutableState.write { $0.credential = newValue } }
  158. }
  159. // MARK: Validators
  160. /// `Validator` callback closures that store the validation calls enqueued.
  161. fileprivate var protectedValidators: Protector<[() -> Void]> = Protector([])
  162. // MARK: URLRequests
  163. /// All `URLRequests` created on behalf of the `Request`, including original and adapted requests.
  164. public var requests: [URLRequest] { return protectedMutableState.directValue.requests }
  165. /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed.
  166. public var firstRequest: URLRequest? { return requests.first }
  167. /// Last `URLRequest` created on behalf of the `Request`.
  168. public var lastRequest: URLRequest? { return requests.last }
  169. /// Current `URLRequest` created on behalf of the `Request`.
  170. public var request: URLRequest? { return lastRequest }
  171. /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from
  172. /// `requests` due to `URLSession` manipulation.
  173. public var performedRequests: [URLRequest] {
  174. return protectedMutableState.read { $0.tasks.compactMap { $0.currentRequest } }
  175. }
  176. // MARK: HTTPURLResponse
  177. /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the
  178. /// last `URLSessionTask`.
  179. public var response: HTTPURLResponse? { return lastTask?.response as? HTTPURLResponse }
  180. // MARK: Tasks
  181. /// All `URLSessionTask`s created on behalf of the `Request`.
  182. public var tasks: [URLSessionTask] { return protectedMutableState.directValue.tasks }
  183. /// First `URLSessionTask` created on behalf of the `Request`.
  184. public var firstTask: URLSessionTask? { return tasks.first }
  185. /// Last `URLSessionTask` crated on behalf of the `Request`.
  186. public var lastTask: URLSessionTask? { return tasks.last }
  187. /// Current `URLSessionTask` created on behalf of the `Request`.
  188. public var task: URLSessionTask? { return lastTask }
  189. // MARK: Metrics
  190. /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created.
  191. public var allMetrics: [URLSessionTaskMetrics] { return protectedMutableState.directValue.metrics }
  192. /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  193. public var firstMetrics: URLSessionTaskMetrics? { return allMetrics.first }
  194. /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  195. public var lastMetrics: URLSessionTaskMetrics? { return allMetrics.last }
  196. /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  197. public var metrics: URLSessionTaskMetrics? { return lastMetrics }
  198. // MARK: Retry Count
  199. /// Number of times the `Request` has been retried.
  200. public var retryCount: Int { return protectedMutableState.directValue.retryCount }
  201. // MARK: Error
  202. /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed.
  203. fileprivate(set) public var error: Error? {
  204. get { return protectedMutableState.directValue.error }
  205. set { protectedMutableState.write { $0.error = newValue } }
  206. }
  207. /// Default initializer for the `Request` superclass.
  208. ///
  209. /// - Parameters:
  210. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  211. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  212. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  213. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  214. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  215. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  216. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  217. init(id: UUID = UUID(),
  218. underlyingQueue: DispatchQueue,
  219. serializationQueue: DispatchQueue,
  220. eventMonitor: EventMonitor?,
  221. interceptor: RequestInterceptor?,
  222. delegate: RequestDelegate) {
  223. self.id = id
  224. self.underlyingQueue = underlyingQueue
  225. self.serializationQueue = serializationQueue
  226. self.eventMonitor = eventMonitor
  227. self.interceptor = interceptor
  228. self.delegate = delegate
  229. }
  230. // MARK: - Internal Event API
  231. // All API must be called from underlyingQueue.
  232. /// Called when a initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active,
  233. /// the `URLRequest` will be adapted before being issued.
  234. ///
  235. /// - Parameter request: The `URLRequest` created.
  236. func didCreateInitialURLRequest(_ request: URLRequest) {
  237. protectedMutableState.write { $0.requests.append(request) }
  238. eventMonitor?.request(self, didCreateInitialURLRequest: request)
  239. }
  240. /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`.
  241. ///
  242. /// - Note: Triggers retry.
  243. ///
  244. /// - Parameter error: `Error` thrown from the failed creation.
  245. func didFailToCreateURLRequest(with error: Error) {
  246. self.error = error
  247. eventMonitor?.request(self, didFailToCreateURLRequestWithError: error)
  248. callCURLHandlerIfNecessary()
  249. retryOrFinish(error: error)
  250. }
  251. /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`.
  252. ///
  253. /// - Parameters:
  254. /// - initialRequest: The `URLRequest` that was adapted.
  255. /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`.
  256. func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) {
  257. protectedMutableState.write { $0.requests.append(adaptedRequest) }
  258. eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest)
  259. }
  260. /// Called when a `RequestAdapter` fails to adapt a `URLRequest`.
  261. ///
  262. /// - Note: Triggers retry.
  263. ///
  264. /// - Parameters:
  265. /// - request: The `URLRequest` the adapter was called with.
  266. /// - error: The `Error` returned by the `RequestAdapter`.
  267. func didFailToAdaptURLRequest(_ request: URLRequest, withError error: Error) {
  268. self.error = error
  269. eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error)
  270. callCURLHandlerIfNecessary()
  271. retryOrFinish(error: error)
  272. }
  273. /// Final `URLRequest` has been created for the instance.
  274. ///
  275. /// - Parameter request: The `URLRequest` created.
  276. func didCreateURLRequest(_ request: URLRequest) {
  277. eventMonitor?.request(self, didCreateURLRequest: request)
  278. callCURLHandlerIfNecessary()
  279. }
  280. /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`.
  281. private func callCURLHandlerIfNecessary() {
  282. protectedMutableState.write { mutableState in
  283. guard let cURLHandler = mutableState.cURLHandler else { return }
  284. self.underlyingQueue.async { cURLHandler(self.cURLDescription()) }
  285. mutableState.cURLHandler = nil
  286. }
  287. }
  288. /// Called when a `URLSessionTask` is created on behalf of the instance.
  289. ///
  290. /// - Parameter task: The `URLSessionTask` created.
  291. func didCreateTask(_ task: URLSessionTask) {
  292. protectedMutableState.write { $0.tasks.append(task) }
  293. eventMonitor?.request(self, didCreateTask: task)
  294. }
  295. /// Called when resumption is completed.
  296. func didResume() {
  297. eventMonitor?.requestDidResume(self)
  298. }
  299. /// Called when a `URLSessionTask` is resumed on behalf of the instance.
  300. ///
  301. /// - Parameter task: The `URLSessionTask` resumed.
  302. func didResumeTask(_ task: URLSessionTask) {
  303. eventMonitor?.request(self, didResumeTask: task)
  304. }
  305. /// Called when suspension is completed.
  306. func didSuspend() {
  307. eventMonitor?.requestDidSuspend(self)
  308. }
  309. /// Called when a `URLSessionTask` is suspended on behalf of the instance.
  310. ///
  311. /// - Parameter task: The `URLSessionTask` suspended.
  312. func didSuspendTask(_ task: URLSessionTask) {
  313. eventMonitor?.request(self, didSuspendTask: task)
  314. }
  315. /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`.
  316. func didCancel() {
  317. error = AFError.explicitlyCancelled
  318. eventMonitor?.requestDidCancel(self)
  319. }
  320. /// Called when a `URLSessionTask` is cancelled on behalf of the instance.
  321. ///
  322. /// - Parameter task: The `URLSessionTask` cancelled.
  323. func didCancelTask(_ task: URLSessionTask) {
  324. eventMonitor?.request(self, didCancelTask: task)
  325. }
  326. /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance.
  327. ///
  328. /// - Parameter metrics: The `URLSessionTaskMetrics` gathered.
  329. func didGatherMetrics(_ metrics: URLSessionTaskMetrics) {
  330. protectedMutableState.write { $0.metrics.append(metrics) }
  331. eventMonitor?.request(self, didGatherMetrics: metrics)
  332. }
  333. /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning.
  334. ///
  335. /// - Parameters:
  336. /// - task: The `URLSessionTask` which failed.
  337. /// - error: The early failure `Error`.
  338. func didFailTask(_ task: URLSessionTask, earlyWithError error: Error) {
  339. self.error = error
  340. // Task will still complete, so didCompleteTask(_:with:) will handle retry.
  341. eventMonitor?.request(self, didFailTask: task, earlyWithError: error)
  342. }
  343. /// Called when a `URLSessionTask` completes. All tasks will eventually call this method.
  344. ///
  345. /// - Note: Response validation is synchronously triggered in this step.
  346. ///
  347. /// - Parameters:
  348. /// - task: The `URLSessionTask` which completed.
  349. /// - error: The `Error` `task` may have completed with. If `error` has already been set on the instance, this
  350. /// value is ignored.
  351. func didCompleteTask(_ task: URLSessionTask, with error: Error?) {
  352. self.error = self.error ?? error
  353. protectedValidators.directValue.forEach { $0() }
  354. eventMonitor?.request(self, didCompleteTask: task, with: error)
  355. retryOrFinish(error: self.error)
  356. }
  357. /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`.
  358. func prepareForRetry() {
  359. protectedMutableState.write { $0.retryCount += 1 }
  360. reset()
  361. eventMonitor?.requestIsRetrying(self)
  362. }
  363. /// Called to determine whether retry will be triggered for the particular error, or whether the instance should
  364. /// call `finish()`.
  365. ///
  366. /// - Parameter error: The possible `Error` which may trigger retry.
  367. func retryOrFinish(error: Error?) {
  368. guard let error = error, let delegate = delegate else { finish(); return }
  369. delegate.retryResult(for: self, dueTo: error) { retryResult in
  370. switch retryResult {
  371. case .doNotRetry, .doNotRetryWithError:
  372. self.finish(error: retryResult.error)
  373. case .retry, .retryWithDelay:
  374. delegate.retryRequest(self, withDelay: retryResult.delay)
  375. }
  376. }
  377. }
  378. /// Finishes this `Request` and starts the response serializers.
  379. ///
  380. /// - Parameter error: The possible `Error` with which the instance will finish.
  381. func finish(error: Error? = nil) {
  382. if let error = error { self.error = error }
  383. // Start response handlers
  384. processNextResponseSerializer()
  385. eventMonitor?.requestDidFinish(self)
  386. }
  387. /// Appends the response serialization closure to the instance.
  388. ///
  389. /// - Parameter closure: The closure containing the response serialization call.
  390. func appendResponseSerializer(_ closure: @escaping () -> Void) {
  391. protectedMutableState.write { mutableState in
  392. mutableState.responseSerializers.append(closure)
  393. if mutableState.state == .finished {
  394. mutableState.state = .resumed
  395. }
  396. if mutableState.responseSerializerProcessingFinished {
  397. underlyingQueue.async { self.processNextResponseSerializer() }
  398. }
  399. }
  400. }
  401. /// Returns the next response serializer closure to execute if there's one left.
  402. ///
  403. /// - Returns: The next response serialization closure, if there is one.
  404. func nextResponseSerializer() -> (() -> Void)? {
  405. var responseSerializer: (() -> Void)?
  406. protectedMutableState.write { mutableState in
  407. let responseSerializerIndex = mutableState.responseSerializerCompletions.count
  408. if responseSerializerIndex < mutableState.responseSerializers.count {
  409. responseSerializer = mutableState.responseSerializers[responseSerializerIndex]
  410. }
  411. }
  412. return responseSerializer
  413. }
  414. /// Processes the next response serializer and calls all completions if response serialization is complete.
  415. func processNextResponseSerializer() {
  416. guard let responseSerializer = nextResponseSerializer() else {
  417. // Execute all response serializer completions and clear them
  418. var completions: [() -> Void] = []
  419. protectedMutableState.write { mutableState in
  420. completions = mutableState.responseSerializerCompletions
  421. // Clear out all response serializers and response serializer completions in mutable state since the
  422. // request is complete. It's important to do this prior to calling the completion closures in case
  423. // the completions call back into the request triggering a re-processing of the response serializers.
  424. // An example of how this can happen is by calling cancel inside a response completion closure.
  425. mutableState.responseSerializers.removeAll()
  426. mutableState.responseSerializerCompletions.removeAll()
  427. if mutableState.state.canTransitionTo(.finished) {
  428. mutableState.state = .finished
  429. }
  430. mutableState.responseSerializerProcessingFinished = true
  431. }
  432. completions.forEach { $0() }
  433. // Cleanup the request
  434. cleanup()
  435. return
  436. }
  437. serializationQueue.async { responseSerializer() }
  438. }
  439. /// Notifies the `Request` that the response serializer is complete.
  440. ///
  441. /// - Parameter completion: The completion handler provided with the response serilizer, called when all serializers
  442. /// are complete.
  443. func responseSerializerDidComplete(completion: @escaping () -> Void) {
  444. protectedMutableState.write { $0.responseSerializerCompletions.append(completion) }
  445. processNextResponseSerializer()
  446. }
  447. /// Resets all task and response serializer related state for retry.
  448. func reset() {
  449. error = nil
  450. uploadProgress.totalUnitCount = 0
  451. uploadProgress.completedUnitCount = 0
  452. downloadProgress.totalUnitCount = 0
  453. downloadProgress.completedUnitCount = 0
  454. protectedMutableState.write { $0.responseSerializerCompletions = [] }
  455. }
  456. /// Called when updating the upload progress.
  457. ///
  458. /// - Parameters:
  459. /// - totalBytesSent: Total bytes sent so far.
  460. /// - totalBytesExpectedToSend: Total bytes expected to send.
  461. func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  462. uploadProgress.totalUnitCount = totalBytesExpectedToSend
  463. uploadProgress.completedUnitCount = totalBytesSent
  464. uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
  465. }
  466. /// Perform a closure on the current `state` while locked.
  467. ///
  468. /// - Parameter perform: The closure to perform.
  469. func withState(perform: (State) -> Void) {
  470. protectedMutableState.withState(perform: perform)
  471. }
  472. // MARK: Task Creation
  473. /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
  474. ///
  475. /// - Parameters:
  476. /// - request: `URLRequest` to use to create the `URLSessionTask`.
  477. /// - session: `URLSession` which creates the `URLSessionTask`.
  478. ///
  479. /// - Returns: The `URLSessionTask` created.
  480. func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  481. fatalError("Subclasses must override.")
  482. }
  483. // MARK: - Public API
  484. // These APIs are callable from any queue.
  485. // MARK: State
  486. /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended.
  487. ///
  488. /// - Returns: The instance.
  489. @discardableResult
  490. public func cancel() -> Self {
  491. protectedMutableState.write { (mutableState) in
  492. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  493. mutableState.state = .cancelled
  494. underlyingQueue.async { self.didCancel() }
  495. guard let task = mutableState.tasks.last, task.state != .completed else {
  496. underlyingQueue.async { self.finish() }
  497. return
  498. }
  499. task.cancel()
  500. underlyingQueue.async { self.didCancelTask(task) }
  501. }
  502. return self
  503. }
  504. /// Suspends the instance.
  505. ///
  506. /// - Returns: The instance.
  507. @discardableResult
  508. public func suspend() -> Self {
  509. protectedMutableState.write { (mutableState) in
  510. guard mutableState.state.canTransitionTo(.suspended) else { return }
  511. mutableState.state = .suspended
  512. underlyingQueue.async { self.didSuspend() }
  513. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  514. task.suspend()
  515. underlyingQueue.async { self.didSuspendTask(task) }
  516. }
  517. return self
  518. }
  519. /// Resumes the instance.
  520. ///
  521. /// - Returns: The instance.
  522. @discardableResult
  523. public func resume() -> Self {
  524. protectedMutableState.write { (mutableState) in
  525. guard mutableState.state.canTransitionTo(.resumed) else { return }
  526. mutableState.state = .resumed
  527. underlyingQueue.async { self.didResume() }
  528. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  529. task.resume()
  530. underlyingQueue.async { self.didResumeTask(task) }
  531. }
  532. return self
  533. }
  534. // MARK: - Closure API
  535. /// Associates a credential using the provided values with the instance.
  536. ///
  537. /// - Parameters:
  538. /// - username: The username.
  539. /// - password: The password.
  540. /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default.
  541. ///
  542. /// - Returns: The instance.
  543. @discardableResult
  544. public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
  545. let credential = URLCredential(user: username, password: password, persistence: persistence)
  546. return authenticate(with: credential)
  547. }
  548. /// Associates the provided credential with the instance.
  549. ///
  550. /// - Parameter credential: The `URLCredential`.
  551. ///
  552. /// - Returns: The instance.
  553. @discardableResult
  554. public func authenticate(with credential: URLCredential) -> Self {
  555. protectedMutableState.write { $0.credential = credential }
  556. return self
  557. }
  558. /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server.
  559. ///
  560. /// - Note: Only the last closure provided is used.
  561. ///
  562. /// - Parameters:
  563. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  564. /// - closure: The closure to be executed periodically as data is read from the server.
  565. ///
  566. /// - Returns: The instance.
  567. @discardableResult
  568. public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  569. protectedMutableState.write { $0.downloadProgressHandler = (handler: closure, queue: queue) }
  570. return self
  571. }
  572. /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.
  573. ///
  574. /// - Note: Only the last closure provided is used.
  575. ///
  576. /// - Parameters:
  577. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  578. /// - closure: The closure to be executed periodically as data is sent to the server.
  579. ///
  580. /// - Returns: The instance.
  581. @discardableResult
  582. public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  583. protectedMutableState.write { $0.uploadProgressHandler = (handler: closure, queue: queue) }
  584. return self
  585. }
  586. // MARK: Redirects
  587. /// Sets the redirect handler for the instance which will be used if a redirect response is encountered.
  588. ///
  589. /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash.
  590. ///
  591. /// - Parameter handler: The `RedirectHandler`.
  592. ///
  593. /// - Returns: The instance.
  594. @discardableResult
  595. public func redirect(using handler: RedirectHandler) -> Self {
  596. protectedMutableState.write { mutableState in
  597. precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.")
  598. mutableState.redirectHandler = handler
  599. }
  600. return self
  601. }
  602. // MARK: Cached Responses
  603. /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response.
  604. ///
  605. /// - Note: Attempting to set the cache handler more than once is a logic error and will crash.
  606. ///
  607. /// - Parameter handler: The `CachedResponseHandler`.
  608. ///
  609. /// - Returns: The instance.
  610. @discardableResult
  611. public func cacheResponse(using handler: CachedResponseHandler) -> Self {
  612. protectedMutableState.write { mutableState in
  613. precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.")
  614. mutableState.cachedResponseHandler = handler
  615. }
  616. return self
  617. }
  618. /// Sets a handler to be called when the cURL description of the request is available.
  619. ///
  620. /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
  621. ///
  622. /// - Parameter handler: Closure to be called when the cURL description is available.
  623. ///
  624. /// - Returns: The instance.
  625. @discardableResult
  626. public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self {
  627. protectedMutableState.write { mutableState in
  628. if mutableState.requests.last != nil {
  629. underlyingQueue.async { handler(self.cURLDescription()) }
  630. } else {
  631. mutableState.cURLHandler = handler
  632. }
  633. }
  634. return self
  635. }
  636. // MARK: Cleanup
  637. /// Final cleanup step executed when the instance finishes response serialization.
  638. open func cleanup() {
  639. // No-op: override in subclass
  640. }
  641. }
  642. // MARK: - Protocol Conformances
  643. extension Request: Equatable {
  644. public static func == (lhs: Request, rhs: Request) -> Bool {
  645. return lhs.id == rhs.id
  646. }
  647. }
  648. extension Request: Hashable {
  649. public func hash(into hasher: inout Hasher) {
  650. hasher.combine(id)
  651. }
  652. }
  653. extension Request: CustomStringConvertible {
  654. /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
  655. /// created, as well as the response status code, if a response has been received.
  656. public var description: String {
  657. guard let request = performedRequests.last ?? lastRequest,
  658. let url = request.url,
  659. let method = request.httpMethod else { return "No request created yet." }
  660. let requestDescription = "\(method) \(url.absoluteString)"
  661. return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
  662. }
  663. }
  664. extension Request {
  665. /// cURL representation of the instance.
  666. ///
  667. /// - Returns: The cURL equivalent of the instance.
  668. public func cURLDescription() -> String {
  669. guard
  670. let request = lastRequest,
  671. let url = request.url,
  672. let host = url.host,
  673. let method = request.httpMethod else { return "$ curl command could not be created" }
  674. var components = ["$ curl -v"]
  675. components.append("-X \(method)")
  676. if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
  677. let protectionSpace = URLProtectionSpace(
  678. host: host,
  679. port: url.port ?? 0,
  680. protocol: url.scheme,
  681. realm: host,
  682. authenticationMethod: NSURLAuthenticationMethodHTTPBasic
  683. )
  684. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  685. for credential in credentials {
  686. guard let user = credential.user, let password = credential.password else { continue }
  687. components.append("-u \(user):\(password)")
  688. }
  689. } else {
  690. if let credential = credential, let user = credential.user, let password = credential.password {
  691. components.append("-u \(user):\(password)")
  692. }
  693. }
  694. }
  695. if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
  696. if
  697. let cookieStorage = configuration.httpCookieStorage,
  698. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
  699. {
  700. let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
  701. components.append("-b \"\(allCookies)\"")
  702. }
  703. }
  704. var headers: [String: String] = [:]
  705. if let additionalHeaders = delegate?.sessionConfiguration.httpAdditionalHeaders as? [String: String] {
  706. for (field, value) in additionalHeaders where field != "Cookie" {
  707. headers[field] = value
  708. }
  709. }
  710. if let headerFields = request.allHTTPHeaderFields {
  711. for (field, value) in headerFields where field != "Cookie" {
  712. headers[field] = value
  713. }
  714. }
  715. for (field, value) in headers {
  716. let escapedValue = value.replacingOccurrences(of: "\"", with: "\\\"")
  717. components.append("-H \"\(field): \(escapedValue)\"")
  718. }
  719. if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
  720. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  721. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  722. components.append("-d \"\(escapedBody)\"")
  723. }
  724. components.append("\"\(url.absoluteString)\"")
  725. return components.joined(separator: " \\\n\t")
  726. }
  727. }
  728. /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
  729. public protocol RequestDelegate: AnyObject {
  730. /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s.
  731. var sessionConfiguration: URLSessionConfiguration { get }
  732. /// Asynchronously ask the delegate whether a `Request` will be retried.
  733. ///
  734. /// - Parameters:
  735. /// - request: `Request` which failed.
  736. /// - error: `Error` which produced the failure.
  737. /// - completion: Closure taking the `RetryResult` for evaluation.
  738. func retryResult(for request: Request, dueTo error: Error, completion: @escaping (RetryResult) -> Void)
  739. /// Asynchronously retry the `Request`.
  740. ///
  741. /// - Parameters:
  742. /// - request: `Request` which will be retried.
  743. /// - timeDelay: `TimeInterval` after which the retry will be triggered.
  744. func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
  745. }
  746. // MARK: - Subclasses
  747. // MARK: - DataRequest
  748. /// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`.
  749. public class DataRequest: Request {
  750. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  751. public let convertible: URLRequestConvertible
  752. /// `Data` read from the server so far.
  753. public var data: Data? { return protectedData.directValue }
  754. /// Protected storage for the `Data` read by the instance.
  755. private var protectedData: Protector<Data?> = Protector(nil)
  756. /// Creates a `DataRequest` using the provided parameters.
  757. ///
  758. /// - Parameters:
  759. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  760. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  761. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  762. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  763. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  764. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  765. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  766. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  767. init(id: UUID = UUID(),
  768. convertible: URLRequestConvertible,
  769. underlyingQueue: DispatchQueue,
  770. serializationQueue: DispatchQueue,
  771. eventMonitor: EventMonitor?,
  772. interceptor: RequestInterceptor?,
  773. delegate: RequestDelegate) {
  774. self.convertible = convertible
  775. super.init(id: id,
  776. underlyingQueue: underlyingQueue,
  777. serializationQueue: serializationQueue,
  778. eventMonitor: eventMonitor,
  779. interceptor: interceptor,
  780. delegate: delegate)
  781. }
  782. override func reset() {
  783. super.reset()
  784. protectedData.directValue = nil
  785. }
  786. /// Called when `Data` is received by this instance.
  787. ///
  788. /// - Note: Also calls `updateDownloadProgress`.
  789. ///
  790. /// - Parameter data: The `Data` received.
  791. func didReceive(data: Data) {
  792. if self.data == nil {
  793. protectedData.directValue = data
  794. } else {
  795. protectedData.append(data)
  796. }
  797. updateDownloadProgress()
  798. }
  799. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  800. let copiedRequest = request
  801. return session.dataTask(with: copiedRequest)
  802. }
  803. /// Called to updated the `downloadProgress` of the instance.
  804. func updateDownloadProgress() {
  805. let totalBytesReceived = Int64(data?.count ?? 0)
  806. let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  807. downloadProgress.totalUnitCount = totalBytesExpected
  808. downloadProgress.completedUnitCount = totalBytesReceived
  809. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  810. }
  811. /// Validates the request, using the specified closure.
  812. ///
  813. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  814. ///
  815. /// - Parameter validation: `Validation` closure used to validate the response.
  816. ///
  817. /// - Returns: The instance.
  818. @discardableResult
  819. public func validate(_ validation: @escaping Validation) -> Self {
  820. let validator: () -> Void = { [unowned self] in
  821. guard self.error == nil, let response = self.response else { return }
  822. let result = validation(self.request, response, self.data)
  823. if case .failure(let error) = result { self.error = error }
  824. self.eventMonitor?.request(self,
  825. didValidateRequest: self.request,
  826. response: response,
  827. data: self.data,
  828. withResult: result)
  829. }
  830. protectedValidators.append(validator)
  831. return self
  832. }
  833. }
  834. // MARK: - DownloadRequest
  835. /// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`.
  836. public class DownloadRequest: Request {
  837. /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination
  838. /// `URL`.
  839. public struct Options: OptionSet {
  840. /// Specifies that intermediate directories for the destination URL should be created.
  841. public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
  842. /// Specifies that any previous file at the destination `URL` should be removed.
  843. public static let removePreviousFile = Options(rawValue: 1 << 1)
  844. /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
  845. public let rawValue: Int
  846. public init(rawValue: Int) {
  847. self.rawValue = rawValue
  848. }
  849. }
  850. // MARK: Destination
  851. /// A closure executed once a download request has successfully completed in order to determine where to move the
  852. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  853. /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
  854. /// the options defining how the file should be moved.
  855. public typealias Destination = (_ temporaryURL: URL,
  856. _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
  857. // MARK: Destination
  858. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  859. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  860. ///
  861. /// - Parameters:
  862. /// - directory: The search path directory. `.documentDirectory` by default.
  863. /// - domain: The search path domain mask. `.userDomainMask` by default.
  864. /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by
  865. /// default.
  866. /// - Returns: The `Destination` closure.
  867. public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
  868. in domain: FileManager.SearchPathDomainMask = .userDomainMask,
  869. options: Options = []) -> Destination {
  870. return { temporaryURL, response in
  871. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  872. let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
  873. return (url, options)
  874. }
  875. }
  876. /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends
  877. /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files
  878. /// with this destination must be additionally moved if they should survive the system reclamation of temporary
  879. /// space.
  880. static let defaultDestination: Destination = { (url, _) in
  881. let filename = "Alamofire_\(url.lastPathComponent)"
  882. let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
  883. return (destination, [])
  884. }
  885. /// Type describing the source used to create the underlying `URLSessionDownloadTask`.
  886. public enum Downloadable {
  887. /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value.
  888. case request(URLRequestConvertible)
  889. /// Download should be started from the associated resume `Data` value.
  890. case resumeData(Data)
  891. }
  892. // MARK: Mutable State
  893. /// Type containing all mutable state for `DownloadRequest` instances.
  894. private struct DownloadRequestMutableState {
  895. /// Possible resume `Data` produced when cancelling the instance.
  896. var resumeData: Data?
  897. /// `URL` to which `Data` is being downloaded.
  898. var fileURL: URL?
  899. }
  900. /// Protected mutable state specific to `DownloadRequest`.
  901. private let protectedDownloadMutableState: Protector<DownloadRequestMutableState> = Protector(DownloadRequestMutableState())
  902. /// If the download is resumable and eventually cancelled, this value may be used to resume the download using the
  903. /// `download(resumingWith data:)` API.
  904. ///
  905. /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel).
  906. public var resumeData: Data? { return protectedDownloadMutableState.directValue.resumeData }
  907. /// If the download is successful, the `URL` where the file was downloaded.
  908. public var fileURL: URL? { return protectedDownloadMutableState.directValue.fileURL }
  909. // MARK: Initial State
  910. /// `Downloadable` value used for this instance.
  911. public let downloadable: Downloadable
  912. /// The `Destination` to which the downloaded file is moved.
  913. let destination: Destination
  914. /// Creates a `DownloadRequest` using the provided parameters.
  915. ///
  916. /// - Parameters:
  917. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  918. /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance.
  919. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  920. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  921. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  922. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  923. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  924. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`
  925. /// - destination: `Destination` closure used to move the downloaded file to its final location.
  926. init(id: UUID = UUID(),
  927. downloadable: Downloadable,
  928. underlyingQueue: DispatchQueue,
  929. serializationQueue: DispatchQueue,
  930. eventMonitor: EventMonitor?,
  931. interceptor: RequestInterceptor?,
  932. delegate: RequestDelegate,
  933. destination: @escaping Destination) {
  934. self.downloadable = downloadable
  935. self.destination = destination
  936. super.init(id: id,
  937. underlyingQueue: underlyingQueue,
  938. serializationQueue: serializationQueue,
  939. eventMonitor: eventMonitor,
  940. interceptor: interceptor,
  941. delegate: delegate)
  942. }
  943. override func reset() {
  944. super.reset()
  945. protectedDownloadMutableState.write {
  946. $0.resumeData = nil
  947. $0.fileURL = nil
  948. }
  949. }
  950. /// Called when a download has finished.
  951. ///
  952. /// - Parameters:
  953. /// - task: `URLSessionTask` that finished the download.
  954. /// - result: `AFResult` of the automatic move to `destination`.
  955. func didFinishDownloading(using task: URLSessionTask, with result: AFResult<URL>) {
  956. eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
  957. switch result {
  958. case .success(let url): protectedDownloadMutableState.write { $0.fileURL = url }
  959. case .failure(let error): self.error = error
  960. }
  961. }
  962. /// Updates the `downloadProgress` using the provided values.
  963. ///
  964. /// - Parameters:
  965. /// - bytesWritten: Total bytes written so far.
  966. /// - totalBytesExpectedToWrite: Total bytes expected to write.
  967. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  968. downloadProgress.totalUnitCount = totalBytesExpectedToWrite
  969. downloadProgress.completedUnitCount += bytesWritten
  970. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  971. }
  972. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  973. return session.downloadTask(with: request)
  974. }
  975. /// Creates a `URLSessionTask` from the provided resume data.
  976. ///
  977. /// - Parameters:
  978. /// - data: `Data` used to resume the download.
  979. /// - session: `URLSession` used to create the `URLSessionTask`.
  980. ///
  981. /// - Returns: The `URLSessionTask` created.
  982. public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
  983. return session.downloadTask(withResumeData: data)
  984. }
  985. /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended.
  986. ///
  987. /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use
  988. /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`.
  989. ///
  990. /// - Returns: The instance.
  991. @discardableResult
  992. public override func cancel() -> Self {
  993. return cancel(producingResumeData: false)
  994. }
  995. /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be
  996. /// resumed or suspended.
  997. ///
  998. /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if
  999. /// available.
  1000. ///
  1001. /// - Returns: The instance.
  1002. @discardableResult
  1003. public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self {
  1004. return cancel(optionallyProducingResumeData: (shouldProduceResumeData) ? { _ in } : nil)
  1005. }
  1006. /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed
  1007. /// or suspended.
  1008. ///
  1009. /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData`
  1010. /// property.
  1011. ///
  1012. /// - Parameter completionHandler: The completion handler that is called when the download has been successfully
  1013. /// cancelled. It is not guaranteed to be called on a particular queue, so you may
  1014. /// want use an appropriate queue to perform your work.
  1015. ///
  1016. /// - Returns: The instance.
  1017. @discardableResult
  1018. public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self {
  1019. return cancel(optionallyProducingResumeData: completionHandler)
  1020. }
  1021. /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed,
  1022. /// cancellation is performed without producing resume data.
  1023. ///
  1024. /// - Parameter completionHandler: Optional resume data handler.
  1025. ///
  1026. /// - Returns: The instance.
  1027. private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self {
  1028. protectedMutableState.write { (mutableState) in
  1029. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  1030. mutableState.state = .cancelled
  1031. underlyingQueue.async { self.didCancel() }
  1032. guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
  1033. underlyingQueue.async { self.finish() }
  1034. return
  1035. }
  1036. if let completionHandler = completionHandler {
  1037. task.cancel { (resumeData) in
  1038. self.protectedDownloadMutableState.write { $0.resumeData = resumeData }
  1039. self.underlyingQueue.async { self.didCancelTask(task) }
  1040. completionHandler(resumeData)
  1041. }
  1042. } else {
  1043. task.cancel()
  1044. self.underlyingQueue.async { self.didCancelTask(task) }
  1045. }
  1046. }
  1047. return self
  1048. }
  1049. /// Validates the request, using the specified closure.
  1050. ///
  1051. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  1052. ///
  1053. /// - Parameter validation: `Validation` closure to validate the response.
  1054. ///
  1055. /// - Returns: The instance.
  1056. @discardableResult
  1057. public func validate(_ validation: @escaping Validation) -> Self {
  1058. let validator: () -> Void = { [unowned self] in
  1059. guard self.error == nil, let response = self.response else { return }
  1060. let result = validation(self.request, response, self.fileURL)
  1061. if case .failure(let error) = result { self.error = error }
  1062. self.eventMonitor?.request(self,
  1063. didValidateRequest: self.request,
  1064. response: response,
  1065. fileURL: self.fileURL,
  1066. withResult: result)
  1067. }
  1068. protectedValidators.append(validator)
  1069. return self
  1070. }
  1071. }
  1072. // MARK: - UploadRequest
  1073. /// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`.
  1074. public class UploadRequest: DataRequest {
  1075. /// Type describing the origin of the upload, whether `Data`, file, or stream.
  1076. public enum Uploadable {
  1077. /// Upload from the provided `Data` value.
  1078. case data(Data)
  1079. /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be
  1080. /// automatically removed once uploaded.
  1081. case file(URL, shouldRemove: Bool)
  1082. /// Upload from the provided `InputStream`.
  1083. case stream(InputStream)
  1084. }
  1085. // MARK: Initial State
  1086. /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance.
  1087. public let upload: UploadableConvertible
  1088. // MARK: Mutable State
  1089. /// `Uploadable` value used by the instance.
  1090. public var uploadable: Uploadable?
  1091. /// Creates an `UploadRequest` using the provided parameters.
  1092. ///
  1093. /// - Parameters:
  1094. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  1095. /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed.
  1096. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1097. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  1098. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1099. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1100. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1101. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  1102. init(id: UUID = UUID(),
  1103. convertible: UploadConvertible,
  1104. underlyingQueue: DispatchQueue,
  1105. serializationQueue: DispatchQueue,
  1106. eventMonitor: EventMonitor?,
  1107. interceptor: RequestInterceptor?,
  1108. delegate: RequestDelegate) {
  1109. self.upload = convertible
  1110. super.init(id: id,
  1111. convertible: convertible,
  1112. underlyingQueue: underlyingQueue,
  1113. serializationQueue: serializationQueue,
  1114. eventMonitor: eventMonitor,
  1115. interceptor: interceptor,
  1116. delegate: delegate)
  1117. }
  1118. /// Called when the `Uploadable` value has been created from the `UploadConvertible`.
  1119. ///
  1120. /// - Parameter uploadable: The `Uploadable` that was created.
  1121. func didCreateUploadable(_ uploadable: Uploadable) {
  1122. self.uploadable = uploadable
  1123. eventMonitor?.request(self, didCreateUploadable: uploadable)
  1124. }
  1125. /// Called when the `Uploadable` value could not be created.
  1126. ///
  1127. /// - Parameter error: `Error` produced by the failure.
  1128. func didFailToCreateUploadable(with error: Error) {
  1129. self.error = error
  1130. eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
  1131. retryOrFinish(error: error)
  1132. }
  1133. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1134. guard let uploadable = uploadable else {
  1135. fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
  1136. }
  1137. switch uploadable {
  1138. case let .data(data): return session.uploadTask(with: request, from: data)
  1139. case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
  1140. case .stream: return session.uploadTask(withStreamedRequest: request)
  1141. }
  1142. }
  1143. /// Produces the `InputStream` from `uploadable`, if it can.
  1144. ///
  1145. /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash.
  1146. ///
  1147. /// - Returns: The `InputStream`.
  1148. func inputStream() -> InputStream {
  1149. guard let uploadable = uploadable else {
  1150. fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
  1151. }
  1152. guard case let .stream(stream) = uploadable else {
  1153. fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
  1154. }
  1155. eventMonitor?.request(self, didProvideInputStream: stream)
  1156. return stream
  1157. }
  1158. public override func cleanup() {
  1159. super.cleanup()
  1160. guard
  1161. let uploadable = self.uploadable,
  1162. case let .file(url, shouldRemove) = uploadable,
  1163. shouldRemove
  1164. else { return }
  1165. // TODO: Abstract file manager
  1166. try? FileManager.default.removeItem(at: url)
  1167. }
  1168. }
  1169. /// A type that can produce an `UploadRequest.Uploadable` value.
  1170. public protocol UploadableConvertible {
  1171. /// Produces an `UploadRequest.Uploadable` value from the instance.
  1172. ///
  1173. /// - Returns: The `UploadRequest.Uploadable`.
  1174. /// - Throws: Any `Error` produced during creation.
  1175. func createUploadable() throws -> UploadRequest.Uploadable
  1176. }
  1177. extension UploadRequest.Uploadable: UploadableConvertible {
  1178. public func createUploadable() throws -> UploadRequest.Uploadable {
  1179. return self
  1180. }
  1181. }
  1182. /// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`.
  1183. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible { }