Request.swift 78 KB

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