Request.swift 38 KB

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