DataRequest.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. //
  2. // DataRequest.swift
  3. //
  4. // Copyright (c) 2014-2024 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` subclass which handles in-memory `Data` download using `URLSessionDataTask`.
  26. public class DataRequest: Request, @unchecked Sendable {
  27. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  28. public let convertible: any URLRequestConvertible
  29. /// `Data` read from the server so far.
  30. public var data: Data? { dataMutableState.read(\.data) }
  31. private struct DataMutableState {
  32. var data: Data?
  33. var httpResponseHandler: (queue: DispatchQueue,
  34. handler: @Sendable (_ response: HTTPURLResponse,
  35. _ completionHandler: @escaping @Sendable (ResponseDisposition) -> Void) -> Void)?
  36. }
  37. private let dataMutableState = Protected(DataMutableState())
  38. /// Creates a `DataRequest` using the provided parameters.
  39. ///
  40. /// - Parameters:
  41. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  42. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  43. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  44. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  45. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  46. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  47. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  48. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  49. init(id: UUID = UUID(),
  50. convertible: any URLRequestConvertible,
  51. underlyingQueue: DispatchQueue,
  52. serializationQueue: DispatchQueue,
  53. eventMonitor: (any EventMonitor)?,
  54. interceptor: (any RequestInterceptor)?,
  55. delegate: any RequestDelegate) {
  56. self.convertible = convertible
  57. super.init(id: id,
  58. underlyingQueue: underlyingQueue,
  59. serializationQueue: serializationQueue,
  60. eventMonitor: eventMonitor,
  61. interceptor: interceptor,
  62. delegate: delegate)
  63. }
  64. override func reset() {
  65. super.reset()
  66. dataMutableState.write { mutableState in
  67. mutableState.data = nil
  68. }
  69. }
  70. /// Called when `Data` is received by this instance.
  71. ///
  72. /// - Note: Also calls `updateDownloadProgress`.
  73. ///
  74. /// - Parameter data: The `Data` received.
  75. func didReceive(data: Data) {
  76. dataMutableState.write { mutableState in
  77. if mutableState.data == nil {
  78. mutableState.data = data
  79. } else {
  80. mutableState.data?.append(data)
  81. }
  82. }
  83. updateDownloadProgress()
  84. }
  85. func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {
  86. dataMutableState.read { dataMutableState in
  87. guard let httpResponseHandler = dataMutableState.httpResponseHandler else {
  88. underlyingQueue.async { completionHandler(.allow) }
  89. return
  90. }
  91. httpResponseHandler.queue.async {
  92. httpResponseHandler.handler(response) { disposition in
  93. if disposition == .cancel {
  94. self.mutableState.write { mutableState in
  95. mutableState.state = .cancelled
  96. mutableState.error = mutableState.error ?? AFError.explicitlyCancelled
  97. }
  98. }
  99. self.underlyingQueue.async {
  100. completionHandler(disposition.sessionDisposition)
  101. }
  102. }
  103. }
  104. }
  105. }
  106. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  107. let copiedRequest = request
  108. return session.dataTask(with: copiedRequest)
  109. }
  110. /// Called to update the `downloadProgress` of the instance.
  111. func updateDownloadProgress() {
  112. let totalBytesReceived = Int64(data?.count ?? 0)
  113. let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  114. downloadProgress.totalUnitCount = totalBytesExpected
  115. downloadProgress.completedUnitCount = totalBytesReceived
  116. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  117. }
  118. /// Validates the request, using the specified closure.
  119. ///
  120. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  121. ///
  122. /// - Parameter validation: `Validation` closure used to validate the response.
  123. ///
  124. /// - Returns: The instance.
  125. @preconcurrency
  126. @discardableResult
  127. public func validate(_ validation: @escaping Validation) -> Self {
  128. let validator: @Sendable () -> Void = { [unowned self] in
  129. guard error == nil, let response else { return }
  130. let result = validation(request, response, data)
  131. if case let .failure(error) = result {
  132. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  133. }
  134. eventMonitor?.request(self,
  135. didValidateRequest: request,
  136. response: response,
  137. data: data,
  138. withResult: result)
  139. }
  140. validators.write { $0.append(validator) }
  141. return self
  142. }
  143. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion
  144. /// handler to return a `ResponseDisposition` value.
  145. ///
  146. /// - Parameters:
  147. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  148. /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided
  149. /// MUST be called, otherwise the request will never complete.
  150. ///
  151. /// - Returns: The instance.
  152. @_disfavoredOverload
  153. @preconcurrency
  154. @discardableResult
  155. public func onHTTPResponse(
  156. on queue: DispatchQueue = .main,
  157. perform handler: @escaping @Sendable (_ response: HTTPURLResponse,
  158. _ completionHandler: @escaping @Sendable (ResponseDisposition) -> Void) -> Void
  159. ) -> Self {
  160. dataMutableState.write { mutableState in
  161. mutableState.httpResponseHandler = (queue, handler)
  162. }
  163. return self
  164. }
  165. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`.
  166. ///
  167. /// - Parameters:
  168. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  169. /// - handler: Closure called when the instance produces an `HTTPURLResponse`.
  170. ///
  171. /// - Returns: The instance.
  172. @preconcurrency
  173. @discardableResult
  174. public func onHTTPResponse(on queue: DispatchQueue = .main,
  175. perform handler: @escaping @Sendable (HTTPURLResponse) -> Void) -> Self {
  176. onHTTPResponse(on: queue) { response, completionHandler in
  177. handler(response)
  178. completionHandler(.allow)
  179. }
  180. return self
  181. }
  182. // MARK: Response Serialization
  183. /// Adds a handler to be called once the request has finished.
  184. ///
  185. /// - Parameters:
  186. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  187. /// - completionHandler: The code to be executed once the request has finished.
  188. ///
  189. /// - Returns: The request.
  190. @preconcurrency
  191. @discardableResult
  192. public func response(queue: DispatchQueue = .main, completionHandler: @escaping @Sendable (AFDataResponse<Data?>) -> Void) -> Self {
  193. appendResponseSerializer {
  194. // Start work that should be on the serialization queue.
  195. let result = AFResult<Data?>(value: self.data, error: self.error)
  196. // End work that should be on the serialization queue.
  197. self.underlyingQueue.async {
  198. let response = DataResponse(request: self.request,
  199. response: self.response,
  200. data: self.data,
  201. metrics: self.metrics,
  202. serializationDuration: 0,
  203. result: result)
  204. self.eventMonitor?.request(self, didParseResponse: response)
  205. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  206. }
  207. }
  208. return self
  209. }
  210. private func _response<Serializer: DataResponseSerializerProtocol>(queue: DispatchQueue = .main,
  211. responseSerializer: Serializer,
  212. completionHandler: @escaping @Sendable (AFDataResponse<Serializer.SerializedObject>) -> Void)
  213. -> Self {
  214. appendResponseSerializer {
  215. // Start work that should be on the serialization queue.
  216. let start = ProcessInfo.processInfo.systemUptime
  217. let result: AFResult<Serializer.SerializedObject> = Result {
  218. try responseSerializer.serialize(request: self.request,
  219. response: self.response,
  220. data: self.data,
  221. error: self.error)
  222. }.mapError { error in
  223. error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
  224. }
  225. let end = ProcessInfo.processInfo.systemUptime
  226. // End work that should be on the serialization queue.
  227. self.underlyingQueue.async {
  228. let response = DataResponse(request: self.request,
  229. response: self.response,
  230. data: self.data,
  231. metrics: self.metrics,
  232. serializationDuration: end - start,
  233. result: result)
  234. self.eventMonitor?.request(self, didParseResponse: response)
  235. guard !self.isCancelled, let serializerError = result.failure, let delegate = self.delegate else {
  236. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  237. return
  238. }
  239. delegate.retryResult(for: self, dueTo: serializerError) { retryResult in
  240. var didComplete: (@Sendable () -> Void)?
  241. defer {
  242. if let didComplete {
  243. self.responseSerializerDidComplete { queue.async { didComplete() } }
  244. }
  245. }
  246. switch retryResult {
  247. case .doNotRetry:
  248. didComplete = { completionHandler(response) }
  249. case let .doNotRetryWithError(retryError):
  250. let result: AFResult<Serializer.SerializedObject> = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
  251. let response = DataResponse(request: self.request,
  252. response: self.response,
  253. data: self.data,
  254. metrics: self.metrics,
  255. serializationDuration: end - start,
  256. result: result)
  257. didComplete = { completionHandler(response) }
  258. case .retry, .retryWithDelay:
  259. delegate.retryRequest(self, withDelay: retryResult.delay)
  260. }
  261. }
  262. }
  263. }
  264. return self
  265. }
  266. /// Adds a handler to be called once the request has finished.
  267. ///
  268. /// - Parameters:
  269. /// - queue: The queue on which the completion handler is dispatched. `.main` by default
  270. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data.
  271. /// - completionHandler: The code to be executed once the request has finished.
  272. ///
  273. /// - Returns: The request.
  274. @preconcurrency
  275. @discardableResult
  276. public func response<Serializer: DataResponseSerializerProtocol>(queue: DispatchQueue = .main,
  277. responseSerializer: Serializer,
  278. completionHandler: @escaping @Sendable (AFDataResponse<Serializer.SerializedObject>) -> Void)
  279. -> Self {
  280. _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
  281. }
  282. /// Adds a handler to be called once the request has finished.
  283. ///
  284. /// - Parameters:
  285. /// - queue: The queue on which the completion handler is dispatched. `.main` by default
  286. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data.
  287. /// - completionHandler: The code to be executed once the request has finished.
  288. ///
  289. /// - Returns: The request.
  290. @preconcurrency
  291. @discardableResult
  292. public func response<Serializer: ResponseSerializer>(queue: DispatchQueue = .main,
  293. responseSerializer: Serializer,
  294. completionHandler: @escaping @Sendable (AFDataResponse<Serializer.SerializedObject>) -> Void)
  295. -> Self {
  296. _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
  297. }
  298. /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished.
  299. ///
  300. /// - Parameters:
  301. /// - queue: The queue on which the completion handler is called. `.main` by default.
  302. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  303. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  304. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  305. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  306. /// - completionHandler: A closure to be executed once the request has finished.
  307. ///
  308. /// - Returns: The request.
  309. @preconcurrency
  310. @discardableResult
  311. public func responseData(queue: DispatchQueue = .main,
  312. dataPreprocessor: any DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
  313. emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
  314. emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods,
  315. completionHandler: @escaping @Sendable (AFDataResponse<Data>) -> Void) -> Self {
  316. response(queue: queue,
  317. responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
  318. emptyResponseCodes: emptyResponseCodes,
  319. emptyRequestMethods: emptyRequestMethods),
  320. completionHandler: completionHandler)
  321. }
  322. /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished.
  323. ///
  324. /// - Parameters:
  325. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  326. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  327. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  328. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined
  329. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  330. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  331. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  332. /// - completionHandler: A closure to be executed once the request has finished.
  333. ///
  334. /// - Returns: The request.
  335. @preconcurrency
  336. @discardableResult
  337. public func responseString(queue: DispatchQueue = .main,
  338. dataPreprocessor: any DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
  339. encoding: String.Encoding? = nil,
  340. emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
  341. emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods,
  342. completionHandler: @escaping @Sendable (AFDataResponse<String>) -> Void) -> Self {
  343. response(queue: queue,
  344. responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
  345. encoding: encoding,
  346. emptyResponseCodes: emptyResponseCodes,
  347. emptyRequestMethods: emptyRequestMethods),
  348. completionHandler: completionHandler)
  349. }
  350. /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished.
  351. ///
  352. /// - Parameters:
  353. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  354. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  355. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  356. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  357. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  358. /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments`
  359. /// by default.
  360. /// - completionHandler: A closure to be executed once the request has finished.
  361. ///
  362. /// - Returns: The request.
  363. @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.")
  364. @preconcurrency
  365. @discardableResult
  366. public func responseJSON(queue: DispatchQueue = .main,
  367. dataPreprocessor: any DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
  368. emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
  369. emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
  370. options: JSONSerialization.ReadingOptions = .allowFragments,
  371. completionHandler: @escaping @Sendable (AFDataResponse<Any>) -> Void) -> Self {
  372. response(queue: queue,
  373. responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor,
  374. emptyResponseCodes: emptyResponseCodes,
  375. emptyRequestMethods: emptyRequestMethods,
  376. options: options),
  377. completionHandler: completionHandler)
  378. }
  379. /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished.
  380. ///
  381. /// - Parameters:
  382. /// - type: `Decodable` type to decode from response data.
  383. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  384. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  385. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  386. /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
  387. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  388. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  389. /// - completionHandler: A closure to be executed once the request has finished.
  390. ///
  391. /// - Returns: The request.
  392. @preconcurrency
  393. @discardableResult
  394. public func responseDecodable<Value>(of type: Value.Type = Value.self,
  395. queue: DispatchQueue = .main,
  396. dataPreprocessor: any DataPreprocessor = DecodableResponseSerializer<Value>.defaultDataPreprocessor,
  397. decoder: any DataDecoder = JSONDecoder(),
  398. emptyResponseCodes: Set<Int> = DecodableResponseSerializer<Value>.defaultEmptyResponseCodes,
  399. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<Value>.defaultEmptyRequestMethods,
  400. completionHandler: @escaping @Sendable (AFDataResponse<Value>) -> Void) -> Self where Value: Decodable, Value: Sendable {
  401. response(queue: queue,
  402. responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor,
  403. decoder: decoder,
  404. emptyResponseCodes: emptyResponseCodes,
  405. emptyRequestMethods: emptyRequestMethods),
  406. completionHandler: completionHandler)
  407. }
  408. }