Request.swift 62 KB

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