Request.swift 38 KB

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