Request.swift 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917
  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. /// - Parameter closure: Closure to be called when the request finishes.
  751. func onFinish(perform finishHandler: @escaping () -> Void) {
  752. guard !isFinished else { finishHandler(); return }
  753. $mutableState.write { state in
  754. state.finishHandlers.append(finishHandler)
  755. }
  756. }
  757. /// Final cleanup step executed when the instance finishes response serialization.
  758. func cleanup() {
  759. delegate?.cleanup(after: self)
  760. let handlers = $mutableState.finishHandlers
  761. handlers.forEach { $0() }
  762. $mutableState.write { state in
  763. state.finishHandlers.removeAll()
  764. }
  765. }
  766. }
  767. // MARK: - Protocol Conformances
  768. extension Request: Equatable {
  769. public static func ==(lhs: Request, rhs: Request) -> Bool {
  770. lhs.id == rhs.id
  771. }
  772. }
  773. extension Request: Hashable {
  774. public func hash(into hasher: inout Hasher) {
  775. hasher.combine(id)
  776. }
  777. }
  778. extension Request: CustomStringConvertible {
  779. /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
  780. /// created, as well as the response status code, if a response has been received.
  781. public var description: String {
  782. guard let request = performedRequests.last ?? lastRequest,
  783. let url = request.url,
  784. let method = request.httpMethod else { return "No request created yet." }
  785. let requestDescription = "\(method) \(url.absoluteString)"
  786. return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
  787. }
  788. }
  789. #if swift(>=5.7)
  790. extension Request: @unchecked Sendable {}
  791. // extension DataRequest: @unchecked Sendable {}
  792. #endif
  793. extension Request {
  794. /// cURL representation of the instance.
  795. ///
  796. /// - Returns: The cURL equivalent of the instance.
  797. public func cURLDescription() -> String {
  798. guard
  799. let request = lastRequest,
  800. let url = request.url,
  801. let host = url.host,
  802. let method = request.httpMethod else { return "$ curl command could not be created" }
  803. var components = ["$ curl -v"]
  804. components.append("-X \(method)")
  805. if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
  806. let protectionSpace = URLProtectionSpace(host: host,
  807. port: url.port ?? 0,
  808. protocol: url.scheme,
  809. realm: host,
  810. authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  811. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  812. for credential in credentials {
  813. guard let user = credential.user, let password = credential.password else { continue }
  814. components.append("-u \(user):\(password)")
  815. }
  816. } else {
  817. if let credential = credential, let user = credential.user, let password = credential.password {
  818. components.append("-u \(user):\(password)")
  819. }
  820. }
  821. }
  822. if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
  823. if
  824. let cookieStorage = configuration.httpCookieStorage,
  825. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty {
  826. let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
  827. components.append("-b \"\(allCookies)\"")
  828. }
  829. }
  830. var headers = HTTPHeaders()
  831. if let sessionHeaders = delegate?.sessionConfiguration.headers {
  832. for header in sessionHeaders where header.name != "Cookie" {
  833. headers[header.name] = header.value
  834. }
  835. }
  836. for header in request.headers where header.name != "Cookie" {
  837. headers[header.name] = header.value
  838. }
  839. for header in headers {
  840. let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"")
  841. components.append("-H \"\(header.name): \(escapedValue)\"")
  842. }
  843. if let httpBodyData = request.httpBody {
  844. let httpBody = String(decoding: httpBodyData, as: UTF8.self)
  845. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  846. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  847. components.append("-d \"\(escapedBody)\"")
  848. }
  849. components.append("\"\(url.absoluteString)\"")
  850. return components.joined(separator: " \\\n\t")
  851. }
  852. }
  853. /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
  854. public protocol RequestDelegate: AnyObject {
  855. /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s.
  856. var sessionConfiguration: URLSessionConfiguration { get }
  857. /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler.
  858. var startImmediately: Bool { get }
  859. /// Notifies the delegate the `Request` has reached a point where it needs cleanup.
  860. ///
  861. /// - Parameter request: The `Request` to cleanup after.
  862. func cleanup(after request: Request)
  863. /// Asynchronously ask the delegate whether a `Request` will be retried.
  864. ///
  865. /// - Parameters:
  866. /// - request: `Request` which failed.
  867. /// - error: `Error` which produced the failure.
  868. /// - completion: Closure taking the `RetryResult` for evaluation.
  869. func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void)
  870. /// Asynchronously retry the `Request`.
  871. ///
  872. /// - Parameters:
  873. /// - request: `Request` which will be retried.
  874. /// - timeDelay: `TimeInterval` after which the retry will be triggered.
  875. func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
  876. }
  877. // MARK: - Subclasses
  878. // MARK: - DataRequest
  879. /// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`.
  880. public class DataRequest: Request {
  881. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  882. public let convertible: URLRequestConvertible
  883. /// `Data` read from the server so far.
  884. public var data: Data? { mutableData }
  885. /// Protected storage for the `Data` read by the instance.
  886. @Protected
  887. private var mutableData: Data? = nil
  888. /// Creates a `DataRequest` using the provided parameters.
  889. ///
  890. /// - Parameters:
  891. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  892. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  893. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  894. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  895. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  896. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  897. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  898. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  899. init(id: UUID = UUID(),
  900. convertible: URLRequestConvertible,
  901. underlyingQueue: DispatchQueue,
  902. serializationQueue: DispatchQueue,
  903. eventMonitor: EventMonitor?,
  904. interceptor: RequestInterceptor?,
  905. delegate: RequestDelegate) {
  906. self.convertible = convertible
  907. super.init(id: id,
  908. underlyingQueue: underlyingQueue,
  909. serializationQueue: serializationQueue,
  910. eventMonitor: eventMonitor,
  911. interceptor: interceptor,
  912. delegate: delegate)
  913. }
  914. override func reset() {
  915. super.reset()
  916. mutableData = nil
  917. }
  918. /// Called when `Data` is received by this instance.
  919. ///
  920. /// - Note: Also calls `updateDownloadProgress`.
  921. ///
  922. /// - Parameter data: The `Data` received.
  923. func didReceive(data: Data) {
  924. if self.data == nil {
  925. mutableData = data
  926. } else {
  927. $mutableData.write { $0?.append(data) }
  928. }
  929. updateDownloadProgress()
  930. }
  931. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  932. let copiedRequest = request
  933. return session.dataTask(with: copiedRequest)
  934. }
  935. /// Called to update the `downloadProgress` of the instance.
  936. func updateDownloadProgress() {
  937. let totalBytesReceived = Int64(data?.count ?? 0)
  938. let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  939. downloadProgress.totalUnitCount = totalBytesExpected
  940. downloadProgress.completedUnitCount = totalBytesReceived
  941. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  942. }
  943. /// Validates the request, using the specified closure.
  944. ///
  945. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  946. ///
  947. /// - Parameter validation: `Validation` closure used to validate the response.
  948. ///
  949. /// - Returns: The instance.
  950. @discardableResult
  951. public func validate(_ validation: @escaping Validation) -> Self {
  952. let validator: () -> Void = { [unowned self] in
  953. guard self.error == nil, let response = self.response else { return }
  954. let result = validation(self.request, response, self.data)
  955. if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) }
  956. self.eventMonitor?.request(self,
  957. didValidateRequest: self.request,
  958. response: response,
  959. data: self.data,
  960. withResult: result)
  961. }
  962. $validators.write { $0.append(validator) }
  963. return self
  964. }
  965. }
  966. // MARK: - DataStreamRequest
  967. /// `Request` subclass which streams HTTP response `Data` through a `Handler` closure.
  968. public final class DataStreamRequest: Request {
  969. /// Closure type handling `DataStreamRequest.Stream` values.
  970. public typealias Handler<Success, Failure: Error> = (Stream<Success, Failure>) throws -> Void
  971. /// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used
  972. /// to stop the stream at any time.
  973. public struct Stream<Success, Failure: Error> {
  974. /// Latest `Event` from the stream.
  975. public let event: Event<Success, Failure>
  976. /// Token used to cancel the stream.
  977. public let token: CancellationToken
  978. /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
  979. public func cancel() {
  980. token.cancel()
  981. }
  982. }
  983. /// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed
  984. /// `Data` or the completion of the stream.
  985. public enum Event<Success, Failure: Error> {
  986. /// Output produced every time the instance receives additional `Data`. The associated value contains the
  987. /// `Result` of processing the incoming `Data`.
  988. case stream(Result<Success, Failure>)
  989. /// Output produced when the instance has completed, whether due to stream end, cancellation, or an error.
  990. /// Associated `Completion` value contains the final state.
  991. case complete(Completion)
  992. }
  993. /// Value containing the state of a `DataStreamRequest` when the stream was completed.
  994. public struct Completion {
  995. /// Last `URLRequest` issued by the instance.
  996. public let request: URLRequest?
  997. /// Last `HTTPURLResponse` received by the instance.
  998. public let response: HTTPURLResponse?
  999. /// Last `URLSessionTaskMetrics` produced for the instance.
  1000. public let metrics: URLSessionTaskMetrics?
  1001. /// `AFError` produced for the instance, if any.
  1002. public let error: AFError?
  1003. }
  1004. /// Type used to cancel an ongoing stream.
  1005. public struct CancellationToken {
  1006. weak var request: DataStreamRequest?
  1007. init(_ request: DataStreamRequest) {
  1008. self.request = request
  1009. }
  1010. /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
  1011. public func cancel() {
  1012. request?.cancel()
  1013. }
  1014. }
  1015. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  1016. public let convertible: URLRequestConvertible
  1017. /// Whether or not the instance will be cancelled if stream parsing encounters an error.
  1018. public let automaticallyCancelOnStreamError: Bool
  1019. /// Internal mutable state specific to this type.
  1020. struct StreamMutableState {
  1021. /// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called.
  1022. var outputStream: OutputStream?
  1023. /// Stream closures called as `Data` is received.
  1024. var streams: [(_ data: Data) -> Void] = []
  1025. /// Number of currently executing streams. Used to ensure completions are only fired after all streams are
  1026. /// enqueued.
  1027. var numberOfExecutingStreams = 0
  1028. /// Completion calls enqueued while streams are still executing.
  1029. var enqueuedCompletionEvents: [() -> Void] = []
  1030. }
  1031. @Protected
  1032. var streamMutableState = StreamMutableState()
  1033. /// Creates a `DataStreamRequest` using the provided parameters.
  1034. ///
  1035. /// - Parameters:
  1036. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()`
  1037. /// by default.
  1038. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this
  1039. /// instance.
  1040. /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error`
  1041. /// is thrown while serializing stream `Data`.
  1042. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1043. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default
  1044. /// targets
  1045. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1046. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1047. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1048. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by
  1049. /// the `Request`.
  1050. init(id: UUID = UUID(),
  1051. convertible: URLRequestConvertible,
  1052. automaticallyCancelOnStreamError: Bool,
  1053. underlyingQueue: DispatchQueue,
  1054. serializationQueue: DispatchQueue,
  1055. eventMonitor: EventMonitor?,
  1056. interceptor: RequestInterceptor?,
  1057. delegate: RequestDelegate) {
  1058. self.convertible = convertible
  1059. self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError
  1060. super.init(id: id,
  1061. underlyingQueue: underlyingQueue,
  1062. serializationQueue: serializationQueue,
  1063. eventMonitor: eventMonitor,
  1064. interceptor: interceptor,
  1065. delegate: delegate)
  1066. }
  1067. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1068. let copiedRequest = request
  1069. return session.dataTask(with: copiedRequest)
  1070. }
  1071. override func finish(error: AFError? = nil) {
  1072. $streamMutableState.write { state in
  1073. state.outputStream?.close()
  1074. }
  1075. super.finish(error: error)
  1076. }
  1077. func didReceive(data: Data) {
  1078. $streamMutableState.write { state in
  1079. #if !(os(Linux) || os(Windows))
  1080. if let stream = state.outputStream {
  1081. underlyingQueue.async {
  1082. var bytes = Array(data)
  1083. stream.write(&bytes, maxLength: bytes.count)
  1084. }
  1085. }
  1086. #endif
  1087. state.numberOfExecutingStreams += state.streams.count
  1088. let localState = state
  1089. underlyingQueue.async { localState.streams.forEach { $0(data) } }
  1090. }
  1091. }
  1092. /// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure.
  1093. ///
  1094. /// - Parameter validation: `Validation` closure used to validate the request and response.
  1095. ///
  1096. /// - Returns: The `DataStreamRequest`.
  1097. @discardableResult
  1098. public func validate(_ validation: @escaping Validation) -> Self {
  1099. let validator: () -> Void = { [unowned self] in
  1100. guard self.error == nil, let response = self.response else { return }
  1101. let result = validation(self.request, response)
  1102. if case let .failure(error) = result {
  1103. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  1104. }
  1105. self.eventMonitor?.request(self,
  1106. didValidateRequest: self.request,
  1107. response: response,
  1108. withResult: result)
  1109. }
  1110. $validators.write { $0.append(validator) }
  1111. return self
  1112. }
  1113. #if !(os(Linux) || os(Windows))
  1114. /// Produces an `InputStream` that receives the `Data` received by the instance.
  1115. ///
  1116. /// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`.
  1117. /// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or
  1118. /// not the creating session has `startRequestsImmediately` set to `true`.
  1119. ///
  1120. /// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`.
  1121. ///
  1122. /// - Returns: The `InputStream` bound to the internal `OutboundStream`.
  1123. public func asInputStream(bufferSize: Int = 1024) -> InputStream? {
  1124. defer { resume() }
  1125. var inputStream: InputStream?
  1126. $streamMutableState.write { state in
  1127. Foundation.Stream.getBoundStreams(withBufferSize: bufferSize,
  1128. inputStream: &inputStream,
  1129. outputStream: &state.outputStream)
  1130. state.outputStream?.open()
  1131. }
  1132. return inputStream
  1133. }
  1134. #endif
  1135. func capturingError(from closure: () throws -> Void) {
  1136. do {
  1137. try closure()
  1138. } catch {
  1139. self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
  1140. cancel()
  1141. }
  1142. }
  1143. func appendStreamCompletion<Success, Failure>(on queue: DispatchQueue,
  1144. stream: @escaping Handler<Success, Failure>) {
  1145. appendResponseSerializer {
  1146. self.underlyingQueue.async {
  1147. self.responseSerializerDidComplete {
  1148. self.$streamMutableState.write { state in
  1149. guard state.numberOfExecutingStreams == 0 else {
  1150. state.enqueuedCompletionEvents.append {
  1151. self.enqueueCompletion(on: queue, stream: stream)
  1152. }
  1153. return
  1154. }
  1155. self.enqueueCompletion(on: queue, stream: stream)
  1156. }
  1157. }
  1158. }
  1159. }
  1160. }
  1161. func enqueueCompletion<Success, Failure>(on queue: DispatchQueue,
  1162. stream: @escaping Handler<Success, Failure>) {
  1163. queue.async {
  1164. do {
  1165. let completion = Completion(request: self.request,
  1166. response: self.response,
  1167. metrics: self.metrics,
  1168. error: self.error)
  1169. try stream(.init(event: .complete(completion), token: .init(self)))
  1170. } catch {
  1171. // Ignore error, as errors on Completion can't be handled anyway.
  1172. }
  1173. }
  1174. }
  1175. }
  1176. extension DataStreamRequest.Stream {
  1177. /// Incoming `Result` values from `Event.stream`.
  1178. public var result: Result<Success, Failure>? {
  1179. guard case let .stream(result) = event else { return nil }
  1180. return result
  1181. }
  1182. /// `Success` value of the instance, if any.
  1183. public var value: Success? {
  1184. guard case let .success(value) = result else { return nil }
  1185. return value
  1186. }
  1187. /// `Failure` value of the instance, if any.
  1188. public var error: Failure? {
  1189. guard case let .failure(error) = result else { return nil }
  1190. return error
  1191. }
  1192. /// `Completion` value of the instance, if any.
  1193. public var completion: DataStreamRequest.Completion? {
  1194. guard case let .complete(completion) = event else { return nil }
  1195. return completion
  1196. }
  1197. }
  1198. // MARK: - DownloadRequest
  1199. /// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`.
  1200. public class DownloadRequest: Request {
  1201. /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination
  1202. /// `URL`.
  1203. public struct Options: OptionSet {
  1204. /// Specifies that intermediate directories for the destination URL should be created.
  1205. public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
  1206. /// Specifies that any previous file at the destination `URL` should be removed.
  1207. public static let removePreviousFile = Options(rawValue: 1 << 1)
  1208. public let rawValue: Int
  1209. public init(rawValue: Int) {
  1210. self.rawValue = rawValue
  1211. }
  1212. }
  1213. // MARK: Destination
  1214. /// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the
  1215. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  1216. /// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and
  1217. /// the options defining how the file should be moved.
  1218. ///
  1219. /// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not
  1220. /// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory.
  1221. public typealias Destination = (_ temporaryURL: URL,
  1222. _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
  1223. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  1224. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  1225. ///
  1226. /// - Parameters:
  1227. /// - directory: The search path directory. `.documentDirectory` by default.
  1228. /// - domain: The search path domain mask. `.userDomainMask` by default.
  1229. /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by
  1230. /// default.
  1231. /// - Returns: The `Destination` closure.
  1232. public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
  1233. in domain: FileManager.SearchPathDomainMask = .userDomainMask,
  1234. options: Options = []) -> Destination {
  1235. { temporaryURL, response in
  1236. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  1237. let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
  1238. return (url, options)
  1239. }
  1240. }
  1241. /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends
  1242. /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files
  1243. /// with this destination must be additionally moved if they should survive the system reclamation of temporary
  1244. /// space.
  1245. static let defaultDestination: Destination = { url, _ in
  1246. (defaultDestinationURL(url), [])
  1247. }
  1248. /// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the
  1249. /// provided file name.
  1250. static let defaultDestinationURL: (URL) -> URL = { url in
  1251. let filename = "Alamofire_\(url.lastPathComponent)"
  1252. let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
  1253. return destination
  1254. }
  1255. // MARK: Downloadable
  1256. /// Type describing the source used to create the underlying `URLSessionDownloadTask`.
  1257. public enum Downloadable {
  1258. /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value.
  1259. case request(URLRequestConvertible)
  1260. /// Download should be started from the associated resume `Data` value.
  1261. case resumeData(Data)
  1262. }
  1263. // MARK: Mutable State
  1264. /// Type containing all mutable state for `DownloadRequest` instances.
  1265. private struct DownloadRequestMutableState {
  1266. /// Possible resume `Data` produced when cancelling the instance.
  1267. var resumeData: Data?
  1268. /// `URL` to which `Data` is being downloaded.
  1269. var fileURL: URL?
  1270. }
  1271. /// Protected mutable state specific to `DownloadRequest`.
  1272. @Protected
  1273. private var mutableDownloadState = DownloadRequestMutableState()
  1274. /// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download
  1275. /// using the `download(resumingWith data:)` API.
  1276. ///
  1277. /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel).
  1278. public var resumeData: Data? {
  1279. #if !(os(Linux) || os(Windows))
  1280. return $mutableDownloadState.resumeData ?? error?.downloadResumeData
  1281. #else
  1282. return $mutableDownloadState.resumeData
  1283. #endif
  1284. }
  1285. /// If the download is successful, the `URL` where the file was downloaded.
  1286. public var fileURL: URL? { $mutableDownloadState.fileURL }
  1287. // MARK: Initial State
  1288. /// `Downloadable` value used for this instance.
  1289. public let downloadable: Downloadable
  1290. /// The `Destination` to which the downloaded file is moved.
  1291. let destination: Destination
  1292. /// Creates a `DownloadRequest` using the provided parameters.
  1293. ///
  1294. /// - Parameters:
  1295. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  1296. /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance.
  1297. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1298. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  1299. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1300. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1301. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1302. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`
  1303. /// - destination: `Destination` closure used to move the downloaded file to its final location.
  1304. init(id: UUID = UUID(),
  1305. downloadable: Downloadable,
  1306. underlyingQueue: DispatchQueue,
  1307. serializationQueue: DispatchQueue,
  1308. eventMonitor: EventMonitor?,
  1309. interceptor: RequestInterceptor?,
  1310. delegate: RequestDelegate,
  1311. destination: @escaping Destination) {
  1312. self.downloadable = downloadable
  1313. self.destination = destination
  1314. super.init(id: id,
  1315. underlyingQueue: underlyingQueue,
  1316. serializationQueue: serializationQueue,
  1317. eventMonitor: eventMonitor,
  1318. interceptor: interceptor,
  1319. delegate: delegate)
  1320. }
  1321. override func reset() {
  1322. super.reset()
  1323. $mutableDownloadState.write {
  1324. $0.resumeData = nil
  1325. $0.fileURL = nil
  1326. }
  1327. }
  1328. /// Called when a download has finished.
  1329. ///
  1330. /// - Parameters:
  1331. /// - task: `URLSessionTask` that finished the download.
  1332. /// - result: `Result` of the automatic move to `destination`.
  1333. func didFinishDownloading(using task: URLSessionTask, with result: Result<URL, AFError>) {
  1334. eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
  1335. switch result {
  1336. case let .success(url): $mutableDownloadState.fileURL = url
  1337. case let .failure(error): self.error = error
  1338. }
  1339. }
  1340. /// Updates the `downloadProgress` using the provided values.
  1341. ///
  1342. /// - Parameters:
  1343. /// - bytesWritten: Total bytes written so far.
  1344. /// - totalBytesExpectedToWrite: Total bytes expected to write.
  1345. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  1346. downloadProgress.totalUnitCount = totalBytesExpectedToWrite
  1347. downloadProgress.completedUnitCount += bytesWritten
  1348. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  1349. }
  1350. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1351. session.downloadTask(with: request)
  1352. }
  1353. /// Creates a `URLSessionTask` from the provided resume data.
  1354. ///
  1355. /// - Parameters:
  1356. /// - data: `Data` used to resume the download.
  1357. /// - session: `URLSession` used to create the `URLSessionTask`.
  1358. ///
  1359. /// - Returns: The `URLSessionTask` created.
  1360. public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
  1361. session.downloadTask(withResumeData: data)
  1362. }
  1363. /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended.
  1364. ///
  1365. /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use
  1366. /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`.
  1367. ///
  1368. /// - Returns: The instance.
  1369. @discardableResult
  1370. override public func cancel() -> Self {
  1371. cancel(producingResumeData: false)
  1372. }
  1373. /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be
  1374. /// resumed or suspended.
  1375. ///
  1376. /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if
  1377. /// available.
  1378. ///
  1379. /// - Returns: The instance.
  1380. @discardableResult
  1381. public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self {
  1382. cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil)
  1383. }
  1384. /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed
  1385. /// or suspended.
  1386. ///
  1387. /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData`
  1388. /// property.
  1389. ///
  1390. /// - Parameter completionHandler: The completion handler that is called when the download has been successfully
  1391. /// cancelled. It is not guaranteed to be called on a particular queue, so you may
  1392. /// want use an appropriate queue to perform your work.
  1393. ///
  1394. /// - Returns: The instance.
  1395. @discardableResult
  1396. public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self {
  1397. cancel(optionallyProducingResumeData: completionHandler)
  1398. }
  1399. /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed,
  1400. /// cancellation is performed without producing resume data.
  1401. ///
  1402. /// - Parameter completionHandler: Optional resume data handler.
  1403. ///
  1404. /// - Returns: The instance.
  1405. private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self {
  1406. $mutableState.write { mutableState in
  1407. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  1408. mutableState.state = .cancelled
  1409. underlyingQueue.async { self.didCancel() }
  1410. guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
  1411. underlyingQueue.async { self.finish() }
  1412. return
  1413. }
  1414. if let completionHandler = completionHandler {
  1415. // Resume to ensure metrics are gathered.
  1416. task.resume()
  1417. task.cancel { resumeData in
  1418. self.$mutableDownloadState.resumeData = resumeData
  1419. self.underlyingQueue.async { self.didCancelTask(task) }
  1420. completionHandler(resumeData)
  1421. }
  1422. } else {
  1423. // Resume to ensure metrics are gathered.
  1424. task.resume()
  1425. task.cancel()
  1426. self.underlyingQueue.async { self.didCancelTask(task) }
  1427. }
  1428. }
  1429. return self
  1430. }
  1431. /// Validates the request, using the specified closure.
  1432. ///
  1433. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  1434. ///
  1435. /// - Parameter validation: `Validation` closure to validate the response.
  1436. ///
  1437. /// - Returns: The instance.
  1438. @discardableResult
  1439. public func validate(_ validation: @escaping Validation) -> Self {
  1440. let validator: () -> Void = { [unowned self] in
  1441. guard self.error == nil, let response = self.response else { return }
  1442. let result = validation(self.request, response, self.fileURL)
  1443. if case let .failure(error) = result {
  1444. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  1445. }
  1446. self.eventMonitor?.request(self,
  1447. didValidateRequest: self.request,
  1448. response: response,
  1449. fileURL: self.fileURL,
  1450. withResult: result)
  1451. }
  1452. $validators.write { $0.append(validator) }
  1453. return self
  1454. }
  1455. }
  1456. // MARK: - UploadRequest
  1457. /// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`.
  1458. public class UploadRequest: DataRequest {
  1459. /// Type describing the origin of the upload, whether `Data`, file, or stream.
  1460. public enum Uploadable {
  1461. /// Upload from the provided `Data` value.
  1462. case data(Data)
  1463. /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be
  1464. /// automatically removed once uploaded.
  1465. case file(URL, shouldRemove: Bool)
  1466. /// Upload from the provided `InputStream`.
  1467. case stream(InputStream)
  1468. }
  1469. // MARK: Initial State
  1470. /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance.
  1471. public let upload: UploadableConvertible
  1472. /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written
  1473. /// to disk.
  1474. public let fileManager: FileManager
  1475. // MARK: Mutable State
  1476. /// `Uploadable` value used by the instance.
  1477. public var uploadable: Uploadable?
  1478. /// Creates an `UploadRequest` using the provided parameters.
  1479. ///
  1480. /// - Parameters:
  1481. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  1482. /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed.
  1483. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1484. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  1485. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1486. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1487. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1488. /// - fileManager: `FileManager` used to perform cleanup tasks, including the removal of multipart form
  1489. /// encoded payloads written to disk.
  1490. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  1491. init(id: UUID = UUID(),
  1492. convertible: UploadConvertible,
  1493. underlyingQueue: DispatchQueue,
  1494. serializationQueue: DispatchQueue,
  1495. eventMonitor: EventMonitor?,
  1496. interceptor: RequestInterceptor?,
  1497. fileManager: FileManager,
  1498. delegate: RequestDelegate) {
  1499. upload = convertible
  1500. self.fileManager = fileManager
  1501. super.init(id: id,
  1502. convertible: convertible,
  1503. underlyingQueue: underlyingQueue,
  1504. serializationQueue: serializationQueue,
  1505. eventMonitor: eventMonitor,
  1506. interceptor: interceptor,
  1507. delegate: delegate)
  1508. }
  1509. /// Called when the `Uploadable` value has been created from the `UploadConvertible`.
  1510. ///
  1511. /// - Parameter uploadable: The `Uploadable` that was created.
  1512. func didCreateUploadable(_ uploadable: Uploadable) {
  1513. self.uploadable = uploadable
  1514. eventMonitor?.request(self, didCreateUploadable: uploadable)
  1515. }
  1516. /// Called when the `Uploadable` value could not be created.
  1517. ///
  1518. /// - Parameter error: `AFError` produced by the failure.
  1519. func didFailToCreateUploadable(with error: AFError) {
  1520. self.error = error
  1521. eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
  1522. retryOrFinish(error: error)
  1523. }
  1524. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1525. guard let uploadable = uploadable else {
  1526. fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
  1527. }
  1528. switch uploadable {
  1529. case let .data(data): return session.uploadTask(with: request, from: data)
  1530. case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
  1531. case .stream: return session.uploadTask(withStreamedRequest: request)
  1532. }
  1533. }
  1534. override func reset() {
  1535. // Uploadable must be recreated on every retry.
  1536. uploadable = nil
  1537. super.reset()
  1538. }
  1539. /// Produces the `InputStream` from `uploadable`, if it can.
  1540. ///
  1541. /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash.
  1542. ///
  1543. /// - Returns: The `InputStream`.
  1544. func inputStream() -> InputStream {
  1545. guard let uploadable = uploadable else {
  1546. fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
  1547. }
  1548. guard case let .stream(stream) = uploadable else {
  1549. fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
  1550. }
  1551. eventMonitor?.request(self, didProvideInputStream: stream)
  1552. return stream
  1553. }
  1554. override public func cleanup() {
  1555. defer { super.cleanup() }
  1556. guard
  1557. let uploadable = uploadable,
  1558. case let .file(url, shouldRemove) = uploadable,
  1559. shouldRemove
  1560. else { return }
  1561. try? fileManager.removeItem(at: url)
  1562. }
  1563. }
  1564. /// A type that can produce an `UploadRequest.Uploadable` value.
  1565. public protocol UploadableConvertible {
  1566. /// Produces an `UploadRequest.Uploadable` value from the instance.
  1567. ///
  1568. /// - Returns: The `UploadRequest.Uploadable`.
  1569. /// - Throws: Any `Error` produced during creation.
  1570. func createUploadable() throws -> UploadRequest.Uploadable
  1571. }
  1572. extension UploadRequest.Uploadable: UploadableConvertible {
  1573. public func createUploadable() throws -> UploadRequest.Uploadable {
  1574. self
  1575. }
  1576. }
  1577. /// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`.
  1578. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {}