Request.swift 72 KB

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