Request.swift 77 KB

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