Request.swift 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600
  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)
  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.Output, Serializer.Failure>) -> Void
  1623. ) -> Self where Serializer: WebSocketMessageSerializer, Serializer.Failure == Error {
  1624. forIncomingEvent(on: queue) { incomingEvent in
  1625. let event: Event<Serializer.Output, 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, 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<Output, Failure> {
  1733. associatedtype Output
  1734. associatedtype Failure: Error = Error
  1735. func decode(_ message: URLSessionWebSocketTask.Message) throws -> Output
  1736. }
  1737. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  1738. extension WebSocketMessageSerializer {
  1739. public static func json<Value>(
  1740. decoder: JSONDecoder = JSONDecoder()
  1741. ) -> DecodableWebSocketMessageDecoder<Value> where Self == DecodableWebSocketMessageDecoder<Value> {
  1742. .json(decoder: decoder)
  1743. }
  1744. static var passthrough: PassthroughWebSocketMessageDecoder {
  1745. PassthroughWebSocketMessageDecoder()
  1746. }
  1747. }
  1748. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  1749. struct PassthroughWebSocketMessageDecoder: WebSocketMessageSerializer {
  1750. public typealias Failure = Never
  1751. public func decode(_ message: URLSessionWebSocketTask.Message) -> URLSessionWebSocketTask.Message {
  1752. message
  1753. }
  1754. }
  1755. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  1756. public struct DecodableWebSocketMessageDecoder<Value: Decodable>: WebSocketMessageSerializer {
  1757. public static func json(decoder: JSONDecoder = JSONDecoder()) -> DecodableWebSocketMessageDecoder<Value> {
  1758. DecodableWebSocketMessageDecoder(decoder: decoder)
  1759. }
  1760. public struct UnknownMessage: Error {}
  1761. public let decoder: DataDecoder
  1762. public init(decoder: DataDecoder) {
  1763. self.decoder = decoder
  1764. }
  1765. public func decode(_ message: URLSessionWebSocketTask.Message) throws -> Value {
  1766. switch message {
  1767. case let .data(data):
  1768. return try decoder.decode(Value.self, from: data)
  1769. case let .string(string):
  1770. return try decoder.decode(Value.self, from: Data(string.utf8))
  1771. @unknown default:
  1772. throw UnknownMessage()
  1773. }
  1774. }
  1775. }
  1776. #endif
  1777. // MARK: - DownloadRequest
  1778. /// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`.
  1779. public class DownloadRequest: Request {
  1780. /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination
  1781. /// `URL`.
  1782. public struct Options: OptionSet {
  1783. /// Specifies that intermediate directories for the destination URL should be created.
  1784. public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
  1785. /// Specifies that any previous file at the destination `URL` should be removed.
  1786. public static let removePreviousFile = Options(rawValue: 1 << 1)
  1787. public let rawValue: Int
  1788. public init(rawValue: Int) {
  1789. self.rawValue = rawValue
  1790. }
  1791. }
  1792. // MARK: Destination
  1793. /// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the
  1794. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  1795. /// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and
  1796. /// the options defining how the file should be moved.
  1797. ///
  1798. /// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not
  1799. /// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory.
  1800. public typealias Destination = (_ temporaryURL: URL,
  1801. _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
  1802. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  1803. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  1804. ///
  1805. /// - Parameters:
  1806. /// - directory: The search path directory. `.documentDirectory` by default.
  1807. /// - domain: The search path domain mask. `.userDomainMask` by default.
  1808. /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by
  1809. /// default.
  1810. /// - Returns: The `Destination` closure.
  1811. public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
  1812. in domain: FileManager.SearchPathDomainMask = .userDomainMask,
  1813. options: Options = []) -> Destination {
  1814. { temporaryURL, response in
  1815. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  1816. let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
  1817. return (url, options)
  1818. }
  1819. }
  1820. /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends
  1821. /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files
  1822. /// with this destination must be additionally moved if they should survive the system reclamation of temporary
  1823. /// space.
  1824. static let defaultDestination: Destination = { url, _ in
  1825. (defaultDestinationURL(url), [])
  1826. }
  1827. /// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the
  1828. /// provided file name.
  1829. static let defaultDestinationURL: (URL) -> URL = { url in
  1830. let filename = "Alamofire_\(url.lastPathComponent)"
  1831. let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
  1832. return destination
  1833. }
  1834. // MARK: Downloadable
  1835. /// Type describing the source used to create the underlying `URLSessionDownloadTask`.
  1836. public enum Downloadable {
  1837. /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value.
  1838. case request(URLRequestConvertible)
  1839. /// Download should be started from the associated resume `Data` value.
  1840. case resumeData(Data)
  1841. }
  1842. // MARK: Mutable State
  1843. /// Type containing all mutable state for `DownloadRequest` instances.
  1844. private struct DownloadRequestMutableState {
  1845. /// Possible resume `Data` produced when cancelling the instance.
  1846. var resumeData: Data?
  1847. /// `URL` to which `Data` is being downloaded.
  1848. var fileURL: URL?
  1849. }
  1850. /// Protected mutable state specific to `DownloadRequest`.
  1851. private let mutableDownloadState = Protected(DownloadRequestMutableState())
  1852. /// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download
  1853. /// using the `download(resumingWith data:)` API.
  1854. ///
  1855. /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel).
  1856. public var resumeData: Data? {
  1857. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  1858. return mutableDownloadState.resumeData ?? error?.downloadResumeData
  1859. #else
  1860. return mutableDownloadState.resumeData
  1861. #endif
  1862. }
  1863. /// If the download is successful, the `URL` where the file was downloaded.
  1864. public var fileURL: URL? { mutableDownloadState.fileURL }
  1865. // MARK: Initial State
  1866. /// `Downloadable` value used for this instance.
  1867. public let downloadable: Downloadable
  1868. /// The `Destination` to which the downloaded file is moved.
  1869. let destination: Destination
  1870. /// Creates a `DownloadRequest` using the provided parameters.
  1871. ///
  1872. /// - Parameters:
  1873. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  1874. /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance.
  1875. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1876. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  1877. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1878. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1879. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1880. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`
  1881. /// - destination: `Destination` closure used to move the downloaded file to its final location.
  1882. init(id: UUID = UUID(),
  1883. downloadable: Downloadable,
  1884. underlyingQueue: DispatchQueue,
  1885. serializationQueue: DispatchQueue,
  1886. eventMonitor: EventMonitor?,
  1887. interceptor: RequestInterceptor?,
  1888. delegate: RequestDelegate,
  1889. destination: @escaping Destination) {
  1890. self.downloadable = downloadable
  1891. self.destination = destination
  1892. super.init(id: id,
  1893. underlyingQueue: underlyingQueue,
  1894. serializationQueue: serializationQueue,
  1895. eventMonitor: eventMonitor,
  1896. interceptor: interceptor,
  1897. delegate: delegate)
  1898. }
  1899. override func reset() {
  1900. super.reset()
  1901. mutableDownloadState.write {
  1902. $0.resumeData = nil
  1903. $0.fileURL = nil
  1904. }
  1905. }
  1906. /// Called when a download has finished.
  1907. ///
  1908. /// - Parameters:
  1909. /// - task: `URLSessionTask` that finished the download.
  1910. /// - result: `Result` of the automatic move to `destination`.
  1911. func didFinishDownloading(using task: URLSessionTask, with result: Result<URL, AFError>) {
  1912. eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
  1913. switch result {
  1914. case let .success(url): mutableDownloadState.fileURL = url
  1915. case let .failure(error): self.error = error
  1916. }
  1917. }
  1918. /// Updates the `downloadProgress` using the provided values.
  1919. ///
  1920. /// - Parameters:
  1921. /// - bytesWritten: Total bytes written so far.
  1922. /// - totalBytesExpectedToWrite: Total bytes expected to write.
  1923. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  1924. downloadProgress.totalUnitCount = totalBytesExpectedToWrite
  1925. downloadProgress.completedUnitCount += bytesWritten
  1926. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  1927. }
  1928. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1929. session.downloadTask(with: request)
  1930. }
  1931. /// Creates a `URLSessionTask` from the provided resume data.
  1932. ///
  1933. /// - Parameters:
  1934. /// - data: `Data` used to resume the download.
  1935. /// - session: `URLSession` used to create the `URLSessionTask`.
  1936. ///
  1937. /// - Returns: The `URLSessionTask` created.
  1938. public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
  1939. session.downloadTask(withResumeData: data)
  1940. }
  1941. /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended.
  1942. ///
  1943. /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use
  1944. /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`.
  1945. ///
  1946. /// - Returns: The instance.
  1947. @discardableResult
  1948. override public func cancel() -> Self {
  1949. cancel(producingResumeData: false)
  1950. }
  1951. /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be
  1952. /// resumed or suspended.
  1953. ///
  1954. /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if
  1955. /// available.
  1956. ///
  1957. /// - Returns: The instance.
  1958. @discardableResult
  1959. public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self {
  1960. cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil)
  1961. }
  1962. /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed
  1963. /// or suspended.
  1964. ///
  1965. /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData`
  1966. /// property.
  1967. ///
  1968. /// - Parameter completionHandler: The completion handler that is called when the download has been successfully
  1969. /// cancelled. It is not guaranteed to be called on a particular queue, so you may
  1970. /// want use an appropriate queue to perform your work.
  1971. ///
  1972. /// - Returns: The instance.
  1973. @discardableResult
  1974. public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self {
  1975. cancel(optionallyProducingResumeData: completionHandler)
  1976. }
  1977. /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed,
  1978. /// cancellation is performed without producing resume data.
  1979. ///
  1980. /// - Parameter completionHandler: Optional resume data handler.
  1981. ///
  1982. /// - Returns: The instance.
  1983. private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self {
  1984. mutableState.write { mutableState in
  1985. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  1986. mutableState.state = .cancelled
  1987. underlyingQueue.async { self.didCancel() }
  1988. guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
  1989. underlyingQueue.async { self.finish() }
  1990. return
  1991. }
  1992. if let completionHandler = completionHandler {
  1993. // Resume to ensure metrics are gathered.
  1994. task.resume()
  1995. task.cancel { resumeData in
  1996. self.mutableDownloadState.resumeData = resumeData
  1997. self.underlyingQueue.async { self.didCancelTask(task) }
  1998. completionHandler(resumeData)
  1999. }
  2000. } else {
  2001. // Resume to ensure metrics are gathered.
  2002. task.resume()
  2003. task.cancel()
  2004. self.underlyingQueue.async { self.didCancelTask(task) }
  2005. }
  2006. }
  2007. return self
  2008. }
  2009. /// Validates the request, using the specified closure.
  2010. ///
  2011. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  2012. ///
  2013. /// - Parameter validation: `Validation` closure to validate the response.
  2014. ///
  2015. /// - Returns: The instance.
  2016. @discardableResult
  2017. public func validate(_ validation: @escaping Validation) -> Self {
  2018. let validator: () -> Void = { [unowned self] in
  2019. guard error == nil, let response = response else { return }
  2020. let result = validation(request, response, fileURL)
  2021. if case let .failure(error) = result {
  2022. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  2023. }
  2024. eventMonitor?.request(self,
  2025. didValidateRequest: request,
  2026. response: response,
  2027. fileURL: fileURL,
  2028. withResult: result)
  2029. }
  2030. validators.write { $0.append(validator) }
  2031. return self
  2032. }
  2033. }
  2034. // MARK: - UploadRequest
  2035. /// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`.
  2036. public class UploadRequest: DataRequest {
  2037. /// Type describing the origin of the upload, whether `Data`, file, or stream.
  2038. public enum Uploadable {
  2039. /// Upload from the provided `Data` value.
  2040. case data(Data)
  2041. /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be
  2042. /// automatically removed once uploaded.
  2043. case file(URL, shouldRemove: Bool)
  2044. /// Upload from the provided `InputStream`.
  2045. case stream(InputStream)
  2046. }
  2047. // MARK: Initial State
  2048. /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance.
  2049. public let upload: UploadableConvertible
  2050. /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written
  2051. /// to disk.
  2052. public let fileManager: FileManager
  2053. // MARK: Mutable State
  2054. /// `Uploadable` value used by the instance.
  2055. public var uploadable: Uploadable?
  2056. /// Creates an `UploadRequest` using the provided parameters.
  2057. ///
  2058. /// - Parameters:
  2059. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  2060. /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed.
  2061. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  2062. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  2063. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  2064. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  2065. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  2066. /// - fileManager: `FileManager` used to perform cleanup tasks, including the removal of multipart form
  2067. /// encoded payloads written to disk.
  2068. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  2069. init(id: UUID = UUID(),
  2070. convertible: UploadConvertible,
  2071. underlyingQueue: DispatchQueue,
  2072. serializationQueue: DispatchQueue,
  2073. eventMonitor: EventMonitor?,
  2074. interceptor: RequestInterceptor?,
  2075. fileManager: FileManager,
  2076. delegate: RequestDelegate) {
  2077. upload = convertible
  2078. self.fileManager = fileManager
  2079. super.init(id: id,
  2080. convertible: convertible,
  2081. underlyingQueue: underlyingQueue,
  2082. serializationQueue: serializationQueue,
  2083. eventMonitor: eventMonitor,
  2084. interceptor: interceptor,
  2085. delegate: delegate)
  2086. }
  2087. /// Called when the `Uploadable` value has been created from the `UploadConvertible`.
  2088. ///
  2089. /// - Parameter uploadable: The `Uploadable` that was created.
  2090. func didCreateUploadable(_ uploadable: Uploadable) {
  2091. self.uploadable = uploadable
  2092. eventMonitor?.request(self, didCreateUploadable: uploadable)
  2093. }
  2094. /// Called when the `Uploadable` value could not be created.
  2095. ///
  2096. /// - Parameter error: `AFError` produced by the failure.
  2097. func didFailToCreateUploadable(with error: AFError) {
  2098. self.error = error
  2099. eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
  2100. retryOrFinish(error: error)
  2101. }
  2102. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  2103. guard let uploadable = uploadable else {
  2104. fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
  2105. }
  2106. switch uploadable {
  2107. case let .data(data): return session.uploadTask(with: request, from: data)
  2108. case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
  2109. case .stream: return session.uploadTask(withStreamedRequest: request)
  2110. }
  2111. }
  2112. override func reset() {
  2113. // Uploadable must be recreated on every retry.
  2114. uploadable = nil
  2115. super.reset()
  2116. }
  2117. /// Produces the `InputStream` from `uploadable`, if it can.
  2118. ///
  2119. /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash.
  2120. ///
  2121. /// - Returns: The `InputStream`.
  2122. func inputStream() -> InputStream {
  2123. guard let uploadable = uploadable else {
  2124. fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
  2125. }
  2126. guard case let .stream(stream) = uploadable else {
  2127. fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
  2128. }
  2129. eventMonitor?.request(self, didProvideInputStream: stream)
  2130. return stream
  2131. }
  2132. override public func cleanup() {
  2133. defer { super.cleanup() }
  2134. guard
  2135. let uploadable = uploadable,
  2136. case let .file(url, shouldRemove) = uploadable,
  2137. shouldRemove
  2138. else { return }
  2139. try? fileManager.removeItem(at: url)
  2140. }
  2141. }
  2142. /// A type that can produce an `UploadRequest.Uploadable` value.
  2143. public protocol UploadableConvertible {
  2144. /// Produces an `UploadRequest.Uploadable` value from the instance.
  2145. ///
  2146. /// - Returns: The `UploadRequest.Uploadable`.
  2147. /// - Throws: Any `Error` produced during creation.
  2148. func createUploadable() throws -> UploadRequest.Uploadable
  2149. }
  2150. extension UploadRequest.Uploadable: UploadableConvertible {
  2151. public func createUploadable() throws -> UploadRequest.Uploadable {
  2152. self
  2153. }
  2154. }
  2155. /// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`.
  2156. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {}