Request.swift 42 KB

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