Request.swift 78 KB

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