Request.swift 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  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. open 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 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. private 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 suspension is completed.
  260. func didSuspend() {
  261. eventMonitor?.requestDidSuspend(self)
  262. }
  263. /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`.
  264. func didCancel() {
  265. error = AFError.explicitlyCancelled
  266. eventMonitor?.requestDidCancel(self)
  267. }
  268. /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the `Request`.
  269. func didGatherMetrics(_ metrics: URLSessionTaskMetrics) {
  270. protectedMutableState.write { $0.metrics.append(metrics) }
  271. eventMonitor?.request(self, didGatherMetrics: metrics)
  272. }
  273. /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning.
  274. func didFailTask(_ task: URLSessionTask, earlyWithError error: Error) {
  275. self.error = error
  276. // Task will still complete, so didCompleteTask(_:with:) will handle retry.
  277. eventMonitor?.request(self, didFailTask: task, earlyWithError: error)
  278. }
  279. /// Called when a `URLSessionTask` completes. All tasks will eventually call this method.
  280. func didCompleteTask(_ task: URLSessionTask, with error: Error?) {
  281. self.error = self.error ?? error
  282. protectedValidators.directValue.forEach { $0() }
  283. eventMonitor?.request(self, didCompleteTask: task, with: error)
  284. retryOrFinish(error: self.error)
  285. }
  286. /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`.
  287. func prepareForRetry() {
  288. protectedMutableState.write { $0.retryCount += 1 }
  289. reset()
  290. eventMonitor?.requestIsRetrying(self)
  291. }
  292. /// Called to trigger retry or finish this `Request`.
  293. func retryOrFinish(error: Error?) {
  294. guard let error = error, let delegate = delegate else { finish(); return }
  295. delegate.retryResult(for: self, dueTo: error) { retryResult in
  296. switch retryResult {
  297. case .doNotRetry, .doNotRetryWithError:
  298. self.finish(error: retryResult.error)
  299. case .retry, .retryWithDelay:
  300. delegate.retryRequest(self, withDelay: retryResult.delay)
  301. }
  302. }
  303. }
  304. /// Finishes this `Request` and starts the response serializers.
  305. func finish(error: Error? = nil) {
  306. if let error = error { self.error = error }
  307. // Start response handlers
  308. processNextResponseSerializer()
  309. eventMonitor?.requestDidFinish(self)
  310. }
  311. /// Appends the response serialization closure to the `Request`.
  312. func appendResponseSerializer(_ closure: @escaping () -> Void) {
  313. protectedMutableState.write { $0.responseSerializers.append(closure) }
  314. }
  315. /// Returns the next response serializer closure to execute if there's one left.
  316. func nextResponseSerializer() -> (() -> Void)? {
  317. var responseSerializer: (() -> Void)?
  318. protectedMutableState.write { mutableState in
  319. let responseSerializerIndex = mutableState.responseSerializerCompletions.count
  320. if responseSerializerIndex < mutableState.responseSerializers.count {
  321. responseSerializer = mutableState.responseSerializers[responseSerializerIndex]
  322. }
  323. }
  324. return responseSerializer
  325. }
  326. /// Processes the next response serializer and calls all completions if response serialization is complete.
  327. func processNextResponseSerializer() {
  328. guard let responseSerializer = nextResponseSerializer() else {
  329. // Execute all response serializer completions
  330. protectedMutableState.directValue.responseSerializerCompletions.forEach { $0() }
  331. // Cleanup the request
  332. cleanup()
  333. return
  334. }
  335. serializationQueue.async { responseSerializer() }
  336. }
  337. /// Notifies the `Request` that the response serializer is complete.
  338. func responseSerializerDidComplete(completion: @escaping () -> Void) {
  339. protectedMutableState.write { $0.responseSerializerCompletions.append(completion) }
  340. processNextResponseSerializer()
  341. }
  342. /// Resets all task and response serializer related state for retry.
  343. func reset() {
  344. error = nil
  345. uploadProgress.totalUnitCount = 0
  346. uploadProgress.completedUnitCount = 0
  347. downloadProgress.totalUnitCount = 0
  348. downloadProgress.completedUnitCount = 0
  349. protectedMutableState.write { $0.responseSerializerCompletions = [] }
  350. }
  351. /// Called when updating the upload progress.
  352. func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  353. uploadProgress.totalUnitCount = totalBytesExpectedToSend
  354. uploadProgress.completedUnitCount = totalBytesSent
  355. uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
  356. }
  357. // MARK: Task Creation
  358. /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
  359. func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  360. fatalError("Subclasses must override.")
  361. }
  362. // MARK: - Public API
  363. // These APIs are callable from any queue.
  364. // MARK: - State
  365. /// Cancels the `Request`. Once cancelled, a `Request` can no longer be resumed or suspended.
  366. ///
  367. /// - Returns: The `Request`.
  368. @discardableResult
  369. open func cancel() -> Self {
  370. guard state.canTransitionTo(.cancelled) else { return self }
  371. state = .cancelled
  372. delegate?.cancelRequest(self)
  373. return self
  374. }
  375. /// Suspends the `Request`.
  376. ///
  377. /// - Returns: The `Request`.
  378. @discardableResult
  379. open func suspend() -> Self {
  380. guard state.canTransitionTo(.suspended) else { return self }
  381. state = .suspended
  382. delegate?.suspendRequest(self)
  383. return self
  384. }
  385. /// Resumes the `Request`.
  386. ///
  387. /// - Returns: The `Request`.
  388. @discardableResult
  389. open func resume() -> Self {
  390. guard state.canTransitionTo(.resumed) else { return self }
  391. state = .resumed
  392. delegate?.resumeRequest(self)
  393. return self
  394. }
  395. // MARK: - Closure API
  396. /// Associates a credential using the provided values with the `Request`.
  397. ///
  398. /// - Parameters:
  399. /// - username: The username.
  400. /// - password: The password.
  401. /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`.
  402. /// - Returns: The `Request`.
  403. @discardableResult
  404. open func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
  405. let credential = URLCredential(user: username, password: password, persistence: persistence)
  406. return authenticate(with: credential)
  407. }
  408. /// Associates the provided credential with the `Request`.
  409. ///
  410. /// - Parameter credential: The `URLCredential`.
  411. /// - Returns: The `Request`.
  412. @discardableResult
  413. open func authenticate(with credential: URLCredential) -> Self {
  414. protectedMutableState.write { $0.credential = credential }
  415. return self
  416. }
  417. /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
  418. ///
  419. /// Only the last closure provided is used.
  420. ///
  421. /// - Parameters:
  422. /// - queue: The `DispatchQueue` to execute the closure on. Defaults to `.main`.
  423. /// - closure: The code to be executed periodically as data is read from the server.
  424. /// - Returns: The `Request`.
  425. @discardableResult
  426. open func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  427. protectedMutableState.write { $0.downloadProgressHandler = (handler: closure, queue: queue) }
  428. return self
  429. }
  430. /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is sent to the server.
  431. ///
  432. /// Only the last closure provided is used.
  433. ///
  434. /// - Parameters:
  435. /// - queue: The `DispatchQueue` to execute the closure on. Defaults to `.main`.
  436. /// - closure: The closure to be executed periodically as data is sent to the server.
  437. /// - Returns: The `Request`.
  438. @discardableResult
  439. open func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  440. protectedMutableState.write { $0.uploadProgressHandler = (handler: closure, queue: queue) }
  441. return self
  442. }
  443. // MARK: - Redirects
  444. /// Sets the redirect handler for the `Request` which will be used if a redirect response is encountered.
  445. ///
  446. /// - Parameter handler: The `RedirectHandler`.
  447. /// - Returns: The `Request`.
  448. @discardableResult
  449. open func redirect(using handler: RedirectHandler) -> Self {
  450. protectedMutableState.write { mutableState in
  451. precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set")
  452. mutableState.redirectHandler = handler
  453. }
  454. return self
  455. }
  456. // MARK: - Cached Responses
  457. /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response.
  458. ///
  459. /// - Parameter handler: The `CachedResponseHandler`.
  460. /// - Returns: The `Request`.
  461. @discardableResult
  462. open func cacheResponse(using handler: CachedResponseHandler) -> Self {
  463. protectedMutableState.write { mutableState in
  464. precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set")
  465. mutableState.cachedResponseHandler = handler
  466. }
  467. return self
  468. }
  469. // MARK: - Cleanup
  470. /// Final cleanup step executed when a `Request` finishes response serialization.
  471. open func cleanup() {
  472. // No-op: override in subclass
  473. }
  474. }
  475. // MARK: - Protocol Conformances
  476. extension Request: Equatable {
  477. public static func == (lhs: Request, rhs: Request) -> Bool {
  478. return lhs.id == rhs.id
  479. }
  480. }
  481. extension Request: Hashable {
  482. public func hash(into hasher: inout Hasher) {
  483. hasher.combine(id)
  484. }
  485. }
  486. extension Request: CustomStringConvertible {
  487. /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
  488. /// created, as well as the response status code, if a response has been received.
  489. public var description: String {
  490. guard let request = performedRequests.last ?? lastRequest,
  491. let url = request.url,
  492. let method = request.httpMethod else { return "No request created yet." }
  493. let requestDescription = "\(method) \(url.absoluteString)"
  494. return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
  495. }
  496. }
  497. extension Request: CustomDebugStringConvertible {
  498. /// A textual representation of this instance in the form of a cURL command.
  499. public var debugDescription: String {
  500. return cURLRepresentation()
  501. }
  502. func cURLRepresentation() -> String {
  503. guard
  504. let request = lastRequest,
  505. let url = request.url,
  506. let host = url.host,
  507. let method = request.httpMethod else { return "$ curl command could not be created" }
  508. var components = ["$ curl -v"]
  509. components.append("-X \(method)")
  510. if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
  511. let protectionSpace = URLProtectionSpace(
  512. host: host,
  513. port: url.port ?? 0,
  514. protocol: url.scheme,
  515. realm: host,
  516. authenticationMethod: NSURLAuthenticationMethodHTTPBasic
  517. )
  518. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  519. for credential in credentials {
  520. guard let user = credential.user, let password = credential.password else { continue }
  521. components.append("-u \(user):\(password)")
  522. }
  523. } else {
  524. if let credential = credential, let user = credential.user, let password = credential.password {
  525. components.append("-u \(user):\(password)")
  526. }
  527. }
  528. }
  529. if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
  530. if
  531. let cookieStorage = configuration.httpCookieStorage,
  532. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
  533. {
  534. let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
  535. components.append("-b \"\(allCookies)\"")
  536. }
  537. }
  538. var headers: [String: String] = [:]
  539. if let additionalHeaders = delegate?.sessionConfiguration.httpAdditionalHeaders as? [String: String] {
  540. for (field, value) in additionalHeaders where field != "Cookie" {
  541. headers[field] = value
  542. }
  543. }
  544. if let headerFields = request.allHTTPHeaderFields {
  545. for (field, value) in headerFields where field != "Cookie" {
  546. headers[field] = value
  547. }
  548. }
  549. for (field, value) in headers {
  550. let escapedValue = value.replacingOccurrences(of: "\"", with: "\\\"")
  551. components.append("-H \"\(field): \(escapedValue)\"")
  552. }
  553. if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
  554. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  555. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  556. components.append("-d \"\(escapedBody)\"")
  557. }
  558. components.append("\"\(url.absoluteString)\"")
  559. return components.joined(separator: " \\\n\t")
  560. }
  561. }
  562. /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
  563. public protocol RequestDelegate: AnyObject {
  564. var sessionConfiguration: URLSessionConfiguration { get }
  565. func retryResult(for request: Request, dueTo error: Error, completion: @escaping (RetryResult) -> Void)
  566. func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
  567. func cancelRequest(_ request: Request)
  568. func cancelDownloadRequest(_ request: DownloadRequest, byProducingResumeData: @escaping (Data?) -> Void)
  569. func suspendRequest(_ request: Request)
  570. func resumeRequest(_ request: Request)
  571. }
  572. // MARK: - Subclasses
  573. // MARK: DataRequest
  574. open class DataRequest: Request {
  575. public let convertible: URLRequestConvertible
  576. private var protectedData: Protector<Data?> = Protector(nil)
  577. public var data: Data? { return protectedData.directValue }
  578. init(id: UUID = UUID(),
  579. convertible: URLRequestConvertible,
  580. underlyingQueue: DispatchQueue,
  581. serializationQueue: DispatchQueue,
  582. eventMonitor: EventMonitor?,
  583. interceptor: RequestInterceptor?,
  584. delegate: RequestDelegate) {
  585. self.convertible = convertible
  586. super.init(id: id,
  587. underlyingQueue: underlyingQueue,
  588. serializationQueue: serializationQueue,
  589. eventMonitor: eventMonitor,
  590. interceptor: interceptor,
  591. delegate: delegate)
  592. }
  593. override func reset() {
  594. super.reset()
  595. protectedData.directValue = nil
  596. }
  597. func didReceive(data: Data) {
  598. if self.data == nil {
  599. protectedData.directValue = data
  600. } else {
  601. protectedData.append(data)
  602. }
  603. updateDownloadProgress()
  604. }
  605. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  606. let copiedRequest = request
  607. return session.dataTask(with: copiedRequest)
  608. }
  609. func updateDownloadProgress() {
  610. let totalBytesRecieved = Int64(data?.count ?? 0)
  611. let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  612. downloadProgress.totalUnitCount = totalBytesExpected
  613. downloadProgress.completedUnitCount = totalBytesRecieved
  614. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  615. }
  616. /// Validates the request, using the specified closure.
  617. ///
  618. /// If validation fails, subsequent calls to response handlers will have an associated error.
  619. ///
  620. /// - parameter validation: A closure to validate the request.
  621. ///
  622. /// - returns: The request.
  623. @discardableResult
  624. public func validate(_ validation: @escaping Validation) -> Self {
  625. let validator: () -> Void = { [unowned self] in
  626. guard self.error == nil, let response = self.response else { return }
  627. let result = validation(self.request, response, self.data)
  628. result.withError { self.error = $0 }
  629. self.eventMonitor?.request(self,
  630. didValidateRequest: self.request,
  631. response: response,
  632. data: self.data,
  633. withResult: result)
  634. }
  635. protectedValidators.append(validator)
  636. return self
  637. }
  638. }
  639. open class DownloadRequest: Request {
  640. /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
  641. /// destination URL.
  642. public struct Options: OptionSet {
  643. /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
  644. public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
  645. /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
  646. public static let removePreviousFile = Options(rawValue: 1 << 1)
  647. /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
  648. public let rawValue: Int
  649. /// Creates a `DownloadRequest.Options` instance with the specified raw value.
  650. ///
  651. /// - parameter rawValue: The raw bitmask value for the option.
  652. ///
  653. /// - returns: A new `DownloadRequest.Options` instance.
  654. public init(rawValue: Int) {
  655. self.rawValue = rawValue
  656. }
  657. }
  658. /// A closure executed once a download request has successfully completed in order to determine where to move the
  659. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  660. /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
  661. /// the options defining how the file should be moved.
  662. public typealias Destination = (_ temporaryURL: URL,
  663. _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
  664. // MARK: Destination
  665. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  666. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  667. ///
  668. /// - parameter directory: The search path directory. `.documentDirectory` by default.
  669. /// - parameter domain: The search path domain mask. `.userDomainMask` by default.
  670. ///
  671. /// - returns: A download file destination closure.
  672. open class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
  673. in domain: FileManager.SearchPathDomainMask = .userDomainMask,
  674. options: Options = []) -> Destination {
  675. return { (temporaryURL, response) in
  676. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  677. let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
  678. return (url, options)
  679. }
  680. }
  681. static let defaultDestination: Destination = { (url, _) in
  682. let filename = "Alamofire_\(url.lastPathComponent)"
  683. let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
  684. return (destination, [])
  685. }
  686. public enum Downloadable {
  687. case request(URLRequestConvertible)
  688. case resumeData(Data)
  689. }
  690. // MARK: Initial State
  691. public let downloadable: Downloadable
  692. let destination: Destination?
  693. // MARK: Updated State
  694. private struct MutableState {
  695. var resumeData: Data?
  696. var fileURL: URL?
  697. }
  698. private let protectedMutableState: Protector<MutableState> = Protector(MutableState())
  699. public var resumeData: Data? { return protectedMutableState.directValue.resumeData }
  700. public var fileURL: URL? { return protectedMutableState.directValue.fileURL }
  701. // MARK: Init
  702. init(id: UUID = UUID(),
  703. downloadable: Downloadable,
  704. underlyingQueue: DispatchQueue,
  705. serializationQueue: DispatchQueue,
  706. eventMonitor: EventMonitor?,
  707. interceptor: RequestInterceptor?,
  708. delegate: RequestDelegate,
  709. destination: Destination? = nil) {
  710. self.downloadable = downloadable
  711. self.destination = destination
  712. super.init(id: id,
  713. underlyingQueue: underlyingQueue,
  714. serializationQueue: serializationQueue,
  715. eventMonitor: eventMonitor,
  716. interceptor: interceptor,
  717. delegate: delegate)
  718. }
  719. override func reset() {
  720. super.reset()
  721. protectedMutableState.write { $0.resumeData = nil }
  722. protectedMutableState.write { $0.fileURL = nil }
  723. }
  724. func didFinishDownloading(using task: URLSessionTask, with result: Result<URL>) {
  725. eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
  726. result.withValue { url in protectedMutableState.write { $0.fileURL = url } }
  727. .withError { self.error = $0 }
  728. }
  729. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  730. downloadProgress.totalUnitCount = totalBytesExpectedToWrite
  731. downloadProgress.completedUnitCount += bytesWritten
  732. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  733. }
  734. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  735. return session.downloadTask(with: request)
  736. }
  737. open func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
  738. return session.downloadTask(withResumeData: data)
  739. }
  740. @discardableResult
  741. open override func cancel() -> Self {
  742. guard state.canTransitionTo(.cancelled) else { return self }
  743. state = .cancelled
  744. delegate?.cancelDownloadRequest(self) { (resumeData) in
  745. self.protectedMutableState.write { $0.resumeData = resumeData }
  746. }
  747. eventMonitor?.requestDidCancel(self)
  748. return self
  749. }
  750. /// Validates the request, using the specified closure.
  751. ///
  752. /// If validation fails, subsequent calls to response handlers will have an associated error.
  753. ///
  754. /// - parameter validation: A closure to validate the request.
  755. ///
  756. /// - returns: The request.
  757. @discardableResult
  758. public func validate(_ validation: @escaping Validation) -> Self {
  759. let validator: () -> Void = { [unowned self] in
  760. guard self.error == nil, let response = self.response else { return }
  761. let result = validation(self.request, response, self.fileURL)
  762. result.withError { self.error = $0 }
  763. self.eventMonitor?.request(self,
  764. didValidateRequest: self.request,
  765. response: response,
  766. fileURL: self.fileURL,
  767. withResult: result)
  768. }
  769. protectedValidators.append(validator)
  770. return self
  771. }
  772. }
  773. open class UploadRequest: DataRequest {
  774. public enum Uploadable {
  775. case data(Data)
  776. case file(URL, shouldRemove: Bool)
  777. case stream(InputStream)
  778. }
  779. // MARK: - Initial State
  780. public let upload: UploadableConvertible
  781. // MARK: - Updated State
  782. public var uploadable: Uploadable?
  783. init(id: UUID = UUID(),
  784. convertible: UploadConvertible,
  785. underlyingQueue: DispatchQueue,
  786. serializationQueue: DispatchQueue,
  787. eventMonitor: EventMonitor?,
  788. interceptor: RequestInterceptor?,
  789. delegate: RequestDelegate) {
  790. self.upload = convertible
  791. super.init(id: id,
  792. convertible: convertible,
  793. underlyingQueue: underlyingQueue,
  794. serializationQueue: serializationQueue,
  795. eventMonitor: eventMonitor,
  796. interceptor: interceptor,
  797. delegate: delegate)
  798. }
  799. func didCreateUploadable(_ uploadable: Uploadable) {
  800. self.uploadable = uploadable
  801. eventMonitor?.request(self, didCreateUploadable: uploadable)
  802. }
  803. func didFailToCreateUploadable(with error: Error) {
  804. self.error = error
  805. eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
  806. retryOrFinish(error: error)
  807. }
  808. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  809. guard let uploadable = uploadable else {
  810. fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
  811. }
  812. switch uploadable {
  813. case let .data(data): return session.uploadTask(with: request, from: data)
  814. case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
  815. case .stream: return session.uploadTask(withStreamedRequest: request)
  816. }
  817. }
  818. func inputStream() -> InputStream {
  819. guard let uploadable = uploadable else {
  820. fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
  821. }
  822. guard case let .stream(stream) = uploadable else {
  823. fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
  824. }
  825. eventMonitor?.request(self, didProvideInputStream: stream)
  826. return stream
  827. }
  828. open override func cleanup() {
  829. super.cleanup()
  830. guard
  831. let uploadable = self.uploadable,
  832. case let .file(url, shouldRemove) = uploadable,
  833. shouldRemove
  834. else { return }
  835. // TODO: Abstract file manager
  836. try? FileManager.default.removeItem(at: url)
  837. }
  838. }
  839. public protocol UploadableConvertible {
  840. func createUploadable() throws -> UploadRequest.Uploadable
  841. }
  842. extension UploadRequest.Uploadable: UploadableConvertible {
  843. public func createUploadable() throws -> UploadRequest.Uploadable {
  844. return self
  845. }
  846. }
  847. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible { }