2
0

Request.swift 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  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. /// Only the last closure provided is used.
  375. ///
  376. /// - Parameters:
  377. /// - queue: The `DispatchQueue` to execute the closure on. Defaults to `.main`.
  378. /// - closure: The code to be executed periodically as data is read from the server.
  379. /// - Returns: The `Request`.
  380. @discardableResult
  381. open func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  382. protectedMutableState.write { $0.downloadProgressHandler = (handler: closure, queue: queue) }
  383. return self
  384. }
  385. /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is sent to 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 closure to be executed periodically as data is sent to the server.
  392. /// - Returns: The `Request`.
  393. @discardableResult
  394. open func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  395. protectedMutableState.write { $0.uploadProgressHandler = (handler: closure, queue: queue) }
  396. return self
  397. }
  398. // MARK: - Redirects
  399. /// Sets the redirect handler for the `Request` which will be used if a redirect response is encountered.
  400. ///
  401. /// - Parameter handler: The `RedirectHandler`.
  402. /// - Returns: The `Request`.
  403. @discardableResult
  404. open func redirect(using handler: RedirectHandler) -> Self {
  405. protectedMutableState.write { mutableState in
  406. precondition(mutableState.redirectHandler == nil, "Redirect handler has already set")
  407. mutableState.redirectHandler = handler
  408. }
  409. return self
  410. }
  411. }
  412. // MARK: - Protocol Conformances
  413. extension Request: Equatable {
  414. public static func == (lhs: Request, rhs: Request) -> Bool {
  415. return lhs.id == rhs.id
  416. }
  417. }
  418. extension Request: Hashable {
  419. public var hashValue: Int {
  420. return id.hashValue
  421. }
  422. }
  423. extension Request: CustomStringConvertible {
  424. /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
  425. /// created, as well as the response status code, if a response has been received.
  426. public var description: String {
  427. guard let request = performedRequests.last ?? lastRequest,
  428. let url = request.url,
  429. let method = request.httpMethod else { return "No request created yet." }
  430. let requestDescription = "\(method) \(url.absoluteString)"
  431. return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
  432. }
  433. }
  434. extension Request: CustomDebugStringConvertible {
  435. /// A textual representation of this instance in the form of a cURL command.
  436. public var debugDescription: String {
  437. return cURLRepresentation()
  438. }
  439. func cURLRepresentation() -> String {
  440. guard
  441. let request = lastRequest,
  442. let url = request.url,
  443. let host = url.host,
  444. let method = request.httpMethod else { return "$ curl command could not be created" }
  445. var components = ["$ curl -v"]
  446. components.append("-X \(method)")
  447. if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
  448. let protectionSpace = URLProtectionSpace(
  449. host: host,
  450. port: url.port ?? 0,
  451. protocol: url.scheme,
  452. realm: host,
  453. authenticationMethod: NSURLAuthenticationMethodHTTPBasic
  454. )
  455. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  456. for credential in credentials {
  457. guard let user = credential.user, let password = credential.password else { continue }
  458. components.append("-u \(user):\(password)")
  459. }
  460. } else {
  461. if let credential = credential, let user = credential.user, let password = credential.password {
  462. components.append("-u \(user):\(password)")
  463. }
  464. }
  465. }
  466. if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
  467. if
  468. let cookieStorage = configuration.httpCookieStorage,
  469. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
  470. {
  471. let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
  472. components.append("-b \"\(allCookies)\"")
  473. }
  474. }
  475. var headers: [String: String] = [:]
  476. if let additionalHeaders = delegate?.sessionConfiguration.httpAdditionalHeaders as? [String: String] {
  477. for (field, value) in additionalHeaders where field != "Cookie" {
  478. headers[field] = value
  479. }
  480. }
  481. if let headerFields = request.allHTTPHeaderFields {
  482. for (field, value) in headerFields where field != "Cookie" {
  483. headers[field] = value
  484. }
  485. }
  486. for (field, value) in headers {
  487. let escapedValue = value.replacingOccurrences(of: "\"", with: "\\\"")
  488. components.append("-H \"\(field): \(escapedValue)\"")
  489. }
  490. if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
  491. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  492. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  493. components.append("-d \"\(escapedBody)\"")
  494. }
  495. components.append("\"\(url.absoluteString)\"")
  496. return components.joined(separator: " \\\n\t")
  497. }
  498. }
  499. /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
  500. public protocol RequestDelegate: AnyObject {
  501. var sessionConfiguration: URLSessionConfiguration { get }
  502. func willRetryRequest(_ request: Request) -> Bool
  503. func retryRequest(_ request: Request, ifNecessaryWithError error: Error)
  504. func cancelRequest(_ request: Request)
  505. func cancelDownloadRequest(_ request: DownloadRequest, byProducingResumeData: @escaping (Data?) -> Void)
  506. func suspendRequest(_ request: Request)
  507. func resumeRequest(_ request: Request)
  508. }
  509. // MARK: - Subclasses
  510. // MARK: DataRequest
  511. open class DataRequest: Request {
  512. public let convertible: URLRequestConvertible
  513. private var protectedData: Protector<Data?> = Protector(nil)
  514. public var data: Data? { return protectedData.directValue }
  515. init(id: UUID = UUID(),
  516. convertible: URLRequestConvertible,
  517. underlyingQueue: DispatchQueue,
  518. serializationQueue: DispatchQueue,
  519. eventMonitor: EventMonitor?,
  520. delegate: RequestDelegate) {
  521. self.convertible = convertible
  522. super.init(id: id,
  523. underlyingQueue: underlyingQueue,
  524. serializationQueue: serializationQueue,
  525. eventMonitor: eventMonitor,
  526. delegate: delegate)
  527. }
  528. override func reset() {
  529. super.reset()
  530. protectedData.directValue = nil
  531. }
  532. func didReceive(data: Data) {
  533. if self.data == nil {
  534. protectedData.directValue = data
  535. } else {
  536. protectedData.append(data)
  537. }
  538. updateDownloadProgress()
  539. }
  540. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  541. let copiedRequest = request
  542. return session.dataTask(with: copiedRequest)
  543. }
  544. func updateDownloadProgress() {
  545. let totalBytesRecieved = Int64(data?.count ?? 0)
  546. let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  547. downloadProgress.totalUnitCount = totalBytesExpected
  548. downloadProgress.completedUnitCount = totalBytesRecieved
  549. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  550. }
  551. /// Validates the request, using the specified closure.
  552. ///
  553. /// If validation fails, subsequent calls to response handlers will have an associated error.
  554. ///
  555. /// - parameter validation: A closure to validate the request.
  556. ///
  557. /// - returns: The request.
  558. @discardableResult
  559. public func validate(_ validation: @escaping Validation) -> Self {
  560. let validator: () -> Void = { [unowned self] in
  561. guard self.error == nil, let response = self.response else { return }
  562. let result = validation(self.request, response, self.data)
  563. result.withError { self.error = $0 }
  564. self.eventMonitor?.request(self,
  565. didValidateRequest: self.request,
  566. response: response,
  567. data: self.data,
  568. withResult: result)
  569. }
  570. protectedValidators.append(validator)
  571. return self
  572. }
  573. }
  574. open class DownloadRequest: Request {
  575. /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
  576. /// destination URL.
  577. public struct Options: OptionSet {
  578. /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
  579. public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
  580. /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
  581. public static let removePreviousFile = Options(rawValue: 1 << 1)
  582. /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
  583. public let rawValue: Int
  584. /// Creates a `DownloadRequest.Options` instance with the specified raw value.
  585. ///
  586. /// - parameter rawValue: The raw bitmask value for the option.
  587. ///
  588. /// - returns: A new `DownloadRequest.Options` instance.
  589. public init(rawValue: Int) {
  590. self.rawValue = rawValue
  591. }
  592. }
  593. /// A closure executed once a download request has successfully completed in order to determine where to move the
  594. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  595. /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
  596. /// the options defining how the file should be moved.
  597. public typealias Destination = (_ temporaryURL: URL,
  598. _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
  599. // MARK: Destination
  600. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  601. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  602. ///
  603. /// - parameter directory: The search path directory. `.documentDirectory` by default.
  604. /// - parameter domain: The search path domain mask. `.userDomainMask` by default.
  605. ///
  606. /// - returns: A download file destination closure.
  607. open class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
  608. in domain: FileManager.SearchPathDomainMask = .userDomainMask,
  609. options: Options = []) -> Destination {
  610. return { (temporaryURL, response) in
  611. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  612. let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
  613. return (url, options)
  614. }
  615. }
  616. static let defaultDestination: Destination = { (url, _) in
  617. let filename = "Alamofire_\(url.lastPathComponent)"
  618. let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
  619. return (destination, [])
  620. }
  621. public enum Downloadable {
  622. case request(URLRequestConvertible)
  623. case resumeData(Data)
  624. }
  625. // MARK: Initial State
  626. public let downloadable: Downloadable
  627. let destination: Destination?
  628. // MARK: Updated State
  629. private struct MutableState {
  630. var resumeData: Data?
  631. var fileURL: URL?
  632. }
  633. private let protectedMutableState: Protector<MutableState> = Protector(MutableState())
  634. public var resumeData: Data? { return protectedMutableState.directValue.resumeData }
  635. public var fileURL: URL? { return protectedMutableState.directValue.fileURL }
  636. // MARK: Init
  637. init(id: UUID = UUID(),
  638. downloadable: Downloadable,
  639. underlyingQueue: DispatchQueue,
  640. serializationQueue: DispatchQueue,
  641. eventMonitor: EventMonitor?,
  642. delegate: RequestDelegate,
  643. destination: Destination? = nil) {
  644. self.downloadable = downloadable
  645. self.destination = destination
  646. super.init(id: id,
  647. underlyingQueue: underlyingQueue,
  648. serializationQueue: serializationQueue,
  649. eventMonitor: eventMonitor,
  650. delegate: delegate)
  651. }
  652. override func reset() {
  653. super.reset()
  654. protectedMutableState.write { $0.resumeData = nil }
  655. protectedMutableState.write { $0.fileURL = nil }
  656. }
  657. func didFinishDownloading(using task: URLSessionTask, with result: Result<URL>) {
  658. eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
  659. result.withValue { url in protectedMutableState.write { $0.fileURL = url } }
  660. .withError { self.error = $0 }
  661. }
  662. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  663. downloadProgress.totalUnitCount = totalBytesExpectedToWrite
  664. downloadProgress.completedUnitCount += bytesWritten
  665. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  666. }
  667. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  668. return session.downloadTask(with: request)
  669. }
  670. open func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
  671. return session.downloadTask(withResumeData: data)
  672. }
  673. @discardableResult
  674. open override func cancel() -> Self {
  675. guard state.canTransitionTo(.cancelled) else { return self }
  676. state = .cancelled
  677. delegate?.cancelDownloadRequest(self) { (resumeData) in
  678. self.protectedMutableState.write { $0.resumeData = resumeData }
  679. }
  680. eventMonitor?.requestDidCancel(self)
  681. return self
  682. }
  683. /// Validates the request, using the specified closure.
  684. ///
  685. /// If validation fails, subsequent calls to response handlers will have an associated error.
  686. ///
  687. /// - parameter validation: A closure to validate the request.
  688. ///
  689. /// - returns: The request.
  690. @discardableResult
  691. public func validate(_ validation: @escaping Validation) -> Self {
  692. let validator: () -> Void = { [unowned self] in
  693. guard self.error == nil, let response = self.response else { return }
  694. let result = validation(self.request, response, self.fileURL)
  695. result.withError { self.error = $0 }
  696. self.eventMonitor?.request(self,
  697. didValidateRequest: self.request,
  698. response: response,
  699. fileURL: self.fileURL,
  700. withResult: result)
  701. }
  702. protectedValidators.append(validator)
  703. return self
  704. }
  705. }
  706. open class UploadRequest: DataRequest {
  707. public enum Uploadable {
  708. case data(Data)
  709. case file(URL, shouldRemove: Bool)
  710. case stream(InputStream)
  711. }
  712. // MARK: - Initial State
  713. public let upload: UploadableConvertible
  714. // MARK: - Updated State
  715. public var uploadable: Uploadable?
  716. init(id: UUID = UUID(),
  717. convertible: UploadConvertible,
  718. underlyingQueue: DispatchQueue,
  719. serializationQueue: DispatchQueue,
  720. eventMonitor: EventMonitor?,
  721. delegate: RequestDelegate) {
  722. self.upload = convertible
  723. super.init(id: id,
  724. convertible: convertible,
  725. underlyingQueue: underlyingQueue,
  726. serializationQueue: serializationQueue,
  727. eventMonitor: eventMonitor,
  728. delegate: delegate)
  729. // Automatically remove temporary upload files (e.g. multipart form data)
  730. internalQueue.addOperation {
  731. guard
  732. let uploadable = self.uploadable,
  733. case let .file(url, shouldRemove) = uploadable,
  734. shouldRemove else { return }
  735. // TODO: Abstract file manager
  736. try? FileManager.default.removeItem(at: url)
  737. }
  738. }
  739. func didCreateUploadable(_ uploadable: Uploadable) {
  740. self.uploadable = uploadable
  741. eventMonitor?.request(self, didCreateUploadable: uploadable)
  742. }
  743. func didFailToCreateUploadable(with error: Error) {
  744. self.error = error
  745. eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
  746. retryOrFinish(error: error)
  747. }
  748. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  749. guard let uploadable = uploadable else {
  750. fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
  751. }
  752. switch uploadable {
  753. case let .data(data): return session.uploadTask(with: request, from: data)
  754. case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
  755. case .stream: return session.uploadTask(withStreamedRequest: request)
  756. }
  757. }
  758. func inputStream() -> InputStream {
  759. guard let uploadable = uploadable else {
  760. fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
  761. }
  762. guard case let .stream(stream) = uploadable else {
  763. fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
  764. }
  765. eventMonitor?.request(self, didProvideInputStream: stream)
  766. return stream
  767. }
  768. }
  769. public protocol UploadableConvertible {
  770. func createUploadable() throws -> UploadRequest.Uploadable
  771. }
  772. extension UploadRequest.Uploadable: UploadableConvertible {
  773. public func createUploadable() throws -> UploadRequest.Uploadable {
  774. return self
  775. }
  776. }
  777. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible { }