Request.swift 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604
  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. fileprivate let mutableState = Protected(MutableState())
  121. /// `State` of the `Request`.
  122. public var state: State { mutableState.state }
  123. /// Returns whether `state` is `.initialized`.
  124. public var isInitialized: Bool { state == .initialized }
  125. /// Returns whether `state is `.resumed`.
  126. public var isResumed: Bool { state == .resumed }
  127. /// Returns whether `state` is `.suspended`.
  128. public var isSuspended: Bool { state == .suspended }
  129. /// Returns whether `state` is `.cancelled`.
  130. public var isCancelled: Bool { state == .cancelled }
  131. /// Returns whether `state` is `.finished`.
  132. public var isFinished: Bool { state == .finished }
  133. // MARK: Progress
  134. /// Closure type executed when monitoring the upload or download progress of a request.
  135. public typealias ProgressHandler = (Progress) -> Void
  136. /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried.
  137. public let uploadProgress = Progress(totalUnitCount: 0)
  138. /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried.
  139. public let downloadProgress = Progress(totalUnitCount: 0)
  140. /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`.
  141. private var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
  142. get { mutableState.uploadProgressHandler }
  143. set { mutableState.uploadProgressHandler = newValue }
  144. }
  145. /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`.
  146. fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
  147. get { mutableState.downloadProgressHandler }
  148. set { mutableState.downloadProgressHandler = newValue }
  149. }
  150. // MARK: Redirect Handling
  151. /// `RedirectHandler` set on the instance.
  152. public private(set) var redirectHandler: RedirectHandler? {
  153. get { mutableState.redirectHandler }
  154. set { mutableState.redirectHandler = newValue }
  155. }
  156. // MARK: Cached Response Handling
  157. /// `CachedResponseHandler` set on the instance.
  158. public private(set) var cachedResponseHandler: CachedResponseHandler? {
  159. get { mutableState.cachedResponseHandler }
  160. set { mutableState.cachedResponseHandler = newValue }
  161. }
  162. // MARK: URLCredential
  163. /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods.
  164. public private(set) var credential: URLCredential? {
  165. get { mutableState.credential }
  166. set { mutableState.credential = newValue }
  167. }
  168. // MARK: Validators
  169. /// `Validator` callback closures that store the validation calls enqueued.
  170. fileprivate let validators = Protected<[() -> Void]>([])
  171. // MARK: URLRequests
  172. /// All `URLRequests` created on behalf of the `Request`, including original and adapted requests.
  173. public var requests: [URLRequest] { mutableState.requests }
  174. /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed.
  175. public var firstRequest: URLRequest? { requests.first }
  176. /// Last `URLRequest` created on behalf of the `Request`.
  177. public var lastRequest: URLRequest? { requests.last }
  178. /// Current `URLRequest` created on behalf of the `Request`.
  179. public var request: URLRequest? { lastRequest }
  180. /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from
  181. /// `requests` due to `URLSession` manipulation.
  182. public var performedRequests: [URLRequest] { mutableState.read { $0.tasks.compactMap(\.currentRequest) } }
  183. // MARK: HTTPURLResponse
  184. /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the
  185. /// last `URLSessionTask`.
  186. public var response: HTTPURLResponse? { lastTask?.response as? HTTPURLResponse }
  187. // MARK: Tasks
  188. /// All `URLSessionTask`s created on behalf of the `Request`.
  189. public var tasks: [URLSessionTask] { mutableState.tasks }
  190. /// First `URLSessionTask` created on behalf of the `Request`.
  191. public var firstTask: URLSessionTask? { tasks.first }
  192. /// Last `URLSessionTask` created on behalf of the `Request`.
  193. public var lastTask: URLSessionTask? { tasks.last }
  194. /// Current `URLSessionTask` created on behalf of the `Request`.
  195. public var task: URLSessionTask? { lastTask }
  196. // MARK: Metrics
  197. /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created.
  198. public var allMetrics: [URLSessionTaskMetrics] { mutableState.metrics }
  199. /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  200. public var firstMetrics: URLSessionTaskMetrics? { allMetrics.first }
  201. /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  202. public var lastMetrics: URLSessionTaskMetrics? { allMetrics.last }
  203. /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  204. public var metrics: URLSessionTaskMetrics? { lastMetrics }
  205. // MARK: Retry Count
  206. /// Number of times the `Request` has been retried.
  207. public var retryCount: Int { mutableState.retryCount }
  208. // MARK: Error
  209. /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed.
  210. public fileprivate(set) var error: AFError? {
  211. get { mutableState.error }
  212. set { mutableState.error = newValue }
  213. }
  214. /// Default initializer for the `Request` superclass.
  215. ///
  216. /// - Parameters:
  217. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  218. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  219. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  220. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  221. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  222. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  223. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  224. init(id: UUID = UUID(),
  225. underlyingQueue: DispatchQueue,
  226. serializationQueue: DispatchQueue,
  227. eventMonitor: EventMonitor?,
  228. interceptor: RequestInterceptor?,
  229. delegate: RequestDelegate) {
  230. self.id = id
  231. self.underlyingQueue = underlyingQueue
  232. self.serializationQueue = serializationQueue
  233. self.eventMonitor = eventMonitor
  234. self.interceptor = interceptor
  235. self.delegate = delegate
  236. }
  237. // MARK: - Internal Event API
  238. // All API must be called from underlyingQueue.
  239. /// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active,
  240. /// the `URLRequest` will be adapted before being issued.
  241. ///
  242. /// - Parameter request: The `URLRequest` created.
  243. func didCreateInitialURLRequest(_ request: URLRequest) {
  244. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  245. mutableState.write { $0.requests.append(request) }
  246. eventMonitor?.request(self, didCreateInitialURLRequest: request)
  247. }
  248. /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`.
  249. ///
  250. /// - Note: Triggers retry.
  251. ///
  252. /// - Parameter error: `AFError` thrown from the failed creation.
  253. func didFailToCreateURLRequest(with error: AFError) {
  254. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  255. self.error = error
  256. eventMonitor?.request(self, didFailToCreateURLRequestWithError: error)
  257. callCURLHandlerIfNecessary()
  258. retryOrFinish(error: error)
  259. }
  260. /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`.
  261. ///
  262. /// - Parameters:
  263. /// - initialRequest: The `URLRequest` that was adapted.
  264. /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`.
  265. func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) {
  266. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  267. mutableState.write { $0.requests.append(adaptedRequest) }
  268. eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest)
  269. }
  270. /// Called when a `RequestAdapter` fails to adapt a `URLRequest`.
  271. ///
  272. /// - Note: Triggers retry.
  273. ///
  274. /// - Parameters:
  275. /// - request: The `URLRequest` the adapter was called with.
  276. /// - error: The `AFError` returned by the `RequestAdapter`.
  277. func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) {
  278. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  279. self.error = error
  280. eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error)
  281. callCURLHandlerIfNecessary()
  282. retryOrFinish(error: error)
  283. }
  284. /// Final `URLRequest` has been created for the instance.
  285. ///
  286. /// - Parameter request: The `URLRequest` created.
  287. func didCreateURLRequest(_ request: URLRequest) {
  288. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  289. mutableState.read { state in
  290. state.urlRequestHandler?.queue.async { state.urlRequestHandler?.handler(request) }
  291. }
  292. eventMonitor?.request(self, didCreateURLRequest: request)
  293. callCURLHandlerIfNecessary()
  294. }
  295. /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`.
  296. private func callCURLHandlerIfNecessary() {
  297. mutableState.write { mutableState in
  298. guard let cURLHandler = mutableState.cURLHandler else { return }
  299. cURLHandler.queue.async { cURLHandler.handler(self.cURLDescription()) }
  300. mutableState.cURLHandler = nil
  301. }
  302. }
  303. /// Called when a `URLSessionTask` is created on behalf of the instance.
  304. ///
  305. /// - Parameter task: The `URLSessionTask` created.
  306. func didCreateTask(_ task: URLSessionTask) {
  307. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  308. mutableState.write { state in
  309. state.tasks.append(task)
  310. guard let urlSessionTaskHandler = state.urlSessionTaskHandler else { return }
  311. urlSessionTaskHandler.queue.async { urlSessionTaskHandler.handler(task) }
  312. }
  313. eventMonitor?.request(self, didCreateTask: task)
  314. }
  315. /// Called when resumption is completed.
  316. func didResume() {
  317. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  318. eventMonitor?.requestDidResume(self)
  319. }
  320. /// Called when a `URLSessionTask` is resumed on behalf of the instance.
  321. ///
  322. /// - Parameter task: The `URLSessionTask` resumed.
  323. func didResumeTask(_ task: URLSessionTask) {
  324. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  325. eventMonitor?.request(self, didResumeTask: task)
  326. }
  327. /// Called when suspension is completed.
  328. func didSuspend() {
  329. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  330. eventMonitor?.requestDidSuspend(self)
  331. }
  332. /// Called when a `URLSessionTask` is suspended on behalf of the instance.
  333. ///
  334. /// - Parameter task: The `URLSessionTask` suspended.
  335. func didSuspendTask(_ task: URLSessionTask) {
  336. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  337. eventMonitor?.request(self, didSuspendTask: task)
  338. }
  339. /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`.
  340. func didCancel() {
  341. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  342. mutableState.write { mutableState in
  343. mutableState.error = mutableState.error ?? AFError.explicitlyCancelled
  344. }
  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. let validators = validators.read { $0 }
  385. validators.forEach { $0() }
  386. eventMonitor?.request(self, didCompleteTask: task, with: error)
  387. retryOrFinish(error: self.error)
  388. }
  389. /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`.
  390. func prepareForRetry() {
  391. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  392. mutableState.write { $0.retryCount += 1 }
  393. reset()
  394. eventMonitor?.requestIsRetrying(self)
  395. }
  396. /// Called to determine whether retry will be triggered for the particular error, or whether the instance should
  397. /// call `finish()`.
  398. ///
  399. /// - Parameter error: The possible `AFError` which may trigger retry.
  400. func retryOrFinish(error: AFError?) {
  401. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  402. guard !isCancelled, let error = error, let delegate = delegate else { finish(); return }
  403. delegate.retryResult(for: self, dueTo: error) { retryResult in
  404. switch retryResult {
  405. case .doNotRetry:
  406. self.finish()
  407. case let .doNotRetryWithError(retryError):
  408. self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
  409. case .retry, .retryWithDelay:
  410. delegate.retryRequest(self, withDelay: retryResult.delay)
  411. }
  412. }
  413. }
  414. /// Finishes this `Request` and starts the response serializers.
  415. ///
  416. /// - Parameter error: The possible `Error` with which the instance will finish.
  417. func finish(error: AFError? = nil) {
  418. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  419. guard !mutableState.isFinishing else { return }
  420. mutableState.isFinishing = true
  421. if let error = error { self.error = error }
  422. // Start response handlers
  423. processNextResponseSerializer()
  424. eventMonitor?.requestDidFinish(self)
  425. }
  426. /// Appends the response serialization closure to the instance.
  427. ///
  428. /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`.
  429. ///
  430. /// - Parameter closure: The closure containing the response serialization call.
  431. func appendResponseSerializer(_ closure: @escaping () -> Void) {
  432. mutableState.write { mutableState in
  433. mutableState.responseSerializers.append(closure)
  434. if mutableState.state == .finished {
  435. mutableState.state = .resumed
  436. }
  437. if mutableState.responseSerializerProcessingFinished {
  438. underlyingQueue.async { self.processNextResponseSerializer() }
  439. }
  440. if mutableState.state.canTransitionTo(.resumed) {
  441. underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } }
  442. }
  443. }
  444. }
  445. /// Returns the next response serializer closure to execute if there's one left.
  446. ///
  447. /// - Returns: The next response serialization closure, if there is one.
  448. func nextResponseSerializer() -> (() -> Void)? {
  449. var responseSerializer: (() -> Void)?
  450. mutableState.write { mutableState in
  451. let responseSerializerIndex = mutableState.responseSerializerCompletions.count
  452. if responseSerializerIndex < mutableState.responseSerializers.count {
  453. responseSerializer = mutableState.responseSerializers[responseSerializerIndex]
  454. }
  455. }
  456. return responseSerializer
  457. }
  458. /// Processes the next response serializer and calls all completions if response serialization is complete.
  459. func processNextResponseSerializer() {
  460. guard let responseSerializer = nextResponseSerializer() else {
  461. // Execute all response serializer completions and clear them
  462. var completions: [() -> Void] = []
  463. mutableState.write { mutableState in
  464. completions = mutableState.responseSerializerCompletions
  465. // Clear out all response serializers and response serializer completions in mutable state since the
  466. // request is complete. It's important to do this prior to calling the completion closures in case
  467. // the completions call back into the request triggering a re-processing of the response serializers.
  468. // An example of how this can happen is by calling cancel inside a response completion closure.
  469. mutableState.responseSerializers.removeAll()
  470. mutableState.responseSerializerCompletions.removeAll()
  471. if mutableState.state.canTransitionTo(.finished) {
  472. mutableState.state = .finished
  473. }
  474. mutableState.responseSerializerProcessingFinished = true
  475. mutableState.isFinishing = false
  476. }
  477. completions.forEach { $0() }
  478. // Cleanup the request
  479. cleanup()
  480. return
  481. }
  482. serializationQueue.async { responseSerializer() }
  483. }
  484. /// Notifies the `Request` that the response serializer is complete.
  485. ///
  486. /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers
  487. /// are complete.
  488. func responseSerializerDidComplete(completion: @escaping () -> Void) {
  489. mutableState.write { $0.responseSerializerCompletions.append(completion) }
  490. processNextResponseSerializer()
  491. }
  492. /// Resets all task and response serializer related state for retry.
  493. func reset() {
  494. error = nil
  495. uploadProgress.totalUnitCount = 0
  496. uploadProgress.completedUnitCount = 0
  497. downloadProgress.totalUnitCount = 0
  498. downloadProgress.completedUnitCount = 0
  499. mutableState.write { state in
  500. state.isFinishing = false
  501. state.responseSerializerCompletions = []
  502. }
  503. }
  504. /// Called when updating the upload progress.
  505. ///
  506. /// - Parameters:
  507. /// - totalBytesSent: Total bytes sent so far.
  508. /// - totalBytesExpectedToSend: Total bytes expected to send.
  509. func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  510. uploadProgress.totalUnitCount = totalBytesExpectedToSend
  511. uploadProgress.completedUnitCount = totalBytesSent
  512. uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
  513. }
  514. /// Perform a closure on the current `state` while locked.
  515. ///
  516. /// - Parameter perform: The closure to perform.
  517. func withState(perform: (State) -> Void) {
  518. mutableState.withState(perform: perform)
  519. }
  520. // MARK: Task Creation
  521. /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
  522. ///
  523. /// - Parameters:
  524. /// - request: `URLRequest` to use to create the `URLSessionTask`.
  525. /// - session: `URLSession` which creates the `URLSessionTask`.
  526. ///
  527. /// - Returns: The `URLSessionTask` created.
  528. func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  529. fatalError("Subclasses must override.")
  530. }
  531. // MARK: - Public API
  532. // These APIs are callable from any queue.
  533. // MARK: State
  534. /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended.
  535. ///
  536. /// - Returns: The instance.
  537. @discardableResult
  538. public func cancel() -> Self {
  539. mutableState.write { mutableState in
  540. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  541. mutableState.state = .cancelled
  542. underlyingQueue.async { self.didCancel() }
  543. guard let task = mutableState.tasks.last, task.state != .completed else {
  544. underlyingQueue.async { self.finish() }
  545. return
  546. }
  547. // Resume to ensure metrics are gathered.
  548. task.resume()
  549. task.cancel()
  550. underlyingQueue.async { self.didCancelTask(task) }
  551. }
  552. return self
  553. }
  554. /// Suspends the instance.
  555. ///
  556. /// - Returns: The instance.
  557. @discardableResult
  558. public func suspend() -> Self {
  559. mutableState.write { mutableState in
  560. guard mutableState.state.canTransitionTo(.suspended) else { return }
  561. mutableState.state = .suspended
  562. underlyingQueue.async { self.didSuspend() }
  563. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  564. task.suspend()
  565. underlyingQueue.async { self.didSuspendTask(task) }
  566. }
  567. return self
  568. }
  569. /// Resumes the instance.
  570. ///
  571. /// - Returns: The instance.
  572. @discardableResult
  573. public func resume() -> Self {
  574. mutableState.write { mutableState in
  575. guard mutableState.state.canTransitionTo(.resumed) else { return }
  576. mutableState.state = .resumed
  577. underlyingQueue.async { self.didResume() }
  578. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  579. task.resume()
  580. underlyingQueue.async { self.didResumeTask(task) }
  581. }
  582. return self
  583. }
  584. // MARK: - Closure API
  585. /// Associates a credential using the provided values with the instance.
  586. ///
  587. /// - Parameters:
  588. /// - username: The username.
  589. /// - password: The password.
  590. /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default.
  591. ///
  592. /// - Returns: The instance.
  593. @discardableResult
  594. public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
  595. let credential = URLCredential(user: username, password: password, persistence: persistence)
  596. return authenticate(with: credential)
  597. }
  598. /// Associates the provided credential with the instance.
  599. ///
  600. /// - Parameter credential: The `URLCredential`.
  601. ///
  602. /// - Returns: The instance.
  603. @discardableResult
  604. public func authenticate(with credential: URLCredential) -> Self {
  605. mutableState.credential = credential
  606. return self
  607. }
  608. /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from 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 read from the server.
  615. ///
  616. /// - Returns: The instance.
  617. @discardableResult
  618. public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  619. mutableState.downloadProgressHandler = (handler: closure, queue: queue)
  620. return self
  621. }
  622. /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.
  623. ///
  624. /// - Note: Only the last closure provided is used.
  625. ///
  626. /// - Parameters:
  627. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  628. /// - closure: The closure to be executed periodically as data is sent to the server.
  629. ///
  630. /// - Returns: The instance.
  631. @discardableResult
  632. public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  633. mutableState.uploadProgressHandler = (handler: closure, queue: queue)
  634. return self
  635. }
  636. // MARK: Redirects
  637. /// Sets the redirect handler for the instance which will be used if a redirect response is encountered.
  638. ///
  639. /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash.
  640. ///
  641. /// - Parameter handler: The `RedirectHandler`.
  642. ///
  643. /// - Returns: The instance.
  644. @discardableResult
  645. public func redirect(using handler: RedirectHandler) -> Self {
  646. mutableState.write { mutableState in
  647. precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.")
  648. mutableState.redirectHandler = handler
  649. }
  650. return self
  651. }
  652. // MARK: Cached Responses
  653. /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response.
  654. ///
  655. /// - Note: Attempting to set the cache handler more than once is a logic error and will crash.
  656. ///
  657. /// - Parameter handler: The `CachedResponseHandler`.
  658. ///
  659. /// - Returns: The instance.
  660. @discardableResult
  661. public func cacheResponse(using handler: CachedResponseHandler) -> Self {
  662. mutableState.write { mutableState in
  663. precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.")
  664. mutableState.cachedResponseHandler = handler
  665. }
  666. return self
  667. }
  668. // MARK: - Lifetime APIs
  669. /// Sets a handler to be called when the cURL description of the request is available.
  670. ///
  671. /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
  672. ///
  673. /// - Parameters:
  674. /// - queue: `DispatchQueue` on which `handler` will be called.
  675. /// - handler: Closure to be called when the cURL description is available.
  676. ///
  677. /// - Returns: The instance.
  678. @discardableResult
  679. public func cURLDescription(on queue: DispatchQueue, calling handler: @escaping (String) -> Void) -> Self {
  680. mutableState.write { mutableState in
  681. if mutableState.requests.last != nil {
  682. queue.async { handler(self.cURLDescription()) }
  683. } else {
  684. mutableState.cURLHandler = (queue, handler)
  685. }
  686. }
  687. return self
  688. }
  689. /// Sets a handler to be called when the cURL description of the request is available.
  690. ///
  691. /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
  692. ///
  693. /// - Parameter handler: Closure to be called when the cURL description is available. Called on the instance's
  694. /// `underlyingQueue` by default.
  695. ///
  696. /// - Returns: The instance.
  697. @discardableResult
  698. public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self {
  699. cURLDescription(on: underlyingQueue, calling: handler)
  700. return self
  701. }
  702. /// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance.
  703. ///
  704. /// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried.
  705. ///
  706. /// - Parameters:
  707. /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
  708. /// - handler: Closure to be called when a `URLRequest` is available.
  709. ///
  710. /// - Returns: The instance.
  711. @discardableResult
  712. public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLRequest) -> Void) -> Self {
  713. mutableState.write { state in
  714. if let request = state.requests.last {
  715. queue.async { handler(request) }
  716. }
  717. state.urlRequestHandler = (queue, handler)
  718. }
  719. return self
  720. }
  721. /// Sets a closure to be called whenever the instance creates a `URLSessionTask`.
  722. ///
  723. /// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It
  724. /// **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features.
  725. /// Additionally, this closure may be called multiple times if the instance is retried.
  726. ///
  727. /// - Parameters:
  728. /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
  729. /// - handler: Closure to be called when the `URLSessionTask` is available.
  730. ///
  731. /// - Returns: The instance.
  732. @discardableResult
  733. public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLSessionTask) -> Void) -> Self {
  734. mutableState.write { state in
  735. if let task = state.tasks.last {
  736. queue.async { handler(task) }
  737. }
  738. state.urlSessionTaskHandler = (queue, handler)
  739. }
  740. return self
  741. }
  742. // MARK: Cleanup
  743. /// Adds a `finishHandler` closure to be called when the request completes.
  744. ///
  745. /// - Parameter closure: Closure to be called when the request finishes.
  746. func onFinish(perform finishHandler: @escaping () -> Void) {
  747. guard !isFinished else { finishHandler(); return }
  748. mutableState.write { state in
  749. state.finishHandlers.append(finishHandler)
  750. }
  751. }
  752. /// Final cleanup step executed when the instance finishes response serialization.
  753. func cleanup() {
  754. let handlers = mutableState.finishHandlers
  755. handlers.forEach { $0() }
  756. mutableState.write { state in
  757. state.finishHandlers.removeAll()
  758. }
  759. delegate?.cleanup(after: self)
  760. }
  761. }
  762. extension Request {
  763. /// Type indicating how a `DataRequest` or `DataStreamRequest` should proceed after receiving an `HTTPURLResponse`.
  764. public enum ResponseDisposition {
  765. /// Allow the request to continue normally.
  766. case allow
  767. /// Cancel the request, similar to calling `cancel()`.
  768. case cancel
  769. var sessionDisposition: URLSession.ResponseDisposition {
  770. switch self {
  771. case .allow: return .allow
  772. case .cancel: return .cancel
  773. }
  774. }
  775. }
  776. }
  777. // MARK: - Protocol Conformances
  778. extension Request: Equatable {
  779. public static func ==(lhs: Request, rhs: Request) -> Bool {
  780. lhs.id == rhs.id
  781. }
  782. }
  783. extension Request: Hashable {
  784. public func hash(into hasher: inout Hasher) {
  785. hasher.combine(id)
  786. }
  787. }
  788. extension Request: CustomStringConvertible {
  789. /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
  790. /// created, as well as the response status code, if a response has been received.
  791. public var description: String {
  792. guard let request = performedRequests.last ?? lastRequest,
  793. let url = request.url,
  794. let method = request.httpMethod else { return "No request created yet." }
  795. let requestDescription = "\(method) \(url.absoluteString)"
  796. return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
  797. }
  798. }
  799. extension Request {
  800. /// cURL representation of the instance.
  801. ///
  802. /// - Returns: The cURL equivalent of the instance.
  803. public func cURLDescription() -> String {
  804. guard
  805. let request = lastRequest,
  806. let url = request.url,
  807. let host = url.host,
  808. let method = request.httpMethod else { return "$ curl command could not be created" }
  809. var components = ["$ curl -v"]
  810. components.append("-X \(method)")
  811. if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
  812. let protectionSpace = URLProtectionSpace(host: host,
  813. port: url.port ?? 0,
  814. protocol: url.scheme,
  815. realm: host,
  816. authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  817. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  818. for credential in credentials {
  819. guard let user = credential.user, let password = credential.password else { continue }
  820. components.append("-u \(user):\(password)")
  821. }
  822. } else {
  823. if let credential = credential, let user = credential.user, let password = credential.password {
  824. components.append("-u \(user):\(password)")
  825. }
  826. }
  827. }
  828. if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
  829. if
  830. let cookieStorage = configuration.httpCookieStorage,
  831. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty {
  832. let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
  833. components.append("-b \"\(allCookies)\"")
  834. }
  835. }
  836. var headers = HTTPHeaders()
  837. if let sessionHeaders = delegate?.sessionConfiguration.headers {
  838. for header in sessionHeaders where header.name != "Cookie" {
  839. headers[header.name] = header.value
  840. }
  841. }
  842. for header in request.headers where header.name != "Cookie" {
  843. headers[header.name] = header.value
  844. }
  845. for header in headers {
  846. let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"")
  847. components.append("-H \"\(header.name): \(escapedValue)\"")
  848. }
  849. if let httpBodyData = request.httpBody {
  850. let httpBody = String(decoding: httpBodyData, as: UTF8.self)
  851. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  852. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  853. components.append("-d \"\(escapedBody)\"")
  854. }
  855. components.append("\"\(url.absoluteString)\"")
  856. return components.joined(separator: " \\\n\t")
  857. }
  858. }
  859. /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
  860. public protocol RequestDelegate: AnyObject {
  861. /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s.
  862. var sessionConfiguration: URLSessionConfiguration { get }
  863. /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler.
  864. var startImmediately: Bool { get }
  865. /// Notifies the delegate the `Request` has reached a point where it needs cleanup.
  866. ///
  867. /// - Parameter request: The `Request` to cleanup after.
  868. func cleanup(after request: Request)
  869. /// Asynchronously ask the delegate whether a `Request` will be retried.
  870. ///
  871. /// - Parameters:
  872. /// - request: `Request` which failed.
  873. /// - error: `Error` which produced the failure.
  874. /// - completion: Closure taking the `RetryResult` for evaluation.
  875. func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void)
  876. /// Asynchronously retry the `Request`.
  877. ///
  878. /// - Parameters:
  879. /// - request: `Request` which will be retried.
  880. /// - timeDelay: `TimeInterval` after which the retry will be triggered.
  881. func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
  882. }
  883. // MARK: - Subclasses
  884. // MARK: - DataRequest
  885. /// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`.
  886. public class DataRequest: Request {
  887. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  888. public let convertible: URLRequestConvertible
  889. /// `Data` read from the server so far.
  890. public var data: Data? { dataMutableState.data }
  891. private struct DataMutableState {
  892. var data: Data?
  893. var httpResponseHandler: (queue: DispatchQueue,
  894. handler: (_ response: HTTPURLResponse,
  895. _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void)?
  896. }
  897. private let dataMutableState = Protected(DataMutableState())
  898. /// Creates a `DataRequest` using the provided parameters.
  899. ///
  900. /// - Parameters:
  901. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  902. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  903. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  904. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  905. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  906. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  907. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  908. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  909. init(id: UUID = UUID(),
  910. convertible: URLRequestConvertible,
  911. underlyingQueue: DispatchQueue,
  912. serializationQueue: DispatchQueue,
  913. eventMonitor: EventMonitor?,
  914. interceptor: RequestInterceptor?,
  915. delegate: RequestDelegate) {
  916. self.convertible = convertible
  917. super.init(id: id,
  918. underlyingQueue: underlyingQueue,
  919. serializationQueue: serializationQueue,
  920. eventMonitor: eventMonitor,
  921. interceptor: interceptor,
  922. delegate: delegate)
  923. }
  924. override func reset() {
  925. super.reset()
  926. dataMutableState.write { mutableState in
  927. mutableState.data = nil
  928. }
  929. }
  930. /// Called when `Data` is received by this instance.
  931. ///
  932. /// - Note: Also calls `updateDownloadProgress`.
  933. ///
  934. /// - Parameter data: The `Data` received.
  935. func didReceive(data: Data) {
  936. dataMutableState.write { mutableState in
  937. if mutableState.data == nil {
  938. mutableState.data = data
  939. } else {
  940. mutableState.data?.append(data)
  941. }
  942. }
  943. updateDownloadProgress()
  944. }
  945. func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
  946. dataMutableState.read { dataMutableState in
  947. guard let httpResponseHandler = dataMutableState.httpResponseHandler else {
  948. underlyingQueue.async { completionHandler(.allow) }
  949. return
  950. }
  951. httpResponseHandler.queue.async {
  952. httpResponseHandler.handler(response) { disposition in
  953. if disposition == .cancel {
  954. self.mutableState.write { mutableState in
  955. mutableState.state = .cancelled
  956. mutableState.error = mutableState.error ?? AFError.explicitlyCancelled
  957. }
  958. }
  959. self.underlyingQueue.async {
  960. completionHandler(disposition.sessionDisposition)
  961. }
  962. }
  963. }
  964. }
  965. }
  966. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  967. let copiedRequest = request
  968. return session.dataTask(with: copiedRequest)
  969. }
  970. /// Called to update the `downloadProgress` of the instance.
  971. func updateDownloadProgress() {
  972. let totalBytesReceived = Int64(data?.count ?? 0)
  973. let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  974. downloadProgress.totalUnitCount = totalBytesExpected
  975. downloadProgress.completedUnitCount = totalBytesReceived
  976. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  977. }
  978. /// Validates the request, using the specified closure.
  979. ///
  980. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  981. ///
  982. /// - Parameter validation: `Validation` closure used to validate the response.
  983. ///
  984. /// - Returns: The instance.
  985. @discardableResult
  986. public func validate(_ validation: @escaping Validation) -> Self {
  987. let validator: () -> Void = { [unowned self] in
  988. guard error == nil, let response = response else { return }
  989. let result = validation(request, response, data)
  990. if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) }
  991. eventMonitor?.request(self,
  992. didValidateRequest: request,
  993. response: response,
  994. data: data,
  995. withResult: result)
  996. }
  997. validators.write { $0.append(validator) }
  998. return self
  999. }
  1000. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion
  1001. /// handler to return a `ResponseDisposition` value.
  1002. ///
  1003. /// - Parameters:
  1004. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  1005. /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided
  1006. /// MUST be called, otherwise the request will never complete.
  1007. ///
  1008. /// - Returns: The instance.
  1009. @_disfavoredOverload
  1010. @discardableResult
  1011. public func onHTTPResponse(
  1012. on queue: DispatchQueue = .main,
  1013. perform handler: @escaping (_ response: HTTPURLResponse,
  1014. _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void
  1015. ) -> Self {
  1016. dataMutableState.write { mutableState in
  1017. mutableState.httpResponseHandler = (queue, handler)
  1018. }
  1019. return self
  1020. }
  1021. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`.
  1022. ///
  1023. /// - Parameters:
  1024. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  1025. /// - handler: Closure called when the instance produces an `HTTPURLResponse`.
  1026. ///
  1027. /// - Returns: The instance.
  1028. @discardableResult
  1029. public func onHTTPResponse(on queue: DispatchQueue = .main,
  1030. perform handler: @escaping (HTTPURLResponse) -> Void) -> Self {
  1031. onHTTPResponse(on: queue) { response, completionHandler in
  1032. handler(response)
  1033. completionHandler(.allow)
  1034. }
  1035. return self
  1036. }
  1037. }
  1038. // MARK: - DataStreamRequest
  1039. /// `Request` subclass which streams HTTP response `Data` through a `Handler` closure.
  1040. public final class DataStreamRequest: Request {
  1041. /// Closure type handling `DataStreamRequest.Stream` values.
  1042. public typealias Handler<Success, Failure: Error> = (Stream<Success, Failure>) throws -> Void
  1043. /// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used
  1044. /// to stop the stream at any time.
  1045. public struct Stream<Success, Failure: Error> {
  1046. /// Latest `Event` from the stream.
  1047. public let event: Event<Success, Failure>
  1048. /// Token used to cancel the stream.
  1049. public let token: CancellationToken
  1050. /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
  1051. public func cancel() {
  1052. token.cancel()
  1053. }
  1054. }
  1055. /// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed
  1056. /// `Data` or the completion of the stream.
  1057. public enum Event<Success, Failure: Error> {
  1058. /// Output produced every time the instance receives additional `Data`. The associated value contains the
  1059. /// `Result` of processing the incoming `Data`.
  1060. case stream(Result<Success, Failure>)
  1061. /// Output produced when the instance has completed, whether due to stream end, cancellation, or an error.
  1062. /// Associated `Completion` value contains the final state.
  1063. case complete(Completion)
  1064. }
  1065. /// Value containing the state of a `DataStreamRequest` when the stream was completed.
  1066. public struct Completion {
  1067. /// Last `URLRequest` issued by the instance.
  1068. public let request: URLRequest?
  1069. /// Last `HTTPURLResponse` received by the instance.
  1070. public let response: HTTPURLResponse?
  1071. /// Last `URLSessionTaskMetrics` produced for the instance.
  1072. public let metrics: URLSessionTaskMetrics?
  1073. /// `AFError` produced for the instance, if any.
  1074. public let error: AFError?
  1075. }
  1076. /// Type used to cancel an ongoing stream.
  1077. public struct CancellationToken {
  1078. weak var request: DataStreamRequest?
  1079. init(_ request: DataStreamRequest) {
  1080. self.request = request
  1081. }
  1082. /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
  1083. public func cancel() {
  1084. request?.cancel()
  1085. }
  1086. }
  1087. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  1088. public let convertible: URLRequestConvertible
  1089. /// Whether or not the instance will be cancelled if stream parsing encounters an error.
  1090. public let automaticallyCancelOnStreamError: Bool
  1091. /// Internal mutable state specific to this type.
  1092. struct StreamMutableState {
  1093. /// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called.
  1094. var outputStream: OutputStream?
  1095. /// Stream closures called as `Data` is received.
  1096. var streams: [(_ data: Data) -> Void] = []
  1097. /// Number of currently executing streams. Used to ensure completions are only fired after all streams are
  1098. /// enqueued.
  1099. var numberOfExecutingStreams = 0
  1100. /// Completion calls enqueued while streams are still executing.
  1101. var enqueuedCompletionEvents: [() -> Void] = []
  1102. /// Handler for any `HTTPURLResponse`s received.
  1103. var httpResponseHandler: (queue: DispatchQueue,
  1104. handler: (_ response: HTTPURLResponse,
  1105. _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void)?
  1106. }
  1107. let streamMutableState = Protected(StreamMutableState())
  1108. /// Creates a `DataStreamRequest` using the provided parameters.
  1109. ///
  1110. /// - Parameters:
  1111. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()`
  1112. /// by default.
  1113. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this
  1114. /// instance.
  1115. /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error`
  1116. /// is thrown while serializing stream `Data`.
  1117. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1118. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default
  1119. /// targets
  1120. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1121. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1122. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1123. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by
  1124. /// the `Request`.
  1125. init(id: UUID = UUID(),
  1126. convertible: URLRequestConvertible,
  1127. automaticallyCancelOnStreamError: Bool,
  1128. underlyingQueue: DispatchQueue,
  1129. serializationQueue: DispatchQueue,
  1130. eventMonitor: EventMonitor?,
  1131. interceptor: RequestInterceptor?,
  1132. delegate: RequestDelegate) {
  1133. self.convertible = convertible
  1134. self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError
  1135. super.init(id: id,
  1136. underlyingQueue: underlyingQueue,
  1137. serializationQueue: serializationQueue,
  1138. eventMonitor: eventMonitor,
  1139. interceptor: interceptor,
  1140. delegate: delegate)
  1141. }
  1142. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1143. let copiedRequest = request
  1144. return session.dataTask(with: copiedRequest)
  1145. }
  1146. override func finish(error: AFError? = nil) {
  1147. streamMutableState.write { state in
  1148. state.outputStream?.close()
  1149. }
  1150. super.finish(error: error)
  1151. }
  1152. func didReceive(data: Data) {
  1153. streamMutableState.write { state in
  1154. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  1155. if let stream = state.outputStream {
  1156. underlyingQueue.async {
  1157. var bytes = Array(data)
  1158. stream.write(&bytes, maxLength: bytes.count)
  1159. }
  1160. }
  1161. #endif
  1162. state.numberOfExecutingStreams += state.streams.count
  1163. let localState = state
  1164. underlyingQueue.async { localState.streams.forEach { $0(data) } }
  1165. }
  1166. }
  1167. func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
  1168. streamMutableState.read { dataMutableState in
  1169. guard let httpResponseHandler = dataMutableState.httpResponseHandler else {
  1170. underlyingQueue.async { completionHandler(.allow) }
  1171. return
  1172. }
  1173. httpResponseHandler.queue.async {
  1174. httpResponseHandler.handler(response) { disposition in
  1175. if disposition == .cancel {
  1176. self.mutableState.write { mutableState in
  1177. mutableState.state = .cancelled
  1178. mutableState.error = mutableState.error ?? AFError.explicitlyCancelled
  1179. }
  1180. }
  1181. self.underlyingQueue.async {
  1182. completionHandler(disposition.sessionDisposition)
  1183. }
  1184. }
  1185. }
  1186. }
  1187. }
  1188. /// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure.
  1189. ///
  1190. /// - Parameter validation: `Validation` closure used to validate the request and response.
  1191. ///
  1192. /// - Returns: The `DataStreamRequest`.
  1193. @discardableResult
  1194. public func validate(_ validation: @escaping Validation) -> Self {
  1195. let validator: () -> Void = { [unowned self] in
  1196. guard error == nil, let response = response else { return }
  1197. let result = validation(request, response)
  1198. if case let .failure(error) = result {
  1199. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  1200. }
  1201. eventMonitor?.request(self,
  1202. didValidateRequest: request,
  1203. response: response,
  1204. withResult: result)
  1205. }
  1206. validators.write { $0.append(validator) }
  1207. return self
  1208. }
  1209. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  1210. /// Produces an `InputStream` that receives the `Data` received by the instance.
  1211. ///
  1212. /// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`.
  1213. /// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or
  1214. /// not the creating session has `startRequestsImmediately` set to `true`.
  1215. ///
  1216. /// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`.
  1217. ///
  1218. /// - Returns: The `InputStream` bound to the internal `OutboundStream`.
  1219. public func asInputStream(bufferSize: Int = 1024) -> InputStream? {
  1220. defer { resume() }
  1221. var inputStream: InputStream?
  1222. streamMutableState.write { state in
  1223. Foundation.Stream.getBoundStreams(withBufferSize: bufferSize,
  1224. inputStream: &inputStream,
  1225. outputStream: &state.outputStream)
  1226. state.outputStream?.open()
  1227. }
  1228. return inputStream
  1229. }
  1230. #endif
  1231. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion
  1232. /// handler to return a `ResponseDisposition` value.
  1233. ///
  1234. /// - Parameters:
  1235. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  1236. /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided
  1237. /// MUST be called, otherwise the request will never complete.
  1238. ///
  1239. /// - Returns: The instance.
  1240. @_disfavoredOverload
  1241. @discardableResult
  1242. public func onHTTPResponse(
  1243. on queue: DispatchQueue = .main,
  1244. perform handler: @escaping (_ response: HTTPURLResponse,
  1245. _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void
  1246. ) -> Self {
  1247. streamMutableState.write { mutableState in
  1248. mutableState.httpResponseHandler = (queue, handler)
  1249. }
  1250. return self
  1251. }
  1252. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`.
  1253. ///
  1254. /// - Parameters:
  1255. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  1256. /// - handler: Closure called when the instance produces an `HTTPURLResponse`.
  1257. ///
  1258. /// - Returns: The instance.
  1259. @discardableResult
  1260. public func onHTTPResponse(on queue: DispatchQueue = .main,
  1261. perform handler: @escaping (HTTPURLResponse) -> Void) -> Self {
  1262. onHTTPResponse(on: queue) { response, completionHandler in
  1263. handler(response)
  1264. completionHandler(.allow)
  1265. }
  1266. return self
  1267. }
  1268. func capturingError(from closure: () throws -> Void) {
  1269. do {
  1270. try closure()
  1271. } catch {
  1272. self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
  1273. cancel()
  1274. }
  1275. }
  1276. func appendStreamCompletion<Success, Failure>(on queue: DispatchQueue,
  1277. stream: @escaping Handler<Success, Failure>) {
  1278. appendResponseSerializer {
  1279. self.underlyingQueue.async {
  1280. self.responseSerializerDidComplete {
  1281. self.streamMutableState.write { state in
  1282. guard state.numberOfExecutingStreams == 0 else {
  1283. state.enqueuedCompletionEvents.append {
  1284. self.enqueueCompletion(on: queue, stream: stream)
  1285. }
  1286. return
  1287. }
  1288. self.enqueueCompletion(on: queue, stream: stream)
  1289. }
  1290. }
  1291. }
  1292. }
  1293. }
  1294. func enqueueCompletion<Success, Failure>(on queue: DispatchQueue,
  1295. stream: @escaping Handler<Success, Failure>) {
  1296. queue.async {
  1297. do {
  1298. let completion = Completion(request: self.request,
  1299. response: self.response,
  1300. metrics: self.metrics,
  1301. error: self.error)
  1302. try stream(.init(event: .complete(completion), token: .init(self)))
  1303. } catch {
  1304. // Ignore error, as errors on Completion can't be handled anyway.
  1305. }
  1306. }
  1307. }
  1308. }
  1309. extension DataStreamRequest.Stream {
  1310. /// Incoming `Result` values from `Event.stream`.
  1311. public var result: Result<Success, Failure>? {
  1312. guard case let .stream(result) = event else { return nil }
  1313. return result
  1314. }
  1315. /// `Success` value of the instance, if any.
  1316. public var value: Success? {
  1317. guard case let .success(value) = result else { return nil }
  1318. return value
  1319. }
  1320. /// `Failure` value of the instance, if any.
  1321. public var error: Failure? {
  1322. guard case let .failure(error) = result else { return nil }
  1323. return error
  1324. }
  1325. /// `Completion` value of the instance, if any.
  1326. public var completion: DataStreamRequest.Completion? {
  1327. guard case let .complete(completion) = event else { return nil }
  1328. return completion
  1329. }
  1330. }
  1331. // MARK: - WebSocketRequest
  1332. #if canImport(Darwin) && !canImport(FoundationNetworking) && swift(>=5.11) && hasFeature(FullTypedThrows)
  1333. /// `Request` subclass which manages a WebSocket connection using `URLSessionWebSocketTask`.
  1334. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  1335. public final class WebSocketRequest: Request {
  1336. enum IncomingEvent {
  1337. case connected(protocol: String?)
  1338. case receivedMessage(URLSessionWebSocketTask.Message)
  1339. case disconnected(closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?)
  1340. case completed(Completion)
  1341. }
  1342. public struct Event<Success, Failure: Error> {
  1343. public enum Kind {
  1344. case connected(protocol: String?)
  1345. case receivedMessage(Success)
  1346. case serializerFailed(Failure)
  1347. // Only received if the server disconnects or we cancel with code, not if we do a simple cancel or error.
  1348. case disconnected(closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?)
  1349. case completed(Completion)
  1350. }
  1351. weak var socket: WebSocketRequest?
  1352. public let kind: Kind
  1353. public var message: Success? {
  1354. guard case let .receivedMessage(message) = kind else { return nil }
  1355. return message
  1356. }
  1357. init(socket: WebSocketRequest, kind: Kind) {
  1358. self.socket = socket
  1359. self.kind = kind
  1360. }
  1361. public func close(sending closeCode: URLSessionWebSocketTask.CloseCode, reason: Data? = nil) {
  1362. socket?.close(sending: closeCode, reason: reason)
  1363. }
  1364. public func cancel() {
  1365. socket?.cancel()
  1366. }
  1367. public func sendPing(respondingOn queue: DispatchQueue = .main, onResponse: @escaping (PingResponse) -> Void) {
  1368. socket?.sendPing(respondingOn: queue, onResponse: onResponse)
  1369. }
  1370. // func mapMessage<NewSuccess>(_ transform: (URLSessionWebSocketTask.Message) throws -> NewSuccess) rethrows -> Event<NewSuccess, Error> {
  1371. // switch self {
  1372. // case let .connected(`protocol`):
  1373. // return .connected(`protocol`)
  1374. // case let .receiveMessage(message):
  1375. // do {
  1376. // let value = try transform(message)
  1377. // return .receivedMessage(<#T##URLSessionWebSocketTask.Message#>)
  1378. // }
  1379. // }
  1380. // }
  1381. }
  1382. public struct Completion {
  1383. /// Last `URLRequest` issued by the instance.
  1384. public let request: URLRequest?
  1385. /// Last `HTTPURLResponse` received by the instance.
  1386. public let response: HTTPURLResponse?
  1387. /// Last `URLSessionTaskMetrics` produced for the instance.
  1388. public let metrics: URLSessionTaskMetrics?
  1389. /// `AFError` produced for the instance, if any.
  1390. public let error: AFError?
  1391. }
  1392. public struct Configuration {
  1393. public static var `default`: Self { Self() }
  1394. public static func `protocol`(_ protocol: String) -> Self {
  1395. Self(protocol: `protocol`)
  1396. }
  1397. public static func maximumMessageSize(_ maximumMessageSize: Int) -> Self {
  1398. Self(maximumMessageSize: maximumMessageSize)
  1399. }
  1400. public static func pingInterval(_ pingInterval: TimeInterval) -> Self {
  1401. Self(pingInterval: pingInterval)
  1402. }
  1403. public let `protocol`: String?
  1404. public let maximumMessageSize: Int
  1405. public let pingInterval: TimeInterval?
  1406. init(protocol: String? = nil, maximumMessageSize: Int = 1_048_576, pingInterval: TimeInterval? = nil) {
  1407. self.protocol = `protocol`
  1408. self.maximumMessageSize = maximumMessageSize
  1409. self.pingInterval = pingInterval
  1410. }
  1411. }
  1412. /// Response to a sent ping.
  1413. public enum PingResponse {
  1414. public struct Pong {
  1415. let start: Date
  1416. let end: Date
  1417. let latency: TimeInterval
  1418. }
  1419. /// Received a pong with the associated state.
  1420. case pong(Pong)
  1421. /// Received an error.
  1422. case error(Error)
  1423. /// Did not send the ping, the request is cancelled or suspended.
  1424. case unsent
  1425. }
  1426. struct SocketMutableState {
  1427. var enqueuedSends: [(message: URLSessionWebSocketTask.Message,
  1428. queue: DispatchQueue,
  1429. completionHandler: (Result<Void, Error>) -> Void)] = []
  1430. var handlers: [(queue: DispatchQueue, handler: (_ event: IncomingEvent) -> Void)] = []
  1431. var pingTimerItem: DispatchWorkItem?
  1432. }
  1433. let socketMutableState = Protected(SocketMutableState())
  1434. var socket: URLSessionWebSocketTask? {
  1435. task as? URLSessionWebSocketTask
  1436. }
  1437. public let convertible: URLRequestConvertible
  1438. public let configuration: Configuration
  1439. init(id: UUID = UUID(),
  1440. convertible: URLRequestConvertible,
  1441. configuration: Configuration,
  1442. underlyingQueue: DispatchQueue,
  1443. serializationQueue: DispatchQueue,
  1444. eventMonitor: EventMonitor?,
  1445. interceptor: RequestInterceptor?,
  1446. delegate: RequestDelegate) {
  1447. self.convertible = convertible
  1448. self.configuration = configuration
  1449. super.init(id: id,
  1450. underlyingQueue: underlyingQueue,
  1451. serializationQueue: serializationQueue,
  1452. eventMonitor: eventMonitor,
  1453. interceptor: interceptor,
  1454. delegate: delegate)
  1455. }
  1456. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1457. var copiedRequest = request
  1458. let task: URLSessionWebSocketTask
  1459. if let `protocol` = configuration.protocol {
  1460. copiedRequest.headers.update(.websocketProtocol(`protocol`))
  1461. task = session.webSocketTask(with: copiedRequest)
  1462. } else {
  1463. task = session.webSocketTask(with: copiedRequest)
  1464. }
  1465. task.maximumMessageSize = configuration.maximumMessageSize
  1466. return task
  1467. }
  1468. override func didCreateTask(_ task: URLSessionTask) {
  1469. super.didCreateTask(task)
  1470. guard let webSocketTask = task as? URLSessionWebSocketTask else {
  1471. fatalError("Invalid task of type \(task.self) created for WebSocketRequest.")
  1472. }
  1473. // TODO: What about the any old tasks? Reset their receive?
  1474. listen(to: webSocketTask)
  1475. // Empty pending messages.
  1476. socketMutableState.write { state in
  1477. guard !state.enqueuedSends.isEmpty else { return }
  1478. let sends = state.enqueuedSends
  1479. self.underlyingQueue.async {
  1480. sends.forEach { send in
  1481. webSocketTask.send(send.message) { error in
  1482. send.queue.async {
  1483. send.completionHandler(Result(value: (), error: error))
  1484. }
  1485. }
  1486. }
  1487. }
  1488. state.enqueuedSends = []
  1489. }
  1490. }
  1491. func didClose() {
  1492. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  1493. mutableState.write { mutableState in
  1494. // Check whether error is cancellation or other websocket closing error.
  1495. // If so, remove it.
  1496. // Otherwise keep it.
  1497. if case let .sessionTaskFailed(error) = mutableState.error, (error as? URLError)?.code == .cancelled {
  1498. mutableState.error = nil
  1499. }
  1500. }
  1501. // TODO: Still issue this event?
  1502. eventMonitor?.requestDidCancel(self)
  1503. }
  1504. @discardableResult
  1505. public func close(sending closeCode: URLSessionWebSocketTask.CloseCode, reason: Data? = nil) -> Self {
  1506. cancelAutomaticPing()
  1507. mutableState.write { mutableState in
  1508. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  1509. mutableState.state = .cancelled
  1510. underlyingQueue.async { self.didClose() }
  1511. guard let task = mutableState.tasks.last, task.state != .completed else {
  1512. underlyingQueue.async { self.finish() }
  1513. return
  1514. }
  1515. // Resume to ensure metrics are gathered.
  1516. task.resume()
  1517. // Cast from state directly, not the property, otherwise the lock is recursive.
  1518. (mutableState.tasks.last as? URLSessionWebSocketTask)?.cancel(with: closeCode, reason: reason)
  1519. underlyingQueue.async { self.didCancelTask(task) }
  1520. }
  1521. return self
  1522. }
  1523. @discardableResult
  1524. override public func cancel() -> Self {
  1525. cancelAutomaticPing()
  1526. return super.cancel()
  1527. }
  1528. func didConnect(protocol: String?) {
  1529. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  1530. socketMutableState.read { state in
  1531. // TODO: Capture HTTPURLResponse here too?
  1532. state.handlers.forEach { handler in
  1533. // Saved handler calls out to serializationQueue immediately, then to handler's queue.
  1534. handler.handler(.connected(protocol: `protocol`))
  1535. }
  1536. }
  1537. if let pingInterval = configuration.pingInterval {
  1538. startAutomaticPing(onInterval: pingInterval)
  1539. }
  1540. }
  1541. public func sendPing(respondingOn queue: DispatchQueue = .main, onResponse: @escaping (PingResponse) -> Void) {
  1542. guard isResumed else {
  1543. queue.async { onResponse(.unsent) }
  1544. return
  1545. }
  1546. let start = Date()
  1547. let startTimestamp = ProcessInfo.processInfo.systemUptime
  1548. socket?.sendPing { error in
  1549. // Calls back on delegate queue / rootQueue / underlyingQueue
  1550. if let error = error {
  1551. queue.async {
  1552. onResponse(.error(error))
  1553. }
  1554. // TODO: What to do with failed ping? Configure for failure, auto retry, or stop pinging?
  1555. } else {
  1556. let end = Date()
  1557. let endTimestamp = ProcessInfo.processInfo.systemUptime
  1558. let pong = PingResponse.Pong(start: start, end: end, latency: endTimestamp - startTimestamp)
  1559. queue.async {
  1560. onResponse(.pong(pong))
  1561. }
  1562. }
  1563. }
  1564. }
  1565. func startAutomaticPing(onInterval pingInterval: TimeInterval) {
  1566. socketMutableState.write { mutableState in
  1567. guard isResumed else {
  1568. // Defer out of lock.
  1569. defer { cancelAutomaticPing() }
  1570. return
  1571. }
  1572. let item = DispatchWorkItem { [weak self] in
  1573. guard let self = self, self.isResumed else { return }
  1574. self.sendPing(respondingOn: self.underlyingQueue) { response in
  1575. guard case .pong = response else { return }
  1576. self.startAutomaticPing(onInterval: pingInterval)
  1577. }
  1578. }
  1579. mutableState.pingTimerItem = item
  1580. underlyingQueue.asyncAfter(deadline: .now() + pingInterval, execute: item)
  1581. }
  1582. }
  1583. func cancelAutomaticPing() {
  1584. socketMutableState.write { mutableState in
  1585. mutableState.pingTimerItem?.cancel()
  1586. mutableState.pingTimerItem = nil
  1587. }
  1588. }
  1589. func didDisconnect(closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
  1590. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  1591. cancelAutomaticPing()
  1592. socketMutableState.read { state in
  1593. state.handlers.forEach { handler in
  1594. // Saved handler calls out to serializationQueue immediately, then to handler's queue.
  1595. handler.handler(.disconnected(closeCode: closeCode, reason: reason))
  1596. }
  1597. }
  1598. }
  1599. private func listen(to task: URLSessionWebSocketTask) {
  1600. // TODO: Do we care about the cycle while receiving?
  1601. task.receive { result in
  1602. switch result {
  1603. case let .success(message):
  1604. self.socketMutableState.read { state in
  1605. state.handlers.forEach { handler in
  1606. // Saved handler calls out to serializationQueue immediately, then to handler's queue.
  1607. handler.handler(.receivedMessage(message))
  1608. }
  1609. }
  1610. self.listen(to: task)
  1611. case .failure:
  1612. // It doesn't seem like any relevant errors are received here, just incorrect garbage, like errors when
  1613. // the socket disconnects.
  1614. break
  1615. }
  1616. }
  1617. }
  1618. @discardableResult
  1619. public func streamSerializer<Serializer>(
  1620. _ serializer: Serializer,
  1621. on queue: DispatchQueue = .main,
  1622. handler: @escaping (_ event: Event<Serializer.Success, Serializer.Failure>) -> Void
  1623. ) -> Self where Serializer: WebSocketMessageSerializer {
  1624. forIncomingEvent(on: queue) { incomingEvent in
  1625. let event: Event<Serializer.Success, Serializer.Failure>
  1626. switch incomingEvent {
  1627. case let .connected(`protocol`):
  1628. event = .init(socket: self, kind: .connected(protocol: `protocol`))
  1629. case let .receivedMessage(message):
  1630. do {
  1631. let serializedMessage = try serializer.decode(message)
  1632. event = .init(socket: self, kind: .receivedMessage(serializedMessage))
  1633. } catch {
  1634. event = .init(socket: self, kind: .serializerFailed(error))
  1635. }
  1636. case let .disconnected(closeCode, reason):
  1637. event = .init(socket: self, kind: .disconnected(closeCode: closeCode, reason: reason))
  1638. case let .completed(completion):
  1639. event = .init(socket: self, kind: .completed(completion))
  1640. }
  1641. queue.async { handler(event) }
  1642. }
  1643. }
  1644. @discardableResult
  1645. public func streamDecodableEvents<Value>(
  1646. _ type: Value.Type = Value.self,
  1647. on queue: DispatchQueue = .main,
  1648. using decoder: DataDecoder = JSONDecoder(),
  1649. handler: @escaping (_ event: Event<Value, DecodableWebSocketMessageDecoder<Value>.Error>) -> Void
  1650. ) -> Self where Value: Decodable {
  1651. streamSerializer(DecodableWebSocketMessageDecoder<Value>(decoder: decoder), on: queue, handler: handler)
  1652. }
  1653. @discardableResult
  1654. public func streamDecodable<Value>(
  1655. _ type: Value.Type = Value.self,
  1656. on queue: DispatchQueue = .main,
  1657. using decoder: DataDecoder = JSONDecoder(),
  1658. handler: @escaping (_ value: Value) -> Void
  1659. ) -> Self where Value: Decodable {
  1660. streamDecodableEvents(Value.self, on: queue) { event in
  1661. event.message.map(handler)
  1662. }
  1663. }
  1664. @discardableResult
  1665. public func streamMessageEvents(
  1666. on queue: DispatchQueue = .main,
  1667. handler: @escaping (_ event: Event<URLSessionWebSocketTask.Message, Never>) -> Void
  1668. ) -> Self {
  1669. forIncomingEvent(on: queue) { incomingEvent in
  1670. let event: Event<URLSessionWebSocketTask.Message, Never>
  1671. switch incomingEvent {
  1672. case let .connected(`protocol`):
  1673. event = .init(socket: self, kind: .connected(protocol: `protocol`))
  1674. case let .receivedMessage(message):
  1675. event = .init(socket: self, kind: .receivedMessage(message))
  1676. case let .disconnected(closeCode, reason):
  1677. event = .init(socket: self, kind: .disconnected(closeCode: closeCode, reason: reason))
  1678. case let .completed(completion):
  1679. event = .init(socket: self, kind: .completed(completion))
  1680. }
  1681. queue.async { handler(event) }
  1682. }
  1683. }
  1684. @discardableResult
  1685. public func streamMessages(
  1686. on queue: DispatchQueue = .main,
  1687. handler: @escaping (_ message: URLSessionWebSocketTask.Message) -> Void
  1688. ) -> Self {
  1689. streamMessageEvents(on: queue) { event in
  1690. event.message.map(handler)
  1691. }
  1692. }
  1693. func forIncomingEvent(on queue: DispatchQueue, handler: @escaping (IncomingEvent) -> Void) -> Self {
  1694. socketMutableState.write { state in
  1695. state.handlers.append((queue: queue, handler: { incomingEvent in
  1696. self.serializationQueue.async {
  1697. handler(incomingEvent)
  1698. }
  1699. }))
  1700. }
  1701. appendResponseSerializer {
  1702. self.responseSerializerDidComplete {
  1703. self.serializationQueue.async {
  1704. handler(.completed(.init(request: self.request,
  1705. response: self.response,
  1706. metrics: self.metrics,
  1707. error: self.error)))
  1708. }
  1709. }
  1710. }
  1711. return self
  1712. }
  1713. public func send(_ message: URLSessionWebSocketTask.Message,
  1714. queue: DispatchQueue = .main,
  1715. completionHandler: @escaping (Result<Void, Error>) -> Void) {
  1716. guard !(isCancelled || isFinished) else { return }
  1717. guard let socket = socket else {
  1718. // URLSessionWebSocketTask note created yet, enqueue the send.
  1719. socketMutableState.write { mutableState in
  1720. mutableState.enqueuedSends.append((message, queue, completionHandler))
  1721. }
  1722. return
  1723. }
  1724. socket.send(message) { error in
  1725. queue.async {
  1726. completionHandler(Result(value: (), error: error))
  1727. }
  1728. }
  1729. }
  1730. }
  1731. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  1732. public protocol WebSocketMessageSerializer<Success, Failure> {
  1733. associatedtype Success
  1734. associatedtype Failure: Error
  1735. func decode(_ message: URLSessionWebSocketTask.Message) throws(Failure) -> Success
  1736. }
  1737. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  1738. public typealias EventOf<Serializer: WebSocketMessageSerializer> = WebSocketRequest.Event<Serializer.Success, Serializer.Failure>
  1739. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  1740. extension WebSocketMessageSerializer {
  1741. public static func json<Value>(
  1742. decoding type: Value.Type = Value.self,
  1743. using decoder: JSONDecoder = JSONDecoder()
  1744. ) -> DecodableWebSocketMessageDecoder<Value> where Self == DecodableWebSocketMessageDecoder<Value> {
  1745. Self(decoder: decoder)
  1746. }
  1747. static var passthrough: PassthroughWebSocketMessageDecoder {
  1748. PassthroughWebSocketMessageDecoder()
  1749. }
  1750. }
  1751. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  1752. public struct PassthroughWebSocketMessageDecoder: WebSocketMessageSerializer {
  1753. public func decode(_ message: URLSessionWebSocketTask.Message) throws(Never) -> URLSessionWebSocketTask.Message {
  1754. message
  1755. }
  1756. }
  1757. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  1758. public struct DecodableWebSocketMessageDecoder<Value: Decodable>: WebSocketMessageSerializer {
  1759. public enum Error: Swift.Error {
  1760. case decoding(Swift.Error)
  1761. case unknownMessage(String)
  1762. }
  1763. public let decoder: DataDecoder
  1764. public init(decoder: DataDecoder) {
  1765. self.decoder = decoder
  1766. }
  1767. public func decode(_ message: URLSessionWebSocketTask.Message) throws(Self.Error) -> Value {
  1768. let data = switch message {
  1769. case let .data(data): data
  1770. case let .string(string): Data(string.utf8)
  1771. @unknown default: throw .unknownMessage(String(describing: message))
  1772. }
  1773. do {
  1774. return try decoder.decode(Value.self, from: data)
  1775. } catch {
  1776. throw .decoding(error)
  1777. }
  1778. }
  1779. }
  1780. #endif
  1781. // MARK: - DownloadRequest
  1782. /// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`.
  1783. public class DownloadRequest: Request {
  1784. /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination
  1785. /// `URL`.
  1786. public struct Options: OptionSet {
  1787. /// Specifies that intermediate directories for the destination URL should be created.
  1788. public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
  1789. /// Specifies that any previous file at the destination `URL` should be removed.
  1790. public static let removePreviousFile = Options(rawValue: 1 << 1)
  1791. public let rawValue: Int
  1792. public init(rawValue: Int) {
  1793. self.rawValue = rawValue
  1794. }
  1795. }
  1796. // MARK: Destination
  1797. /// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the
  1798. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  1799. /// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and
  1800. /// the options defining how the file should be moved.
  1801. ///
  1802. /// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not
  1803. /// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory.
  1804. public typealias Destination = (_ temporaryURL: URL,
  1805. _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
  1806. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  1807. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  1808. ///
  1809. /// - Parameters:
  1810. /// - directory: The search path directory. `.documentDirectory` by default.
  1811. /// - domain: The search path domain mask. `.userDomainMask` by default.
  1812. /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by
  1813. /// default.
  1814. /// - Returns: The `Destination` closure.
  1815. public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
  1816. in domain: FileManager.SearchPathDomainMask = .userDomainMask,
  1817. options: Options = []) -> Destination {
  1818. { temporaryURL, response in
  1819. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  1820. let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
  1821. return (url, options)
  1822. }
  1823. }
  1824. /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends
  1825. /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files
  1826. /// with this destination must be additionally moved if they should survive the system reclamation of temporary
  1827. /// space.
  1828. static let defaultDestination: Destination = { url, _ in
  1829. (defaultDestinationURL(url), [])
  1830. }
  1831. /// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the
  1832. /// provided file name.
  1833. static let defaultDestinationURL: (URL) -> URL = { url in
  1834. let filename = "Alamofire_\(url.lastPathComponent)"
  1835. let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
  1836. return destination
  1837. }
  1838. // MARK: Downloadable
  1839. /// Type describing the source used to create the underlying `URLSessionDownloadTask`.
  1840. public enum Downloadable {
  1841. /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value.
  1842. case request(URLRequestConvertible)
  1843. /// Download should be started from the associated resume `Data` value.
  1844. case resumeData(Data)
  1845. }
  1846. // MARK: Mutable State
  1847. /// Type containing all mutable state for `DownloadRequest` instances.
  1848. private struct DownloadRequestMutableState {
  1849. /// Possible resume `Data` produced when cancelling the instance.
  1850. var resumeData: Data?
  1851. /// `URL` to which `Data` is being downloaded.
  1852. var fileURL: URL?
  1853. }
  1854. /// Protected mutable state specific to `DownloadRequest`.
  1855. private let mutableDownloadState = Protected(DownloadRequestMutableState())
  1856. /// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download
  1857. /// using the `download(resumingWith data:)` API.
  1858. ///
  1859. /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel).
  1860. public var resumeData: Data? {
  1861. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  1862. return mutableDownloadState.resumeData ?? error?.downloadResumeData
  1863. #else
  1864. return mutableDownloadState.resumeData
  1865. #endif
  1866. }
  1867. /// If the download is successful, the `URL` where the file was downloaded.
  1868. public var fileURL: URL? { mutableDownloadState.fileURL }
  1869. // MARK: Initial State
  1870. /// `Downloadable` value used for this instance.
  1871. public let downloadable: Downloadable
  1872. /// The `Destination` to which the downloaded file is moved.
  1873. let destination: Destination
  1874. /// Creates a `DownloadRequest` using the provided parameters.
  1875. ///
  1876. /// - Parameters:
  1877. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  1878. /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance.
  1879. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1880. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  1881. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1882. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1883. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1884. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`
  1885. /// - destination: `Destination` closure used to move the downloaded file to its final location.
  1886. init(id: UUID = UUID(),
  1887. downloadable: Downloadable,
  1888. underlyingQueue: DispatchQueue,
  1889. serializationQueue: DispatchQueue,
  1890. eventMonitor: EventMonitor?,
  1891. interceptor: RequestInterceptor?,
  1892. delegate: RequestDelegate,
  1893. destination: @escaping Destination) {
  1894. self.downloadable = downloadable
  1895. self.destination = destination
  1896. super.init(id: id,
  1897. underlyingQueue: underlyingQueue,
  1898. serializationQueue: serializationQueue,
  1899. eventMonitor: eventMonitor,
  1900. interceptor: interceptor,
  1901. delegate: delegate)
  1902. }
  1903. override func reset() {
  1904. super.reset()
  1905. mutableDownloadState.write {
  1906. $0.resumeData = nil
  1907. $0.fileURL = nil
  1908. }
  1909. }
  1910. /// Called when a download has finished.
  1911. ///
  1912. /// - Parameters:
  1913. /// - task: `URLSessionTask` that finished the download.
  1914. /// - result: `Result` of the automatic move to `destination`.
  1915. func didFinishDownloading(using task: URLSessionTask, with result: Result<URL, AFError>) {
  1916. eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
  1917. switch result {
  1918. case let .success(url): mutableDownloadState.fileURL = url
  1919. case let .failure(error): self.error = error
  1920. }
  1921. }
  1922. /// Updates the `downloadProgress` using the provided values.
  1923. ///
  1924. /// - Parameters:
  1925. /// - bytesWritten: Total bytes written so far.
  1926. /// - totalBytesExpectedToWrite: Total bytes expected to write.
  1927. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  1928. downloadProgress.totalUnitCount = totalBytesExpectedToWrite
  1929. downloadProgress.completedUnitCount += bytesWritten
  1930. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  1931. }
  1932. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1933. session.downloadTask(with: request)
  1934. }
  1935. /// Creates a `URLSessionTask` from the provided resume data.
  1936. ///
  1937. /// - Parameters:
  1938. /// - data: `Data` used to resume the download.
  1939. /// - session: `URLSession` used to create the `URLSessionTask`.
  1940. ///
  1941. /// - Returns: The `URLSessionTask` created.
  1942. public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
  1943. session.downloadTask(withResumeData: data)
  1944. }
  1945. /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended.
  1946. ///
  1947. /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use
  1948. /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`.
  1949. ///
  1950. /// - Returns: The instance.
  1951. @discardableResult
  1952. override public func cancel() -> Self {
  1953. cancel(producingResumeData: false)
  1954. }
  1955. /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be
  1956. /// resumed or suspended.
  1957. ///
  1958. /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if
  1959. /// available.
  1960. ///
  1961. /// - Returns: The instance.
  1962. @discardableResult
  1963. public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self {
  1964. cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil)
  1965. }
  1966. /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed
  1967. /// or suspended.
  1968. ///
  1969. /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData`
  1970. /// property.
  1971. ///
  1972. /// - Parameter completionHandler: The completion handler that is called when the download has been successfully
  1973. /// cancelled. It is not guaranteed to be called on a particular queue, so you may
  1974. /// want use an appropriate queue to perform your work.
  1975. ///
  1976. /// - Returns: The instance.
  1977. @discardableResult
  1978. public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self {
  1979. cancel(optionallyProducingResumeData: completionHandler)
  1980. }
  1981. /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed,
  1982. /// cancellation is performed without producing resume data.
  1983. ///
  1984. /// - Parameter completionHandler: Optional resume data handler.
  1985. ///
  1986. /// - Returns: The instance.
  1987. private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self {
  1988. mutableState.write { mutableState in
  1989. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  1990. mutableState.state = .cancelled
  1991. underlyingQueue.async { self.didCancel() }
  1992. guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
  1993. underlyingQueue.async { self.finish() }
  1994. return
  1995. }
  1996. if let completionHandler = completionHandler {
  1997. // Resume to ensure metrics are gathered.
  1998. task.resume()
  1999. task.cancel { resumeData in
  2000. self.mutableDownloadState.resumeData = resumeData
  2001. self.underlyingQueue.async { self.didCancelTask(task) }
  2002. completionHandler(resumeData)
  2003. }
  2004. } else {
  2005. // Resume to ensure metrics are gathered.
  2006. task.resume()
  2007. task.cancel()
  2008. self.underlyingQueue.async { self.didCancelTask(task) }
  2009. }
  2010. }
  2011. return self
  2012. }
  2013. /// Validates the request, using the specified closure.
  2014. ///
  2015. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  2016. ///
  2017. /// - Parameter validation: `Validation` closure to validate the response.
  2018. ///
  2019. /// - Returns: The instance.
  2020. @discardableResult
  2021. public func validate(_ validation: @escaping Validation) -> Self {
  2022. let validator: () -> Void = { [unowned self] in
  2023. guard error == nil, let response = response else { return }
  2024. let result = validation(request, response, fileURL)
  2025. if case let .failure(error) = result {
  2026. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  2027. }
  2028. eventMonitor?.request(self,
  2029. didValidateRequest: request,
  2030. response: response,
  2031. fileURL: fileURL,
  2032. withResult: result)
  2033. }
  2034. validators.write { $0.append(validator) }
  2035. return self
  2036. }
  2037. }
  2038. // MARK: - UploadRequest
  2039. /// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`.
  2040. public class UploadRequest: DataRequest {
  2041. /// Type describing the origin of the upload, whether `Data`, file, or stream.
  2042. public enum Uploadable {
  2043. /// Upload from the provided `Data` value.
  2044. case data(Data)
  2045. /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be
  2046. /// automatically removed once uploaded.
  2047. case file(URL, shouldRemove: Bool)
  2048. /// Upload from the provided `InputStream`.
  2049. case stream(InputStream)
  2050. }
  2051. // MARK: Initial State
  2052. /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance.
  2053. public let upload: UploadableConvertible
  2054. /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written
  2055. /// to disk.
  2056. public let fileManager: FileManager
  2057. // MARK: Mutable State
  2058. /// `Uploadable` value used by the instance.
  2059. public var uploadable: Uploadable?
  2060. /// Creates an `UploadRequest` using the provided parameters.
  2061. ///
  2062. /// - Parameters:
  2063. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  2064. /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed.
  2065. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  2066. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  2067. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  2068. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  2069. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  2070. /// - fileManager: `FileManager` used to perform cleanup tasks, including the removal of multipart form
  2071. /// encoded payloads written to disk.
  2072. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  2073. init(id: UUID = UUID(),
  2074. convertible: UploadConvertible,
  2075. underlyingQueue: DispatchQueue,
  2076. serializationQueue: DispatchQueue,
  2077. eventMonitor: EventMonitor?,
  2078. interceptor: RequestInterceptor?,
  2079. fileManager: FileManager,
  2080. delegate: RequestDelegate) {
  2081. upload = convertible
  2082. self.fileManager = fileManager
  2083. super.init(id: id,
  2084. convertible: convertible,
  2085. underlyingQueue: underlyingQueue,
  2086. serializationQueue: serializationQueue,
  2087. eventMonitor: eventMonitor,
  2088. interceptor: interceptor,
  2089. delegate: delegate)
  2090. }
  2091. /// Called when the `Uploadable` value has been created from the `UploadConvertible`.
  2092. ///
  2093. /// - Parameter uploadable: The `Uploadable` that was created.
  2094. func didCreateUploadable(_ uploadable: Uploadable) {
  2095. self.uploadable = uploadable
  2096. eventMonitor?.request(self, didCreateUploadable: uploadable)
  2097. }
  2098. /// Called when the `Uploadable` value could not be created.
  2099. ///
  2100. /// - Parameter error: `AFError` produced by the failure.
  2101. func didFailToCreateUploadable(with error: AFError) {
  2102. self.error = error
  2103. eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
  2104. retryOrFinish(error: error)
  2105. }
  2106. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  2107. guard let uploadable = uploadable else {
  2108. fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
  2109. }
  2110. switch uploadable {
  2111. case let .data(data): return session.uploadTask(with: request, from: data)
  2112. case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
  2113. case .stream: return session.uploadTask(withStreamedRequest: request)
  2114. }
  2115. }
  2116. override func reset() {
  2117. // Uploadable must be recreated on every retry.
  2118. uploadable = nil
  2119. super.reset()
  2120. }
  2121. /// Produces the `InputStream` from `uploadable`, if it can.
  2122. ///
  2123. /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash.
  2124. ///
  2125. /// - Returns: The `InputStream`.
  2126. func inputStream() -> InputStream {
  2127. guard let uploadable = uploadable else {
  2128. fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
  2129. }
  2130. guard case let .stream(stream) = uploadable else {
  2131. fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
  2132. }
  2133. eventMonitor?.request(self, didProvideInputStream: stream)
  2134. return stream
  2135. }
  2136. override public func cleanup() {
  2137. defer { super.cleanup() }
  2138. guard
  2139. let uploadable = uploadable,
  2140. case let .file(url, shouldRemove) = uploadable,
  2141. shouldRemove
  2142. else { return }
  2143. try? fileManager.removeItem(at: url)
  2144. }
  2145. }
  2146. /// A type that can produce an `UploadRequest.Uploadable` value.
  2147. public protocol UploadableConvertible {
  2148. /// Produces an `UploadRequest.Uploadable` value from the instance.
  2149. ///
  2150. /// - Returns: The `UploadRequest.Uploadable`.
  2151. /// - Throws: Any `Error` produced during creation.
  2152. func createUploadable() throws -> UploadRequest.Uploadable
  2153. }
  2154. extension UploadRequest.Uploadable: UploadableConvertible {
  2155. public func createUploadable() throws -> UploadRequest.Uploadable {
  2156. self
  2157. }
  2158. }
  2159. /// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`.
  2160. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {}