Request.swift 39 KB

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