Request.swift 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603
  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, let 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 { 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, 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 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 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) // Only Apple platforms support URLSessionWebSocketTask.
  1333. /// `Request` subclass which manages a WebSocket connection using `URLSessionWebSocketTask`.
  1334. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  1335. @_spi(WebSocket) 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. }
  1371. public struct Completion {
  1372. /// Last `URLRequest` issued by the instance.
  1373. public let request: URLRequest?
  1374. /// Last `HTTPURLResponse` received by the instance.
  1375. public let response: HTTPURLResponse?
  1376. /// Last `URLSessionTaskMetrics` produced for the instance.
  1377. public let metrics: URLSessionTaskMetrics?
  1378. /// `AFError` produced for the instance, if any.
  1379. public let error: AFError?
  1380. }
  1381. public struct Configuration {
  1382. public static var `default`: Self { Self() }
  1383. public static func `protocol`(_ protocol: String) -> Self {
  1384. Self(protocol: `protocol`)
  1385. }
  1386. public static func maximumMessageSize(_ maximumMessageSize: Int) -> Self {
  1387. Self(maximumMessageSize: maximumMessageSize)
  1388. }
  1389. public static func pingInterval(_ pingInterval: TimeInterval) -> Self {
  1390. Self(pingInterval: pingInterval)
  1391. }
  1392. public let `protocol`: String?
  1393. public let maximumMessageSize: Int
  1394. public let pingInterval: TimeInterval?
  1395. init(protocol: String? = nil, maximumMessageSize: Int = 1_048_576, pingInterval: TimeInterval? = nil) {
  1396. self.protocol = `protocol`
  1397. self.maximumMessageSize = maximumMessageSize
  1398. self.pingInterval = pingInterval
  1399. }
  1400. }
  1401. /// Response to a sent ping.
  1402. public enum PingResponse {
  1403. public struct Pong {
  1404. let start: Date
  1405. let end: Date
  1406. let latency: TimeInterval
  1407. }
  1408. /// Received a pong with the associated state.
  1409. case pong(Pong)
  1410. /// Received an error.
  1411. case error(Error)
  1412. /// Did not send the ping, the request is cancelled or suspended.
  1413. case unsent
  1414. }
  1415. struct SocketMutableState {
  1416. var enqueuedSends: [(message: URLSessionWebSocketTask.Message,
  1417. queue: DispatchQueue,
  1418. completionHandler: (Result<Void, Error>) -> Void)] = []
  1419. var handlers: [(queue: DispatchQueue, handler: (_ event: IncomingEvent) -> Void)] = []
  1420. var pingTimerItem: DispatchWorkItem?
  1421. }
  1422. let socketMutableState = Protected(SocketMutableState())
  1423. var socket: URLSessionWebSocketTask? {
  1424. task as? URLSessionWebSocketTask
  1425. }
  1426. public let convertible: URLRequestConvertible
  1427. public let configuration: Configuration
  1428. init(id: UUID = UUID(),
  1429. convertible: URLRequestConvertible,
  1430. configuration: Configuration,
  1431. underlyingQueue: DispatchQueue,
  1432. serializationQueue: DispatchQueue,
  1433. eventMonitor: EventMonitor?,
  1434. interceptor: RequestInterceptor?,
  1435. delegate: RequestDelegate) {
  1436. self.convertible = convertible
  1437. self.configuration = configuration
  1438. super.init(id: id,
  1439. underlyingQueue: underlyingQueue,
  1440. serializationQueue: serializationQueue,
  1441. eventMonitor: eventMonitor,
  1442. interceptor: interceptor,
  1443. delegate: delegate)
  1444. }
  1445. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1446. var copiedRequest = request
  1447. let task: URLSessionWebSocketTask
  1448. if let `protocol` = configuration.protocol {
  1449. copiedRequest.headers.update(.websocketProtocol(`protocol`))
  1450. task = session.webSocketTask(with: copiedRequest)
  1451. } else {
  1452. task = session.webSocketTask(with: copiedRequest)
  1453. }
  1454. task.maximumMessageSize = configuration.maximumMessageSize
  1455. return task
  1456. }
  1457. override func didCreateTask(_ task: URLSessionTask) {
  1458. super.didCreateTask(task)
  1459. guard let webSocketTask = task as? URLSessionWebSocketTask else {
  1460. fatalError("Invalid task of type \(task.self) created for WebSocketRequest.")
  1461. }
  1462. // TODO: What about the any old tasks? Reset their receive?
  1463. listen(to: webSocketTask)
  1464. // Empty pending messages.
  1465. socketMutableState.write { state in
  1466. guard !state.enqueuedSends.isEmpty else { return }
  1467. let sends = state.enqueuedSends
  1468. self.underlyingQueue.async {
  1469. for send in sends {
  1470. webSocketTask.send(send.message) { error in
  1471. send.queue.async {
  1472. send.completionHandler(Result(value: (), error: error))
  1473. }
  1474. }
  1475. }
  1476. }
  1477. state.enqueuedSends = []
  1478. }
  1479. }
  1480. func didClose() {
  1481. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  1482. mutableState.write { mutableState in
  1483. // Check whether error is cancellation or other websocket closing error.
  1484. // If so, remove it.
  1485. // Otherwise keep it.
  1486. if case let .sessionTaskFailed(error) = mutableState.error, (error as? URLError)?.code == .cancelled {
  1487. mutableState.error = nil
  1488. }
  1489. }
  1490. // TODO: Still issue this event?
  1491. eventMonitor?.requestDidCancel(self)
  1492. }
  1493. @discardableResult
  1494. public func close(sending closeCode: URLSessionWebSocketTask.CloseCode, reason: Data? = nil) -> Self {
  1495. cancelAutomaticPing()
  1496. mutableState.write { mutableState in
  1497. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  1498. mutableState.state = .cancelled
  1499. underlyingQueue.async { self.didClose() }
  1500. guard let task = mutableState.tasks.last, task.state != .completed else {
  1501. underlyingQueue.async { self.finish() }
  1502. return
  1503. }
  1504. // Resume to ensure metrics are gathered.
  1505. task.resume()
  1506. // Cast from state directly, not the property, otherwise the lock is recursive.
  1507. (mutableState.tasks.last as? URLSessionWebSocketTask)?.cancel(with: closeCode, reason: reason)
  1508. underlyingQueue.async { self.didCancelTask(task) }
  1509. }
  1510. return self
  1511. }
  1512. @discardableResult
  1513. override public func cancel() -> Self {
  1514. cancelAutomaticPing()
  1515. return super.cancel()
  1516. }
  1517. func didConnect(protocol: String?) {
  1518. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  1519. socketMutableState.read { state in
  1520. // TODO: Capture HTTPURLResponse here too?
  1521. for handler in state.handlers {
  1522. // Saved handler calls out to serializationQueue immediately, then to handler's queue.
  1523. handler.handler(.connected(protocol: `protocol`))
  1524. }
  1525. }
  1526. if let pingInterval = configuration.pingInterval {
  1527. startAutomaticPing(every: pingInterval)
  1528. }
  1529. }
  1530. public func sendPing(respondingOn queue: DispatchQueue = .main, onResponse: @escaping (PingResponse) -> Void) {
  1531. guard isResumed else {
  1532. queue.async { onResponse(.unsent) }
  1533. return
  1534. }
  1535. let start = Date()
  1536. let startTimestamp = ProcessInfo.processInfo.systemUptime
  1537. socket?.sendPing { error in
  1538. // Calls back on delegate queue / rootQueue / underlyingQueue
  1539. if let error {
  1540. queue.async {
  1541. onResponse(.error(error))
  1542. }
  1543. // TODO: What to do with failed ping? Configure for failure, auto retry, or stop pinging?
  1544. } else {
  1545. let end = Date()
  1546. let endTimestamp = ProcessInfo.processInfo.systemUptime
  1547. let pong = PingResponse.Pong(start: start, end: end, latency: endTimestamp - startTimestamp)
  1548. queue.async {
  1549. onResponse(.pong(pong))
  1550. }
  1551. }
  1552. }
  1553. }
  1554. func startAutomaticPing(every pingInterval: TimeInterval) {
  1555. socketMutableState.write { mutableState in
  1556. guard isResumed else {
  1557. // Defer out of lock.
  1558. defer { cancelAutomaticPing() }
  1559. return
  1560. }
  1561. let item = DispatchWorkItem { [weak self] in
  1562. guard let self, self.isResumed else { return }
  1563. self.sendPing(respondingOn: self.underlyingQueue) { response in
  1564. guard case .pong = response else { return }
  1565. self.startAutomaticPing(every: pingInterval)
  1566. }
  1567. }
  1568. mutableState.pingTimerItem = item
  1569. underlyingQueue.asyncAfter(deadline: .now() + pingInterval, execute: item)
  1570. }
  1571. }
  1572. #if swift(>=5.8)
  1573. @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
  1574. func startAutomaticPing(every duration: Duration) {
  1575. let interval = TimeInterval(duration.components.seconds) + (Double(duration.components.attoseconds) / 1e18)
  1576. startAutomaticPing(every: interval)
  1577. }
  1578. #endif
  1579. func cancelAutomaticPing() {
  1580. socketMutableState.write { mutableState in
  1581. mutableState.pingTimerItem?.cancel()
  1582. mutableState.pingTimerItem = nil
  1583. }
  1584. }
  1585. func didDisconnect(closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
  1586. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  1587. cancelAutomaticPing()
  1588. socketMutableState.read { state in
  1589. for handler in state.handlers {
  1590. // Saved handler calls out to serializationQueue immediately, then to handler's queue.
  1591. handler.handler(.disconnected(closeCode: closeCode, reason: reason))
  1592. }
  1593. }
  1594. }
  1595. private func listen(to task: URLSessionWebSocketTask) {
  1596. // TODO: Do we care about the cycle while receiving?
  1597. task.receive { result in
  1598. switch result {
  1599. case let .success(message):
  1600. self.socketMutableState.read { state in
  1601. for handler in state.handlers {
  1602. // Saved handler calls out to serializationQueue immediately, then to handler's queue.
  1603. handler.handler(.receivedMessage(message))
  1604. }
  1605. }
  1606. self.listen(to: task)
  1607. case .failure:
  1608. // It doesn't seem like any relevant errors are received here, just incorrect garbage, like errors when
  1609. // the socket disconnects.
  1610. break
  1611. }
  1612. }
  1613. }
  1614. @discardableResult
  1615. public func streamSerializer<Serializer>(
  1616. _ serializer: Serializer,
  1617. on queue: DispatchQueue = .main,
  1618. handler: @escaping (_ event: Event<Serializer.Output, Serializer.Failure>) -> Void
  1619. ) -> Self where Serializer: WebSocketMessageSerializer, Serializer.Failure == Error {
  1620. forIncomingEvent(on: queue) { incomingEvent in
  1621. let event: Event<Serializer.Output, Serializer.Failure>
  1622. switch incomingEvent {
  1623. case let .connected(`protocol`):
  1624. event = .init(socket: self, kind: .connected(protocol: `protocol`))
  1625. case let .receivedMessage(message):
  1626. do {
  1627. let serializedMessage = try serializer.decode(message)
  1628. event = .init(socket: self, kind: .receivedMessage(serializedMessage))
  1629. } catch {
  1630. event = .init(socket: self, kind: .serializerFailed(error))
  1631. }
  1632. case let .disconnected(closeCode, reason):
  1633. event = .init(socket: self, kind: .disconnected(closeCode: closeCode, reason: reason))
  1634. case let .completed(completion):
  1635. event = .init(socket: self, kind: .completed(completion))
  1636. }
  1637. queue.async { handler(event) }
  1638. }
  1639. }
  1640. @discardableResult
  1641. public func streamDecodableEvents<Value>(
  1642. _ type: Value.Type = Value.self,
  1643. on queue: DispatchQueue = .main,
  1644. using decoder: DataDecoder = JSONDecoder(),
  1645. handler: @escaping (_ event: Event<Value, Error>) -> Void
  1646. ) -> Self where Value: Decodable {
  1647. streamSerializer(DecodableWebSocketMessageDecoder<Value>(decoder: decoder), on: queue, handler: handler)
  1648. }
  1649. @discardableResult
  1650. public func streamDecodable<Value>(
  1651. _ type: Value.Type = Value.self,
  1652. on queue: DispatchQueue = .main,
  1653. using decoder: DataDecoder = JSONDecoder(),
  1654. handler: @escaping (_ value: Value) -> Void
  1655. ) -> Self where Value: Decodable {
  1656. streamDecodableEvents(Value.self, on: queue) { event in
  1657. event.message.map(handler)
  1658. }
  1659. }
  1660. @discardableResult
  1661. public func streamMessageEvents(
  1662. on queue: DispatchQueue = .main,
  1663. handler: @escaping (_ event: Event<URLSessionWebSocketTask.Message, Never>) -> Void
  1664. ) -> Self {
  1665. forIncomingEvent(on: queue) { incomingEvent in
  1666. let event: Event<URLSessionWebSocketTask.Message, Never>
  1667. switch incomingEvent {
  1668. case let .connected(`protocol`):
  1669. event = .init(socket: self, kind: .connected(protocol: `protocol`))
  1670. case let .receivedMessage(message):
  1671. event = .init(socket: self, kind: .receivedMessage(message))
  1672. case let .disconnected(closeCode, reason):
  1673. event = .init(socket: self, kind: .disconnected(closeCode: closeCode, reason: reason))
  1674. case let .completed(completion):
  1675. event = .init(socket: self, kind: .completed(completion))
  1676. }
  1677. queue.async { handler(event) }
  1678. }
  1679. }
  1680. @discardableResult
  1681. public func streamMessages(
  1682. on queue: DispatchQueue = .main,
  1683. handler: @escaping (_ message: URLSessionWebSocketTask.Message) -> Void
  1684. ) -> Self {
  1685. streamMessageEvents(on: queue) { event in
  1686. event.message.map(handler)
  1687. }
  1688. }
  1689. func forIncomingEvent(on queue: DispatchQueue, handler: @escaping (IncomingEvent) -> Void) -> Self {
  1690. socketMutableState.write { state in
  1691. state.handlers.append((queue: queue, handler: { incomingEvent in
  1692. self.serializationQueue.async {
  1693. handler(incomingEvent)
  1694. }
  1695. }))
  1696. }
  1697. appendResponseSerializer {
  1698. self.responseSerializerDidComplete {
  1699. self.serializationQueue.async {
  1700. handler(.completed(.init(request: self.request,
  1701. response: self.response,
  1702. metrics: self.metrics,
  1703. error: self.error)))
  1704. }
  1705. }
  1706. }
  1707. return self
  1708. }
  1709. public func send(_ message: URLSessionWebSocketTask.Message,
  1710. queue: DispatchQueue = .main,
  1711. completionHandler: @escaping (Result<Void, Error>) -> Void) {
  1712. guard !(isCancelled || isFinished) else { return }
  1713. guard let socket else {
  1714. // URLSessionWebSocketTask note created yet, enqueue the send.
  1715. socketMutableState.write { mutableState in
  1716. mutableState.enqueuedSends.append((message, queue, completionHandler))
  1717. }
  1718. return
  1719. }
  1720. socket.send(message) { error in
  1721. queue.async {
  1722. completionHandler(Result(value: (), error: error))
  1723. }
  1724. }
  1725. }
  1726. }
  1727. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  1728. public protocol WebSocketMessageSerializer<Output, Failure> {
  1729. associatedtype Output
  1730. associatedtype Failure: Error = Error
  1731. func decode(_ message: URLSessionWebSocketTask.Message) throws -> Output
  1732. }
  1733. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  1734. extension WebSocketMessageSerializer {
  1735. public static func json<Value>(
  1736. decoding _: Value.Type = Value.self,
  1737. using decoder: JSONDecoder = JSONDecoder()
  1738. ) -> DecodableWebSocketMessageDecoder<Value> where Self == DecodableWebSocketMessageDecoder<Value> {
  1739. Self(decoder: decoder)
  1740. }
  1741. static var passthrough: PassthroughWebSocketMessageDecoder {
  1742. PassthroughWebSocketMessageDecoder()
  1743. }
  1744. }
  1745. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  1746. struct PassthroughWebSocketMessageDecoder: WebSocketMessageSerializer {
  1747. public typealias Failure = Never
  1748. public func decode(_ message: URLSessionWebSocketTask.Message) -> URLSessionWebSocketTask.Message {
  1749. message
  1750. }
  1751. }
  1752. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  1753. public struct DecodableWebSocketMessageDecoder<Value: Decodable>: WebSocketMessageSerializer {
  1754. public enum Error: Swift.Error {
  1755. case decoding(Swift.Error)
  1756. case unknownMessage(description: String)
  1757. }
  1758. public let decoder: DataDecoder
  1759. public init(decoder: DataDecoder) {
  1760. self.decoder = decoder
  1761. }
  1762. public func decode(_ message: URLSessionWebSocketTask.Message) throws -> Value {
  1763. let data: Data
  1764. switch message {
  1765. case let .data(messageData):
  1766. data = messageData
  1767. case let .string(string):
  1768. data = Data(string.utf8)
  1769. @unknown default:
  1770. throw Error.unknownMessage(description: String(describing: message))
  1771. }
  1772. do {
  1773. return try decoder.decode(Value.self, from: data)
  1774. } catch {
  1775. throw Error.decoding(error)
  1776. }
  1777. }
  1778. }
  1779. #endif
  1780. // MARK: - DownloadRequest
  1781. /// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`.
  1782. public class DownloadRequest: Request {
  1783. /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination
  1784. /// `URL`.
  1785. public struct Options: OptionSet {
  1786. /// Specifies that intermediate directories for the destination URL should be created.
  1787. public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
  1788. /// Specifies that any previous file at the destination `URL` should be removed.
  1789. public static let removePreviousFile = Options(rawValue: 1 << 1)
  1790. public let rawValue: Int
  1791. public init(rawValue: Int) {
  1792. self.rawValue = rawValue
  1793. }
  1794. }
  1795. // MARK: Destination
  1796. /// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the
  1797. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  1798. /// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and
  1799. /// the options defining how the file should be moved.
  1800. ///
  1801. /// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not
  1802. /// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory.
  1803. public typealias Destination = (_ temporaryURL: URL,
  1804. _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
  1805. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  1806. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  1807. ///
  1808. /// - Parameters:
  1809. /// - directory: The search path directory. `.documentDirectory` by default.
  1810. /// - domain: The search path domain mask. `.userDomainMask` by default.
  1811. /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by
  1812. /// default.
  1813. /// - Returns: The `Destination` closure.
  1814. public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
  1815. in domain: FileManager.SearchPathDomainMask = .userDomainMask,
  1816. options: Options = []) -> Destination {
  1817. { temporaryURL, response in
  1818. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  1819. let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
  1820. return (url, options)
  1821. }
  1822. }
  1823. /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends
  1824. /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files
  1825. /// with this destination must be additionally moved if they should survive the system reclamation of temporary
  1826. /// space.
  1827. static let defaultDestination: Destination = { url, _ in
  1828. (defaultDestinationURL(url), [])
  1829. }
  1830. /// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the
  1831. /// provided file name.
  1832. static let defaultDestinationURL: (URL) -> URL = { url in
  1833. let filename = "Alamofire_\(url.lastPathComponent)"
  1834. let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
  1835. return destination
  1836. }
  1837. // MARK: Downloadable
  1838. /// Type describing the source used to create the underlying `URLSessionDownloadTask`.
  1839. public enum Downloadable {
  1840. /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value.
  1841. case request(URLRequestConvertible)
  1842. /// Download should be started from the associated resume `Data` value.
  1843. case resumeData(Data)
  1844. }
  1845. // MARK: Mutable State
  1846. /// Type containing all mutable state for `DownloadRequest` instances.
  1847. private struct DownloadRequestMutableState {
  1848. /// Possible resume `Data` produced when cancelling the instance.
  1849. var resumeData: Data?
  1850. /// `URL` to which `Data` is being downloaded.
  1851. var fileURL: URL?
  1852. }
  1853. /// Protected mutable state specific to `DownloadRequest`.
  1854. private let mutableDownloadState = Protected(DownloadRequestMutableState())
  1855. /// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download
  1856. /// using the `download(resumingWith data:)` API.
  1857. ///
  1858. /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel).
  1859. public var resumeData: Data? {
  1860. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  1861. return mutableDownloadState.resumeData ?? error?.downloadResumeData
  1862. #else
  1863. return mutableDownloadState.resumeData
  1864. #endif
  1865. }
  1866. /// If the download is successful, the `URL` where the file was downloaded.
  1867. public var fileURL: URL? { mutableDownloadState.fileURL }
  1868. // MARK: Initial State
  1869. /// `Downloadable` value used for this instance.
  1870. public let downloadable: Downloadable
  1871. /// The `Destination` to which the downloaded file is moved.
  1872. let destination: Destination
  1873. /// Creates a `DownloadRequest` using the provided parameters.
  1874. ///
  1875. /// - Parameters:
  1876. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  1877. /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance.
  1878. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1879. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  1880. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1881. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1882. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1883. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`
  1884. /// - destination: `Destination` closure used to move the downloaded file to its final location.
  1885. init(id: UUID = UUID(),
  1886. downloadable: Downloadable,
  1887. underlyingQueue: DispatchQueue,
  1888. serializationQueue: DispatchQueue,
  1889. eventMonitor: EventMonitor?,
  1890. interceptor: RequestInterceptor?,
  1891. delegate: RequestDelegate,
  1892. destination: @escaping Destination) {
  1893. self.downloadable = downloadable
  1894. self.destination = destination
  1895. super.init(id: id,
  1896. underlyingQueue: underlyingQueue,
  1897. serializationQueue: serializationQueue,
  1898. eventMonitor: eventMonitor,
  1899. interceptor: interceptor,
  1900. delegate: delegate)
  1901. }
  1902. override func reset() {
  1903. super.reset()
  1904. mutableDownloadState.write {
  1905. $0.resumeData = nil
  1906. $0.fileURL = nil
  1907. }
  1908. }
  1909. /// Called when a download has finished.
  1910. ///
  1911. /// - Parameters:
  1912. /// - task: `URLSessionTask` that finished the download.
  1913. /// - result: `Result` of the automatic move to `destination`.
  1914. func didFinishDownloading(using task: URLSessionTask, with result: Result<URL, AFError>) {
  1915. eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
  1916. switch result {
  1917. case let .success(url): mutableDownloadState.fileURL = url
  1918. case let .failure(error): self.error = error
  1919. }
  1920. }
  1921. /// Updates the `downloadProgress` using the provided values.
  1922. ///
  1923. /// - Parameters:
  1924. /// - bytesWritten: Total bytes written so far.
  1925. /// - totalBytesExpectedToWrite: Total bytes expected to write.
  1926. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  1927. downloadProgress.totalUnitCount = totalBytesExpectedToWrite
  1928. downloadProgress.completedUnitCount += bytesWritten
  1929. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  1930. }
  1931. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1932. session.downloadTask(with: request)
  1933. }
  1934. /// Creates a `URLSessionTask` from the provided resume data.
  1935. ///
  1936. /// - Parameters:
  1937. /// - data: `Data` used to resume the download.
  1938. /// - session: `URLSession` used to create the `URLSessionTask`.
  1939. ///
  1940. /// - Returns: The `URLSessionTask` created.
  1941. public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
  1942. session.downloadTask(withResumeData: data)
  1943. }
  1944. /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended.
  1945. ///
  1946. /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use
  1947. /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`.
  1948. ///
  1949. /// - Returns: The instance.
  1950. @discardableResult
  1951. override public func cancel() -> Self {
  1952. cancel(producingResumeData: false)
  1953. }
  1954. /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be
  1955. /// resumed or suspended.
  1956. ///
  1957. /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if
  1958. /// available.
  1959. ///
  1960. /// - Returns: The instance.
  1961. @discardableResult
  1962. public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self {
  1963. cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil)
  1964. }
  1965. /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed
  1966. /// or suspended.
  1967. ///
  1968. /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData`
  1969. /// property.
  1970. ///
  1971. /// - Parameter completionHandler: The completion handler that is called when the download has been successfully
  1972. /// cancelled. It is not guaranteed to be called on a particular queue, so you may
  1973. /// want use an appropriate queue to perform your work.
  1974. ///
  1975. /// - Returns: The instance.
  1976. @discardableResult
  1977. public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self {
  1978. cancel(optionallyProducingResumeData: completionHandler)
  1979. }
  1980. /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed,
  1981. /// cancellation is performed without producing resume data.
  1982. ///
  1983. /// - Parameter completionHandler: Optional resume data handler.
  1984. ///
  1985. /// - Returns: The instance.
  1986. private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self {
  1987. mutableState.write { mutableState in
  1988. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  1989. mutableState.state = .cancelled
  1990. underlyingQueue.async { self.didCancel() }
  1991. guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
  1992. underlyingQueue.async { self.finish() }
  1993. return
  1994. }
  1995. if let completionHandler {
  1996. // Resume to ensure metrics are gathered.
  1997. task.resume()
  1998. task.cancel { resumeData in
  1999. self.mutableDownloadState.resumeData = resumeData
  2000. self.underlyingQueue.async { self.didCancelTask(task) }
  2001. completionHandler(resumeData)
  2002. }
  2003. } else {
  2004. // Resume to ensure metrics are gathered.
  2005. task.resume()
  2006. task.cancel()
  2007. self.underlyingQueue.async { self.didCancelTask(task) }
  2008. }
  2009. }
  2010. return self
  2011. }
  2012. /// Validates the request, using the specified closure.
  2013. ///
  2014. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  2015. ///
  2016. /// - Parameter validation: `Validation` closure to validate the response.
  2017. ///
  2018. /// - Returns: The instance.
  2019. @discardableResult
  2020. public func validate(_ validation: @escaping Validation) -> Self {
  2021. let validator: () -> Void = { [unowned self] in
  2022. guard error == nil, let response else { return }
  2023. let result = validation(request, response, fileURL)
  2024. if case let .failure(error) = result {
  2025. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  2026. }
  2027. eventMonitor?.request(self,
  2028. didValidateRequest: request,
  2029. response: response,
  2030. fileURL: fileURL,
  2031. withResult: result)
  2032. }
  2033. validators.write { $0.append(validator) }
  2034. return self
  2035. }
  2036. }
  2037. // MARK: - UploadRequest
  2038. /// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`.
  2039. public class UploadRequest: DataRequest {
  2040. /// Type describing the origin of the upload, whether `Data`, file, or stream.
  2041. public enum Uploadable {
  2042. /// Upload from the provided `Data` value.
  2043. case data(Data)
  2044. /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be
  2045. /// automatically removed once uploaded.
  2046. case file(URL, shouldRemove: Bool)
  2047. /// Upload from the provided `InputStream`.
  2048. case stream(InputStream)
  2049. }
  2050. // MARK: Initial State
  2051. /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance.
  2052. public let upload: UploadableConvertible
  2053. /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written
  2054. /// to disk.
  2055. public let fileManager: FileManager
  2056. // MARK: Mutable State
  2057. /// `Uploadable` value used by the instance.
  2058. public var uploadable: Uploadable?
  2059. /// Creates an `UploadRequest` using the provided parameters.
  2060. ///
  2061. /// - Parameters:
  2062. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  2063. /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed.
  2064. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  2065. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  2066. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  2067. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  2068. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  2069. /// - fileManager: `FileManager` used to perform cleanup tasks, including the removal of multipart form
  2070. /// encoded payloads written to disk.
  2071. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  2072. init(id: UUID = UUID(),
  2073. convertible: UploadConvertible,
  2074. underlyingQueue: DispatchQueue,
  2075. serializationQueue: DispatchQueue,
  2076. eventMonitor: EventMonitor?,
  2077. interceptor: RequestInterceptor?,
  2078. fileManager: FileManager,
  2079. delegate: RequestDelegate) {
  2080. upload = convertible
  2081. self.fileManager = fileManager
  2082. super.init(id: id,
  2083. convertible: convertible,
  2084. underlyingQueue: underlyingQueue,
  2085. serializationQueue: serializationQueue,
  2086. eventMonitor: eventMonitor,
  2087. interceptor: interceptor,
  2088. delegate: delegate)
  2089. }
  2090. /// Called when the `Uploadable` value has been created from the `UploadConvertible`.
  2091. ///
  2092. /// - Parameter uploadable: The `Uploadable` that was created.
  2093. func didCreateUploadable(_ uploadable: Uploadable) {
  2094. self.uploadable = uploadable
  2095. eventMonitor?.request(self, didCreateUploadable: uploadable)
  2096. }
  2097. /// Called when the `Uploadable` value could not be created.
  2098. ///
  2099. /// - Parameter error: `AFError` produced by the failure.
  2100. func didFailToCreateUploadable(with error: AFError) {
  2101. self.error = error
  2102. eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
  2103. retryOrFinish(error: error)
  2104. }
  2105. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  2106. guard let uploadable else {
  2107. fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
  2108. }
  2109. switch uploadable {
  2110. case let .data(data): return session.uploadTask(with: request, from: data)
  2111. case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
  2112. case .stream: return session.uploadTask(withStreamedRequest: request)
  2113. }
  2114. }
  2115. override func reset() {
  2116. // Uploadable must be recreated on every retry.
  2117. uploadable = nil
  2118. super.reset()
  2119. }
  2120. /// Produces the `InputStream` from `uploadable`, if it can.
  2121. ///
  2122. /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash.
  2123. ///
  2124. /// - Returns: The `InputStream`.
  2125. func inputStream() -> InputStream {
  2126. guard let uploadable else {
  2127. fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
  2128. }
  2129. guard case let .stream(stream) = uploadable else {
  2130. fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
  2131. }
  2132. eventMonitor?.request(self, didProvideInputStream: stream)
  2133. return stream
  2134. }
  2135. override public func cleanup() {
  2136. defer { super.cleanup() }
  2137. guard
  2138. let uploadable,
  2139. case let .file(url, shouldRemove) = uploadable,
  2140. shouldRemove
  2141. else { return }
  2142. try? fileManager.removeItem(at: url)
  2143. }
  2144. }
  2145. /// A type that can produce an `UploadRequest.Uploadable` value.
  2146. public protocol UploadableConvertible {
  2147. /// Produces an `UploadRequest.Uploadable` value from the instance.
  2148. ///
  2149. /// - Returns: The `UploadRequest.Uploadable`.
  2150. /// - Throws: Any `Error` produced during creation.
  2151. func createUploadable() throws -> UploadRequest.Uploadable
  2152. }
  2153. extension UploadRequest.Uploadable: UploadableConvertible {
  2154. public func createUploadable() throws -> UploadRequest.Uploadable {
  2155. self
  2156. }
  2157. }
  2158. /// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`.
  2159. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {}