DataRequest.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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.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 { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) }
  132. eventMonitor?.request(self,
  133. didValidateRequest: request,
  134. response: response,
  135. data: data,
  136. withResult: result)
  137. }
  138. validators.write { $0.append(validator) }
  139. return self
  140. }
  141. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion
  142. /// handler to return a `ResponseDisposition` value.
  143. ///
  144. /// - Parameters:
  145. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  146. /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided
  147. /// MUST be called, otherwise the request will never complete.
  148. ///
  149. /// - Returns: The instance.
  150. @_disfavoredOverload
  151. @preconcurrency
  152. @discardableResult
  153. public func onHTTPResponse(
  154. on queue: DispatchQueue = .main,
  155. perform handler: @escaping @Sendable (_ response: HTTPURLResponse,
  156. _ completionHandler: @escaping @Sendable (ResponseDisposition) -> Void) -> Void
  157. ) -> Self {
  158. dataMutableState.write { mutableState in
  159. mutableState.httpResponseHandler = (queue, handler)
  160. }
  161. return self
  162. }
  163. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`.
  164. ///
  165. /// - Parameters:
  166. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  167. /// - handler: Closure called when the instance produces an `HTTPURLResponse`.
  168. ///
  169. /// - Returns: The instance.
  170. @preconcurrency
  171. @discardableResult
  172. public func onHTTPResponse(on queue: DispatchQueue = .main,
  173. perform handler: @escaping @Sendable (HTTPURLResponse) -> Void) -> Self {
  174. onHTTPResponse(on: queue) { response, completionHandler in
  175. handler(response)
  176. completionHandler(.allow)
  177. }
  178. return self
  179. }
  180. // MARK: Response Serialization
  181. /// Adds a handler to be called once the request has finished.
  182. ///
  183. /// - Parameters:
  184. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  185. /// - completionHandler: The code to be executed once the request has finished.
  186. ///
  187. /// - Returns: The request.
  188. @preconcurrency
  189. @discardableResult
  190. public func response(queue: DispatchQueue = .main, completionHandler: @escaping @Sendable (AFDataResponse<Data?>) -> Void) -> Self {
  191. appendResponseSerializer {
  192. // Start work that should be on the serialization queue.
  193. let result = AFResult<Data?>(value: self.data, error: self.error)
  194. // End work that should be on the serialization queue.
  195. self.underlyingQueue.async {
  196. let response = DataResponse(request: self.request,
  197. response: self.response,
  198. data: self.data,
  199. metrics: self.metrics,
  200. serializationDuration: 0,
  201. result: result)
  202. self.eventMonitor?.request(self, didParseResponse: response)
  203. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  204. }
  205. }
  206. return self
  207. }
  208. private func _response<Serializer: DataResponseSerializerProtocol>(queue: DispatchQueue = .main,
  209. responseSerializer: Serializer,
  210. completionHandler: @escaping @Sendable (AFDataResponse<Serializer.SerializedObject>) -> Void)
  211. -> Self {
  212. appendResponseSerializer {
  213. // Start work that should be on the serialization queue.
  214. let start = ProcessInfo.processInfo.systemUptime
  215. let result: AFResult<Serializer.SerializedObject> = Result {
  216. try responseSerializer.serialize(request: self.request,
  217. response: self.response,
  218. data: self.data,
  219. error: self.error)
  220. }.mapError { error in
  221. error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
  222. }
  223. let end = ProcessInfo.processInfo.systemUptime
  224. // End work that should be on the serialization queue.
  225. self.underlyingQueue.async {
  226. let response = DataResponse(request: self.request,
  227. response: self.response,
  228. data: self.data,
  229. metrics: self.metrics,
  230. serializationDuration: end - start,
  231. result: result)
  232. self.eventMonitor?.request(self, didParseResponse: response)
  233. guard !self.isCancelled, let serializerError = result.failure, let delegate = self.delegate else {
  234. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  235. return
  236. }
  237. delegate.retryResult(for: self, dueTo: serializerError) { retryResult in
  238. var didComplete: (@Sendable () -> Void)?
  239. defer {
  240. if let didComplete {
  241. self.responseSerializerDidComplete { queue.async { didComplete() } }
  242. }
  243. }
  244. switch retryResult {
  245. case .doNotRetry:
  246. didComplete = { completionHandler(response) }
  247. case let .doNotRetryWithError(retryError):
  248. let result: AFResult<Serializer.SerializedObject> = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
  249. let response = DataResponse(request: self.request,
  250. response: self.response,
  251. data: self.data,
  252. metrics: self.metrics,
  253. serializationDuration: end - start,
  254. result: result)
  255. didComplete = { completionHandler(response) }
  256. case .retry, .retryWithDelay:
  257. delegate.retryRequest(self, withDelay: retryResult.delay)
  258. }
  259. }
  260. }
  261. }
  262. return self
  263. }
  264. /// Adds a handler to be called once the request has finished.
  265. ///
  266. /// - Parameters:
  267. /// - queue: The queue on which the completion handler is dispatched. `.main` by default
  268. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data.
  269. /// - completionHandler: The code to be executed once the request has finished.
  270. ///
  271. /// - Returns: The request.
  272. @preconcurrency
  273. @discardableResult
  274. public func response<Serializer: DataResponseSerializerProtocol>(queue: DispatchQueue = .main,
  275. responseSerializer: Serializer,
  276. completionHandler: @escaping @Sendable (AFDataResponse<Serializer.SerializedObject>) -> Void)
  277. -> Self {
  278. _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
  279. }
  280. /// Adds a handler to be called once the request has finished.
  281. ///
  282. /// - Parameters:
  283. /// - queue: The queue on which the completion handler is dispatched. `.main` by default
  284. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data.
  285. /// - completionHandler: The code to be executed once the request has finished.
  286. ///
  287. /// - Returns: The request.
  288. @preconcurrency
  289. @discardableResult
  290. public func response<Serializer: ResponseSerializer>(queue: DispatchQueue = .main,
  291. responseSerializer: Serializer,
  292. completionHandler: @escaping @Sendable (AFDataResponse<Serializer.SerializedObject>) -> Void)
  293. -> Self {
  294. _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
  295. }
  296. /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished.
  297. ///
  298. /// - Parameters:
  299. /// - queue: The queue on which the completion handler is called. `.main` by default.
  300. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  301. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  302. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  303. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  304. /// - completionHandler: A closure to be executed once the request has finished.
  305. ///
  306. /// - Returns: The request.
  307. @preconcurrency
  308. @discardableResult
  309. public func responseData(queue: DispatchQueue = .main,
  310. dataPreprocessor: any DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
  311. emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
  312. emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods,
  313. completionHandler: @escaping @Sendable (AFDataResponse<Data>) -> Void) -> Self {
  314. response(queue: queue,
  315. responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
  316. emptyResponseCodes: emptyResponseCodes,
  317. emptyRequestMethods: emptyRequestMethods),
  318. completionHandler: completionHandler)
  319. }
  320. /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished.
  321. ///
  322. /// - Parameters:
  323. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  324. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  325. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  326. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined
  327. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  328. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  329. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  330. /// - completionHandler: A closure to be executed once the request has finished.
  331. ///
  332. /// - Returns: The request.
  333. @preconcurrency
  334. @discardableResult
  335. public func responseString(queue: DispatchQueue = .main,
  336. dataPreprocessor: any DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
  337. encoding: String.Encoding? = nil,
  338. emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
  339. emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods,
  340. completionHandler: @escaping @Sendable (AFDataResponse<String>) -> Void) -> Self {
  341. response(queue: queue,
  342. responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
  343. encoding: encoding,
  344. emptyResponseCodes: emptyResponseCodes,
  345. emptyRequestMethods: emptyRequestMethods),
  346. completionHandler: completionHandler)
  347. }
  348. /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished.
  349. ///
  350. /// - Parameters:
  351. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  352. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  353. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  354. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  355. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  356. /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments`
  357. /// by default.
  358. /// - completionHandler: A closure to be executed once the request has finished.
  359. ///
  360. /// - Returns: The request.
  361. @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.")
  362. @preconcurrency
  363. @discardableResult
  364. public func responseJSON(queue: DispatchQueue = .main,
  365. dataPreprocessor: any DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
  366. emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
  367. emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
  368. options: JSONSerialization.ReadingOptions = .allowFragments,
  369. completionHandler: @escaping @Sendable (AFDataResponse<Any>) -> Void) -> Self {
  370. response(queue: queue,
  371. responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor,
  372. emptyResponseCodes: emptyResponseCodes,
  373. emptyRequestMethods: emptyRequestMethods,
  374. options: options),
  375. completionHandler: completionHandler)
  376. }
  377. /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished.
  378. ///
  379. /// - Parameters:
  380. /// - type: `Decodable` type to decode from response data.
  381. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  382. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  383. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  384. /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
  385. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  386. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  387. /// - completionHandler: A closure to be executed once the request has finished.
  388. ///
  389. /// - Returns: The request.
  390. @preconcurrency
  391. @discardableResult
  392. public func responseDecodable<Value>(of type: Value.Type = Value.self,
  393. queue: DispatchQueue = .main,
  394. dataPreprocessor: any DataPreprocessor = DecodableResponseSerializer<Value>.defaultDataPreprocessor,
  395. decoder: any DataDecoder = JSONDecoder(),
  396. emptyResponseCodes: Set<Int> = DecodableResponseSerializer<Value>.defaultEmptyResponseCodes,
  397. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<Value>.defaultEmptyRequestMethods,
  398. completionHandler: @escaping @Sendable (AFDataResponse<Value>) -> Void) -> Self where Value: Decodable, Value: Sendable {
  399. response(queue: queue,
  400. responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor,
  401. decoder: decoder,
  402. emptyResponseCodes: emptyResponseCodes,
  403. emptyRequestMethods: emptyRequestMethods),
  404. completionHandler: completionHandler)
  405. }
  406. }