Request.swift 43 KB

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