Request.swift 39 KB

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