Request.swift 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  1. //
  2. // Request.swift
  3. //
  4. // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback
  26. /// handling.
  27. public class Request {
  28. /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or
  29. /// `cancel()` on the `Request`.
  30. ///
  31. /// - initialized: Initial state of the `Request`.
  32. /// - resumed: Set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on
  33. /// them in this state.
  34. /// - suspended: Set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on
  35. /// them in this state.
  36. /// - cancelled: Set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on
  37. /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer
  38. /// transition to any other state.
  39. /// - finished: Set when all response serialization completion closures have been cleared on the `Request` and
  40. /// queued on their respective queues.
  41. public enum State {
  42. case initialized, resumed, suspended, cancelled, finished
  43. /// Determines whether `self` can be transitioned to `state`.
  44. func canTransitionTo(_ state: State) -> Bool {
  45. switch (self, state) {
  46. case (.initialized, _):
  47. return true
  48. case (_, .initialized), (.cancelled, _), (.finished, _):
  49. return false
  50. case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed):
  51. return true
  52. case (.suspended, .suspended), (.resumed, .resumed):
  53. return false
  54. case (_, .finished):
  55. return true
  56. }
  57. }
  58. }
  59. // MARK: - Initial State
  60. /// `UUID` prividing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances.
  61. public let id: UUID
  62. /// The serial queue for all internal async actions.
  63. public let underlyingQueue: DispatchQueue
  64. /// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`.
  65. public let serializationQueue: DispatchQueue
  66. /// `EventMonitor` used for event callbacks.
  67. public let eventMonitor: EventMonitor?
  68. /// The `Request`'s interceptor.
  69. public let interceptor: RequestInterceptor?
  70. /// The `Request`'s delegate.
  71. public private(set) weak var delegate: RequestDelegate?
  72. // MARK: - Updated State
  73. /// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`.
  74. struct MutableState {
  75. /// State of the `Request`.
  76. var state: State = .initialized
  77. /// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks.
  78. var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
  79. /// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks.
  80. var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
  81. /// `RetryHandler` provided for redirect responses.
  82. var redirectHandler: RedirectHandler?
  83. /// `CachedResponseHandler` provided to handle caching responses.
  84. var cachedResponseHandler: CachedResponseHandler?
  85. /// Response serialization closures that handle parsing responses.
  86. var responseSerializers: [() -> Void] = []
  87. /// Response serialization completion closures executed once all response serialization is complete.
  88. var responseSerializerCompletions: [() -> Void] = []
  89. /// Whether response serializer processing is finished.
  90. var responseSerializerProcessingFinished = false
  91. /// `URLCredential` used for authentication challenges.
  92. var credential: URLCredential?
  93. /// All `URLRequest`s created by Alamofire on behalf of the `Request`.
  94. var requests: [URLRequest] = []
  95. /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`.
  96. var tasks: [URLSessionTask] = []
  97. /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond
  98. /// exactly the the `tasks` created.
  99. var metrics: [URLSessionTaskMetrics] = []
  100. /// Number of times any retriers provided retried the `Request`.
  101. var retryCount = 0
  102. /// Final `Error` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`.
  103. var error: Error?
  104. }
  105. /// Protected `MutableState` value that provides threadsafe access to state values.
  106. fileprivate let protectedMutableState: Protector<MutableState> = Protector(MutableState())
  107. /// `State` of the `Request`.
  108. public var state: State { return protectedMutableState.directValue.state }
  109. /// Returns whether `state` is `.initialized`.
  110. public var isInitialized: Bool { return state == .initialized }
  111. /// Returns whether `state is `.resumed`.
  112. public var isResumed: Bool { return state == .resumed }
  113. /// Returns whether `state` is `.suspended`.
  114. public var isSuspended: Bool { return state == .suspended }
  115. /// Returns whether `state` is `.cancelled`.
  116. public var isCancelled: Bool { return state == .cancelled }
  117. /// Returns whether `state` is `.finished`.
  118. public var isFinished: Bool { return state == .finished }
  119. // Progress
  120. /// Closure type executed when monitoring the upload or download progress of a request.
  121. public typealias ProgressHandler = (Progress) -> Void
  122. /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried.
  123. public let uploadProgress = Progress(totalUnitCount: 0)
  124. /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried.
  125. public let downloadProgress = Progress(totalUnitCount: 0)
  126. /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`.
  127. fileprivate var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
  128. get { return protectedMutableState.directValue.uploadProgressHandler }
  129. set { protectedMutableState.write { $0.uploadProgressHandler = newValue } }
  130. }
  131. /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`.
  132. fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
  133. get { return protectedMutableState.directValue.downloadProgressHandler }
  134. set { protectedMutableState.write { $0.downloadProgressHandler = newValue } }
  135. }
  136. // Redirects
  137. public private(set) var redirectHandler: RedirectHandler? {
  138. get { return protectedMutableState.directValue.redirectHandler }
  139. set { protectedMutableState.write { $0.redirectHandler = newValue } }
  140. }
  141. // Cached Responses
  142. public private(set) var cachedResponseHandler: CachedResponseHandler? {
  143. get { return protectedMutableState.directValue.cachedResponseHandler }
  144. set { protectedMutableState.write { $0.cachedResponseHandler = newValue } }
  145. }
  146. // Credential
  147. /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods.
  148. public private(set) var credential: URLCredential? {
  149. get { return protectedMutableState.directValue.credential }
  150. set { protectedMutableState.write { $0.credential = newValue } }
  151. }
  152. // Validators
  153. /// `Validator` callback closures that store the validation calls enqueued.
  154. fileprivate var protectedValidators: Protector<[() -> Void]> = Protector([])
  155. // Requests
  156. /// All `URLRequests` created on behalf of the `Request`, including original and adapted requests.
  157. public var requests: [URLRequest] { return protectedMutableState.directValue.requests }
  158. /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed.
  159. public var firstRequest: URLRequest? { return requests.first }
  160. /// Last `URLRequest` created on behalf of the `Request`.
  161. public var lastRequest: URLRequest? { return requests.last }
  162. /// Current `URLRequest` created on behalf of the `Request`.
  163. public var request: URLRequest? { return lastRequest }
  164. /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`.
  165. public var performedRequests: [URLRequest] {
  166. return protectedMutableState.read { $0.tasks.compactMap { $0.currentRequest } }
  167. }
  168. // Response
  169. /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the
  170. /// last `URLSessionTask`.
  171. public var response: HTTPURLResponse? { return lastTask?.response as? HTTPURLResponse }
  172. // Tasks
  173. /// All `URLSessionTask`s created on behalf of the `Request`.
  174. public var tasks: [URLSessionTask] { return protectedMutableState.directValue.tasks }
  175. /// First `URLSessionTask` created on behalf of the `Request`.
  176. public var firstTask: URLSessionTask? { return tasks.first }
  177. /// Last `URLSessionTask` crated on behalf of the `Request`.
  178. public var lastTask: URLSessionTask? { return tasks.last }
  179. /// Current `URLSessionTask` created on behalf of the `Request`.
  180. public var task: URLSessionTask? { return lastTask }
  181. // Metrics
  182. /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created.
  183. public var allMetrics: [URLSessionTaskMetrics] { return protectedMutableState.directValue.metrics }
  184. /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  185. public var firstMetrics: URLSessionTaskMetrics? { return allMetrics.first }
  186. /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  187. public var lastMetrics: URLSessionTaskMetrics? { return allMetrics.last }
  188. /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  189. public var metrics: URLSessionTaskMetrics? { return lastMetrics }
  190. /// Number of times the `Request` has been retried.
  191. public var retryCount: Int { return protectedMutableState.directValue.retryCount }
  192. /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed.
  193. fileprivate(set) public var error: Error? {
  194. get { return protectedMutableState.directValue.error }
  195. set { protectedMutableState.write { $0.error = newValue } }
  196. }
  197. /// Default initializer for the `Request` superclass.
  198. ///
  199. /// - Parameters:
  200. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. Defaults to a random `UUID`.
  201. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  202. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. Targets the
  203. /// `underlyingQueue` when created by a `SessionManager`.
  204. /// - eventMonitor: `EventMonitor` used for event callbacks from internal `Request` actions.
  205. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  206. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  207. public init(id: UUID = UUID(),
  208. underlyingQueue: DispatchQueue,
  209. serializationQueue: DispatchQueue,
  210. eventMonitor: EventMonitor?,
  211. interceptor: RequestInterceptor?,
  212. delegate: RequestDelegate) {
  213. self.id = id
  214. self.underlyingQueue = underlyingQueue
  215. self.serializationQueue = serializationQueue
  216. self.eventMonitor = eventMonitor
  217. self.interceptor = interceptor
  218. self.delegate = delegate
  219. }
  220. // MARK: - Internal API
  221. // Called from underlyingQueue.
  222. /// Called when a `URLRequest` has been created on behalf of the `Request`.
  223. ///
  224. /// - Parameter request: `URLRequest` created.
  225. func didCreateURLRequest(_ request: URLRequest) {
  226. protectedMutableState.write { $0.requests.append(request) }
  227. eventMonitor?.request(self, didCreateURLRequest: request)
  228. }
  229. /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`. Triggers retry.
  230. ///
  231. /// - Parameter error: `Error` thrown from the failed creation.
  232. func didFailToCreateURLRequest(with error: Error) {
  233. self.error = error
  234. eventMonitor?.request(self, didFailToCreateURLRequestWithError: error)
  235. retryOrFinish(error: error)
  236. }
  237. /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`.
  238. ///
  239. /// - Parameters:
  240. /// - initialRequest: The `URLRequest` that was adapted.
  241. /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`.
  242. func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) {
  243. protectedMutableState.write { $0.requests.append(adaptedRequest) }
  244. eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest)
  245. }
  246. /// Called when a `RequestAdapter` fails to adapt a `URLRequest`. Triggers retry.
  247. ///
  248. /// - Parameters:
  249. /// - request: The `URLRequest` the adapter was called with.
  250. /// - error: The `Error` returned by the `RequestAdapter`.
  251. func didFailToAdaptURLRequest(_ request: URLRequest, withError error: Error) {
  252. self.error = error
  253. eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error)
  254. retryOrFinish(error: error)
  255. }
  256. /// Called when a `URLSessionTask` is created on behalf of the `Request`.
  257. ///
  258. /// - Parameter task: The `URLSessionTask` created.
  259. func didCreateTask(_ task: URLSessionTask) {
  260. protectedMutableState.write { $0.tasks.append(task) }
  261. eventMonitor?.request(self, didCreateTask: task)
  262. }
  263. /// Called when resumption is completed.
  264. func didResume() {
  265. eventMonitor?.requestDidResume(self)
  266. }
  267. /// Called when a `URLSessionTask` is resumed on behalf of the instance.
  268. func didResumeTask(_ task: URLSessionTask) {
  269. eventMonitor?.request(self, didResumeTask: task)
  270. }
  271. /// Called when suspension is completed.
  272. func didSuspend() {
  273. eventMonitor?.requestDidSuspend(self)
  274. }
  275. /// Callend when a `URLSessionTask` is suspended on behalf of the instance.
  276. func didSuspendTask(_ task: URLSessionTask) {
  277. eventMonitor?.request(self, didSuspendTask: task)
  278. }
  279. /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`.
  280. func didCancel() {
  281. error = AFError.explicitlyCancelled
  282. eventMonitor?.requestDidCancel(self)
  283. }
  284. /// Called when a `URLSessionTask` is cancelled on behalf of the instance.
  285. func didCancelTask(_ task: URLSessionTask) {
  286. eventMonitor?.request(self, didCancelTask: task)
  287. }
  288. /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the `Request`.
  289. func didGatherMetrics(_ metrics: URLSessionTaskMetrics) {
  290. protectedMutableState.write { $0.metrics.append(metrics) }
  291. eventMonitor?.request(self, didGatherMetrics: metrics)
  292. }
  293. /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning.
  294. func didFailTask(_ task: URLSessionTask, earlyWithError error: Error) {
  295. self.error = error
  296. // Task will still complete, so didCompleteTask(_:with:) will handle retry.
  297. eventMonitor?.request(self, didFailTask: task, earlyWithError: error)
  298. }
  299. /// Called when a `URLSessionTask` completes. All tasks will eventually call this method.
  300. func didCompleteTask(_ task: URLSessionTask, with error: Error?) {
  301. self.error = self.error ?? error
  302. protectedValidators.directValue.forEach { $0() }
  303. eventMonitor?.request(self, didCompleteTask: task, with: error)
  304. retryOrFinish(error: self.error)
  305. }
  306. /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`.
  307. func prepareForRetry() {
  308. protectedMutableState.write { $0.retryCount += 1 }
  309. reset()
  310. eventMonitor?.requestIsRetrying(self)
  311. }
  312. /// Called to trigger retry or finish this `Request`.
  313. func retryOrFinish(error: Error?) {
  314. guard let error = error, let delegate = delegate else { finish(); return }
  315. delegate.retryResult(for: self, dueTo: error) { retryResult in
  316. switch retryResult {
  317. case .doNotRetry, .doNotRetryWithError:
  318. self.finish(error: retryResult.error)
  319. case .retry, .retryWithDelay:
  320. delegate.retryRequest(self, withDelay: retryResult.delay)
  321. }
  322. }
  323. }
  324. /// Finishes this `Request` and starts the response serializers.
  325. func finish(error: Error? = nil) {
  326. if let error = error { self.error = error }
  327. // Start response handlers
  328. processNextResponseSerializer()
  329. eventMonitor?.requestDidFinish(self)
  330. }
  331. /// Appends the response serialization closure to the `Request`.
  332. func appendResponseSerializer(_ closure: @escaping () -> Void) {
  333. protectedMutableState.write { mutableState in
  334. mutableState.responseSerializers.append(closure)
  335. if mutableState.state == .finished {
  336. mutableState.error = AFError.responseSerializationFailed(reason: .responseSerializerAddedAfterRequestFinished)
  337. }
  338. if mutableState.responseSerializerProcessingFinished {
  339. underlyingQueue.async { self.processNextResponseSerializer() }
  340. }
  341. }
  342. }
  343. /// Returns the next response serializer closure to execute if there's one left.
  344. func nextResponseSerializer() -> (() -> Void)? {
  345. var responseSerializer: (() -> Void)?
  346. protectedMutableState.write { mutableState in
  347. let responseSerializerIndex = mutableState.responseSerializerCompletions.count
  348. if responseSerializerIndex < mutableState.responseSerializers.count {
  349. responseSerializer = mutableState.responseSerializers[responseSerializerIndex]
  350. }
  351. }
  352. return responseSerializer
  353. }
  354. /// Processes the next response serializer and calls all completions if response serialization is complete.
  355. func processNextResponseSerializer() {
  356. guard let responseSerializer = nextResponseSerializer() else {
  357. // Execute all response serializer completions and clear them
  358. var completions: [() -> Void] = []
  359. protectedMutableState.write { mutableState in
  360. completions = mutableState.responseSerializerCompletions
  361. // Clear out all response serializers and response serializer completions in mutable state since the
  362. // request is complete. It's important to do this prior to calling the completion closures in case
  363. // the completions call back into the request triggering a re-processing of the response serializers.
  364. // An example of how this can happen is by calling cancel inside a response completion closure.
  365. mutableState.responseSerializers.removeAll()
  366. mutableState.responseSerializerCompletions.removeAll()
  367. if mutableState.state.canTransitionTo(.finished) {
  368. mutableState.state = .finished
  369. }
  370. mutableState.responseSerializerProcessingFinished = true
  371. }
  372. completions.forEach { $0() }
  373. // Cleanup the request
  374. cleanup()
  375. return
  376. }
  377. serializationQueue.async { responseSerializer() }
  378. }
  379. /// Notifies the `Request` that the response serializer is complete.
  380. func responseSerializerDidComplete(completion: @escaping () -> Void) {
  381. protectedMutableState.write { $0.responseSerializerCompletions.append(completion) }
  382. processNextResponseSerializer()
  383. }
  384. /// Resets all task and response serializer related state for retry.
  385. func reset() {
  386. error = nil
  387. uploadProgress.totalUnitCount = 0
  388. uploadProgress.completedUnitCount = 0
  389. downloadProgress.totalUnitCount = 0
  390. downloadProgress.completedUnitCount = 0
  391. protectedMutableState.write { $0.responseSerializerCompletions = [] }
  392. }
  393. /// Called when updating the upload progress.
  394. func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  395. uploadProgress.totalUnitCount = totalBytesExpectedToSend
  396. uploadProgress.completedUnitCount = totalBytesSent
  397. uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
  398. }
  399. /// Perform a closure on the current `state` while locked.
  400. ///
  401. /// - Parameter perform: The closure to perform.
  402. func withState(perform: (State) -> Void) {
  403. protectedMutableState.withState(perform: perform)
  404. }
  405. // MARK: Task Creation
  406. /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
  407. func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  408. fatalError("Subclasses must override.")
  409. }
  410. // MARK: - Public API
  411. // These APIs are callable from any queue.
  412. // MARK: - State
  413. /// Cancels the `Request`. Once cancelled, a `Request` can no longer be resumed or suspended.
  414. ///
  415. /// - Returns: The `Request`.
  416. @discardableResult
  417. public func cancel() -> Self {
  418. protectedMutableState.write { (mutableState) in
  419. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  420. mutableState.state = .cancelled
  421. underlyingQueue.async { self.didCancel() }
  422. guard let task = mutableState.tasks.last, task.state != .completed else {
  423. underlyingQueue.async { self.finish() }
  424. return
  425. }
  426. task.cancel()
  427. underlyingQueue.async { self.didCancelTask(task) }
  428. }
  429. return self
  430. }
  431. /// Suspends the `Request`.
  432. ///
  433. /// - Returns: The `Request`.
  434. @discardableResult
  435. public func suspend() -> Self {
  436. protectedMutableState.write { (mutableState) in
  437. guard mutableState.state.canTransitionTo(.suspended) else { return }
  438. mutableState.state = .suspended
  439. underlyingQueue.async { self.didSuspend() }
  440. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  441. task.suspend()
  442. underlyingQueue.async { self.didSuspendTask(task) }
  443. }
  444. return self
  445. }
  446. /// Resumes the `Request`.
  447. ///
  448. /// - Returns: The `Request`.
  449. @discardableResult
  450. public func resume() -> Self {
  451. protectedMutableState.write { (mutableState) in
  452. guard mutableState.state.canTransitionTo(.resumed) else { return }
  453. mutableState.state = .resumed
  454. underlyingQueue.async { self.didResume() }
  455. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  456. task.resume()
  457. underlyingQueue.async { self.didResumeTask(task) }
  458. }
  459. return self
  460. }
  461. // MARK: - Closure API
  462. /// Associates a credential using the provided values with the `Request`.
  463. ///
  464. /// - Parameters:
  465. /// - username: The username.
  466. /// - password: The password.
  467. /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`.
  468. /// - Returns: The `Request`.
  469. @discardableResult
  470. public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
  471. let credential = URLCredential(user: username, password: password, persistence: persistence)
  472. return authenticate(with: credential)
  473. }
  474. /// Associates the provided credential with the `Request`.
  475. ///
  476. /// - Parameter credential: The `URLCredential`.
  477. /// - Returns: The `Request`.
  478. @discardableResult
  479. public func authenticate(with credential: URLCredential) -> Self {
  480. protectedMutableState.write { $0.credential = credential }
  481. return self
  482. }
  483. /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
  484. ///
  485. /// Only the last closure provided is used.
  486. ///
  487. /// - Parameters:
  488. /// - queue: The `DispatchQueue` to execute the closure on. Defaults to `.main`.
  489. /// - closure: The code to be executed periodically as data is read from the server.
  490. /// - Returns: The `Request`.
  491. @discardableResult
  492. public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  493. protectedMutableState.write { $0.downloadProgressHandler = (handler: closure, queue: queue) }
  494. return self
  495. }
  496. /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is sent to the server.
  497. ///
  498. /// Only the last closure provided is used.
  499. ///
  500. /// - Parameters:
  501. /// - queue: The `DispatchQueue` to execute the closure on. Defaults to `.main`.
  502. /// - closure: The closure to be executed periodically as data is sent to the server.
  503. /// - Returns: The `Request`.
  504. @discardableResult
  505. public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  506. protectedMutableState.write { $0.uploadProgressHandler = (handler: closure, queue: queue) }
  507. return self
  508. }
  509. // MARK: - Redirects
  510. /// Sets the redirect handler for the `Request` which will be used if a redirect response is encountered.
  511. ///
  512. /// - Parameter handler: The `RedirectHandler`.
  513. /// - Returns: The `Request`.
  514. @discardableResult
  515. public func redirect(using handler: RedirectHandler) -> Self {
  516. protectedMutableState.write { mutableState in
  517. precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set")
  518. mutableState.redirectHandler = handler
  519. }
  520. return self
  521. }
  522. // MARK: - Cached Responses
  523. /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response.
  524. ///
  525. /// - Parameter handler: The `CachedResponseHandler`.
  526. /// - Returns: The `Request`.
  527. @discardableResult
  528. public func cacheResponse(using handler: CachedResponseHandler) -> Self {
  529. protectedMutableState.write { mutableState in
  530. precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set")
  531. mutableState.cachedResponseHandler = handler
  532. }
  533. return self
  534. }
  535. // MARK: - Cleanup
  536. /// Final cleanup step executed when a `Request` finishes response serialization.
  537. open func cleanup() {
  538. // No-op: override in subclass
  539. }
  540. }
  541. // MARK: - Protocol Conformances
  542. extension Request: Equatable {
  543. public static func == (lhs: Request, rhs: Request) -> Bool {
  544. return lhs.id == rhs.id
  545. }
  546. }
  547. extension Request: Hashable {
  548. public func hash(into hasher: inout Hasher) {
  549. hasher.combine(id)
  550. }
  551. }
  552. extension Request: CustomStringConvertible {
  553. /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
  554. /// created, as well as the response status code, if a response has been received.
  555. public var description: String {
  556. guard let request = performedRequests.last ?? lastRequest,
  557. let url = request.url,
  558. let method = request.httpMethod else { return "No request created yet." }
  559. let requestDescription = "\(method) \(url.absoluteString)"
  560. return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
  561. }
  562. }
  563. extension Request: CustomDebugStringConvertible {
  564. /// A textual representation of this instance in the form of a cURL command.
  565. public var debugDescription: String {
  566. return cURLRepresentation()
  567. }
  568. func cURLRepresentation() -> String {
  569. guard
  570. let request = lastRequest,
  571. let url = request.url,
  572. let host = url.host,
  573. let method = request.httpMethod else { return "$ curl command could not be created" }
  574. var components = ["$ curl -v"]
  575. components.append("-X \(method)")
  576. if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
  577. let protectionSpace = URLProtectionSpace(
  578. host: host,
  579. port: url.port ?? 0,
  580. protocol: url.scheme,
  581. realm: host,
  582. authenticationMethod: NSURLAuthenticationMethodHTTPBasic
  583. )
  584. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  585. for credential in credentials {
  586. guard let user = credential.user, let password = credential.password else { continue }
  587. components.append("-u \(user):\(password)")
  588. }
  589. } else {
  590. if let credential = credential, let user = credential.user, let password = credential.password {
  591. components.append("-u \(user):\(password)")
  592. }
  593. }
  594. }
  595. if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
  596. if
  597. let cookieStorage = configuration.httpCookieStorage,
  598. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
  599. {
  600. let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
  601. components.append("-b \"\(allCookies)\"")
  602. }
  603. }
  604. var headers: [String: String] = [:]
  605. if let additionalHeaders = delegate?.sessionConfiguration.httpAdditionalHeaders as? [String: String] {
  606. for (field, value) in additionalHeaders where field != "Cookie" {
  607. headers[field] = value
  608. }
  609. }
  610. if let headerFields = request.allHTTPHeaderFields {
  611. for (field, value) in headerFields where field != "Cookie" {
  612. headers[field] = value
  613. }
  614. }
  615. for (field, value) in headers {
  616. let escapedValue = value.replacingOccurrences(of: "\"", with: "\\\"")
  617. components.append("-H \"\(field): \(escapedValue)\"")
  618. }
  619. if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
  620. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  621. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  622. components.append("-d \"\(escapedBody)\"")
  623. }
  624. components.append("\"\(url.absoluteString)\"")
  625. return components.joined(separator: " \\\n\t")
  626. }
  627. }
  628. /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
  629. public protocol RequestDelegate: AnyObject {
  630. var sessionConfiguration: URLSessionConfiguration { get }
  631. func retryResult(for request: Request, dueTo error: Error, completion: @escaping (RetryResult) -> Void)
  632. func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
  633. }
  634. // MARK: - Subclasses
  635. // MARK: DataRequest
  636. public class DataRequest: Request {
  637. public let convertible: URLRequestConvertible
  638. private var protectedData: Protector<Data?> = Protector(nil)
  639. public var data: Data? { return protectedData.directValue }
  640. init(id: UUID = UUID(),
  641. convertible: URLRequestConvertible,
  642. underlyingQueue: DispatchQueue,
  643. serializationQueue: DispatchQueue,
  644. eventMonitor: EventMonitor?,
  645. interceptor: RequestInterceptor?,
  646. delegate: RequestDelegate) {
  647. self.convertible = convertible
  648. super.init(id: id,
  649. underlyingQueue: underlyingQueue,
  650. serializationQueue: serializationQueue,
  651. eventMonitor: eventMonitor,
  652. interceptor: interceptor,
  653. delegate: delegate)
  654. }
  655. override func reset() {
  656. super.reset()
  657. protectedData.directValue = nil
  658. }
  659. func didReceive(data: Data) {
  660. if self.data == nil {
  661. protectedData.directValue = data
  662. } else {
  663. protectedData.append(data)
  664. }
  665. updateDownloadProgress()
  666. }
  667. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  668. let copiedRequest = request
  669. return session.dataTask(with: copiedRequest)
  670. }
  671. func updateDownloadProgress() {
  672. let totalBytesRecieved = Int64(data?.count ?? 0)
  673. let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  674. downloadProgress.totalUnitCount = totalBytesExpected
  675. downloadProgress.completedUnitCount = totalBytesRecieved
  676. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  677. }
  678. /// Validates the request, using the specified closure.
  679. ///
  680. /// If validation fails, subsequent calls to response handlers will have an associated error.
  681. ///
  682. /// - parameter validation: A closure to validate the request.
  683. ///
  684. /// - returns: The request.
  685. @discardableResult
  686. public func validate(_ validation: @escaping Validation) -> Self {
  687. let validator: () -> Void = { [unowned self] in
  688. guard self.error == nil, let response = self.response else { return }
  689. let result = validation(self.request, response, self.data)
  690. if case .failure(let error) = result { self.error = error }
  691. self.eventMonitor?.request(self,
  692. didValidateRequest: self.request,
  693. response: response,
  694. data: self.data,
  695. withResult: result)
  696. }
  697. protectedValidators.append(validator)
  698. return self
  699. }
  700. }
  701. public class DownloadRequest: Request {
  702. /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
  703. /// destination URL.
  704. public struct Options: OptionSet {
  705. /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
  706. public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
  707. /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
  708. public static let removePreviousFile = Options(rawValue: 1 << 1)
  709. /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
  710. public let rawValue: Int
  711. /// Creates a `DownloadRequest.Options` instance with the specified raw value.
  712. ///
  713. /// - parameter rawValue: The raw bitmask value for the option.
  714. ///
  715. /// - returns: A new `DownloadRequest.Options` instance.
  716. public init(rawValue: Int) {
  717. self.rawValue = rawValue
  718. }
  719. }
  720. /// A closure executed once a download request has successfully completed in order to determine where to move the
  721. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  722. /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
  723. /// the options defining how the file should be moved.
  724. public typealias Destination = (_ temporaryURL: URL,
  725. _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
  726. // MARK: Destination
  727. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  728. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  729. ///
  730. /// - parameter directory: The search path directory. `.documentDirectory` by default.
  731. /// - parameter domain: The search path domain mask. `.userDomainMask` by default.
  732. ///
  733. /// - returns: A download file destination closure.
  734. public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
  735. in domain: FileManager.SearchPathDomainMask = .userDomainMask,
  736. options: Options = []) -> Destination {
  737. return { temporaryURL, response in
  738. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  739. let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
  740. return (url, options)
  741. }
  742. }
  743. static let defaultDestination: Destination = { (url, _) in
  744. let filename = "Alamofire_\(url.lastPathComponent)"
  745. let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
  746. return (destination, [])
  747. }
  748. public enum Downloadable {
  749. case request(URLRequestConvertible)
  750. case resumeData(Data)
  751. }
  752. // MARK: Initial State
  753. public let downloadable: Downloadable
  754. let destination: Destination?
  755. // MARK: Updated State
  756. private struct DownloadRequestMutableState {
  757. var resumeData: Data?
  758. var fileURL: URL?
  759. }
  760. private let protectedDownloadMutableState: Protector<DownloadRequestMutableState> = Protector(DownloadRequestMutableState())
  761. public var resumeData: Data? { return protectedDownloadMutableState.directValue.resumeData }
  762. public var fileURL: URL? { return protectedDownloadMutableState.directValue.fileURL }
  763. // MARK: Init
  764. init(id: UUID = UUID(),
  765. downloadable: Downloadable,
  766. underlyingQueue: DispatchQueue,
  767. serializationQueue: DispatchQueue,
  768. eventMonitor: EventMonitor?,
  769. interceptor: RequestInterceptor?,
  770. delegate: RequestDelegate,
  771. destination: Destination? = nil) {
  772. self.downloadable = downloadable
  773. self.destination = destination
  774. super.init(id: id,
  775. underlyingQueue: underlyingQueue,
  776. serializationQueue: serializationQueue,
  777. eventMonitor: eventMonitor,
  778. interceptor: interceptor,
  779. delegate: delegate)
  780. }
  781. override func reset() {
  782. super.reset()
  783. protectedDownloadMutableState.write { $0.resumeData = nil }
  784. protectedDownloadMutableState.write { $0.fileURL = nil }
  785. }
  786. func didFinishDownloading(using task: URLSessionTask, with result: AFResult<URL>) {
  787. eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
  788. switch result {
  789. case .success(let url): protectedDownloadMutableState.write { $0.fileURL = url }
  790. case .failure(let error): self.error = error
  791. }
  792. }
  793. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  794. downloadProgress.totalUnitCount = totalBytesExpectedToWrite
  795. downloadProgress.completedUnitCount += bytesWritten
  796. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  797. }
  798. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  799. return session.downloadTask(with: request)
  800. }
  801. public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
  802. return session.downloadTask(withResumeData: data)
  803. }
  804. @discardableResult
  805. public override func cancel() -> Self {
  806. protectedMutableState.write { (mutableState) in
  807. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  808. mutableState.state = .cancelled
  809. underlyingQueue.async { self.didCancel() }
  810. guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
  811. underlyingQueue.async { self.finish() }
  812. return
  813. }
  814. task.cancel { (resumeData) in
  815. self.protectedDownloadMutableState.write { $0.resumeData = resumeData }
  816. self.underlyingQueue.async { self.didCancelTask(task) }
  817. }
  818. }
  819. return self
  820. }
  821. /// Validates the request, using the specified closure.
  822. ///
  823. /// If validation fails, subsequent calls to response handlers will have an associated error.
  824. ///
  825. /// - parameter validation: A closure to validate the request.
  826. ///
  827. /// - returns: The request.
  828. @discardableResult
  829. public func validate(_ validation: @escaping Validation) -> Self {
  830. let validator: () -> Void = { [unowned self] in
  831. guard self.error == nil, let response = self.response else { return }
  832. let result = validation(self.request, response, self.fileURL)
  833. if case .failure(let error) = result { self.error = error }
  834. self.eventMonitor?.request(self,
  835. didValidateRequest: self.request,
  836. response: response,
  837. fileURL: self.fileURL,
  838. withResult: result)
  839. }
  840. protectedValidators.append(validator)
  841. return self
  842. }
  843. }
  844. public class UploadRequest: DataRequest {
  845. public enum Uploadable {
  846. case data(Data)
  847. case file(URL, shouldRemove: Bool)
  848. case stream(InputStream)
  849. }
  850. // MARK: - Initial State
  851. public let upload: UploadableConvertible
  852. // MARK: - Updated State
  853. public var uploadable: Uploadable?
  854. init(id: UUID = UUID(),
  855. convertible: UploadConvertible,
  856. underlyingQueue: DispatchQueue,
  857. serializationQueue: DispatchQueue,
  858. eventMonitor: EventMonitor?,
  859. interceptor: RequestInterceptor?,
  860. delegate: RequestDelegate) {
  861. self.upload = convertible
  862. super.init(id: id,
  863. convertible: convertible,
  864. underlyingQueue: underlyingQueue,
  865. serializationQueue: serializationQueue,
  866. eventMonitor: eventMonitor,
  867. interceptor: interceptor,
  868. delegate: delegate)
  869. }
  870. func didCreateUploadable(_ uploadable: Uploadable) {
  871. self.uploadable = uploadable
  872. eventMonitor?.request(self, didCreateUploadable: uploadable)
  873. }
  874. func didFailToCreateUploadable(with error: Error) {
  875. self.error = error
  876. eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
  877. retryOrFinish(error: error)
  878. }
  879. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  880. guard let uploadable = uploadable else {
  881. fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
  882. }
  883. switch uploadable {
  884. case let .data(data): return session.uploadTask(with: request, from: data)
  885. case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
  886. case .stream: return session.uploadTask(withStreamedRequest: request)
  887. }
  888. }
  889. func inputStream() -> InputStream {
  890. guard let uploadable = uploadable else {
  891. fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
  892. }
  893. guard case let .stream(stream) = uploadable else {
  894. fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
  895. }
  896. eventMonitor?.request(self, didProvideInputStream: stream)
  897. return stream
  898. }
  899. public override func cleanup() {
  900. super.cleanup()
  901. guard
  902. let uploadable = self.uploadable,
  903. case let .file(url, shouldRemove) = uploadable,
  904. shouldRemove
  905. else { return }
  906. // TODO: Abstract file manager
  907. try? FileManager.default.removeItem(at: url)
  908. }
  909. }
  910. public protocol UploadableConvertible {
  911. func createUploadable() throws -> UploadRequest.Uploadable
  912. }
  913. extension UploadRequest.Uploadable: UploadableConvertible {
  914. public func createUploadable() throws -> UploadRequest.Uploadable {
  915. return self
  916. }
  917. }
  918. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible { }