Concurrency.swift 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. //
  2. // Concurrency.swift
  3. //
  4. // Copyright (c) 2021 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. #if canImport(_Concurrency)
  25. import Foundation
  26. // MARK: - Request Event Streams
  27. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  28. extension Request {
  29. /// Creates a `StreamOf<Progress>` for the instance's upload progress.
  30. ///
  31. /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
  32. ///
  33. /// - Returns: The `StreamOf<Progress>`.
  34. public func uploadProgress(bufferingPolicy: StreamOf<Progress>.BufferingPolicy = .unbounded) -> StreamOf<Progress> {
  35. stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in
  36. uploadProgress(queue: underlyingQueue) { progress in
  37. continuation.yield(progress)
  38. }
  39. }
  40. }
  41. /// Creates a `StreamOf<Progress>` for the instance's download progress.
  42. ///
  43. /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
  44. ///
  45. /// - Returns: The `StreamOf<Progress>`.
  46. public func downloadProgress(bufferingPolicy: StreamOf<Progress>.BufferingPolicy = .unbounded) -> StreamOf<Progress> {
  47. stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in
  48. downloadProgress(queue: underlyingQueue) { progress in
  49. continuation.yield(progress)
  50. }
  51. }
  52. }
  53. /// Creates a `StreamOf<URLRequest>` for the `URLRequest`s produced for the instance.
  54. ///
  55. /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
  56. ///
  57. /// - Returns: The `StreamOf<URLRequest>`.
  58. public func urlRequests(bufferingPolicy: StreamOf<URLRequest>.BufferingPolicy = .unbounded) -> StreamOf<URLRequest> {
  59. stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in
  60. onURLRequestCreation(on: underlyingQueue) { request in
  61. continuation.yield(request)
  62. }
  63. }
  64. }
  65. /// Creates a `StreamOf<URLSessionTask>` for the `URLSessionTask`s produced for the instance.
  66. ///
  67. /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
  68. ///
  69. /// - Returns: The `StreamOf<URLSessionTask>`.
  70. public func urlSessionTasks(bufferingPolicy: StreamOf<URLSessionTask>.BufferingPolicy = .unbounded) -> StreamOf<URLSessionTask> {
  71. stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in
  72. onURLSessionTaskCreation(on: underlyingQueue) { task in
  73. continuation.yield(task)
  74. }
  75. }
  76. }
  77. /// Creates a `StreamOf<String>` for the cURL descriptions produced for the instance.
  78. ///
  79. /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
  80. ///
  81. /// - Returns: The `StreamOf<String>`.
  82. public func cURLDescriptions(bufferingPolicy: StreamOf<String>.BufferingPolicy = .unbounded) -> StreamOf<String> {
  83. stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in
  84. cURLDescription(on: underlyingQueue) { description in
  85. continuation.yield(description)
  86. }
  87. }
  88. }
  89. fileprivate func stream<T>(of type: T.Type = T.self,
  90. bufferingPolicy: StreamOf<T>.BufferingPolicy = .unbounded,
  91. yielder: @escaping (StreamOf<T>.Continuation) -> Void) -> StreamOf<T> {
  92. StreamOf<T>(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in
  93. yielder(continuation)
  94. // Must come after serializers run in order to catch retry progress.
  95. onFinish {
  96. continuation.finish()
  97. }
  98. }
  99. }
  100. }
  101. // MARK: - DataTask
  102. /// Value used to `await` a `DataResponse` and associated values.
  103. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  104. public struct DataTask<Value> {
  105. /// `DataResponse` produced by the `DataRequest` and its response handler.
  106. public var response: DataResponse<Value, AFError> {
  107. get async {
  108. if shouldAutomaticallyCancel {
  109. return await withTaskCancellationHandler {
  110. await task.value
  111. } onCancel: {
  112. cancel()
  113. }
  114. } else {
  115. return await task.value
  116. }
  117. }
  118. }
  119. /// `Result` of any response serialization performed for the `response`.
  120. public var result: Result<Value, AFError> {
  121. get async { await response.result }
  122. }
  123. /// `Value` returned by the `response`.
  124. public var value: Value {
  125. get async throws {
  126. try await result.get()
  127. }
  128. }
  129. private let request: DataRequest
  130. private let task: Task<DataResponse<Value, AFError>, Never>
  131. private let shouldAutomaticallyCancel: Bool
  132. fileprivate init(request: DataRequest, task: Task<DataResponse<Value, AFError>, Never>, shouldAutomaticallyCancel: Bool) {
  133. self.request = request
  134. self.task = task
  135. self.shouldAutomaticallyCancel = shouldAutomaticallyCancel
  136. }
  137. /// Cancel the underlying `DataRequest` and `Task`.
  138. public func cancel() {
  139. task.cancel()
  140. }
  141. /// Resume the underlying `DataRequest`.
  142. public func resume() {
  143. request.resume()
  144. }
  145. /// Suspend the underlying `DataRequest`.
  146. public func suspend() {
  147. request.suspend()
  148. }
  149. }
  150. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  151. extension DataRequest {
  152. /// Creates a `StreamOf<HTTPURLResponse>` for the instance's responses.
  153. ///
  154. /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
  155. ///
  156. /// - Returns: The `StreamOf<HTTPURLResponse>`.
  157. public func httpResponses(bufferingPolicy: StreamOf<HTTPURLResponse>.BufferingPolicy = .unbounded) -> StreamOf<HTTPURLResponse> {
  158. stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in
  159. onHTTPResponse(on: underlyingQueue) { response in
  160. continuation.yield(response)
  161. }
  162. }
  163. }
  164. /// Sets an async closure returning a `Request.ResponseDisposition`, called whenever the `DataRequest` produces an
  165. /// `HTTPURLResponse`.
  166. ///
  167. /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries).
  168. /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams,
  169. /// where responses after the first will contain the part headers.
  170. ///
  171. /// - Parameters:
  172. /// - handler: Async closure executed when a new `HTTPURLResponse` is received and returning a
  173. /// `ResponseDisposition` value. This value determines whether to continue the request or cancel it as
  174. /// if `cancel()` had been called on the instance. Note, this closure is called on an arbitrary thread,
  175. /// so any synchronous calls in it will execute in that context.
  176. ///
  177. /// - Returns: The instance.
  178. @_disfavoredOverload
  179. @discardableResult
  180. public func onHTTPResponse(
  181. perform handler: @escaping @Sendable (_ response: HTTPURLResponse) async -> ResponseDisposition
  182. ) -> Self {
  183. onHTTPResponse(on: underlyingQueue) { response, completionHandler in
  184. Task {
  185. let disposition = await handler(response)
  186. completionHandler(disposition)
  187. }
  188. }
  189. return self
  190. }
  191. /// Sets an async closure called whenever the `DataRequest` produces an `HTTPURLResponse`.
  192. ///
  193. /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries).
  194. /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams,
  195. /// where responses after the first will contain the part headers.
  196. ///
  197. /// - Parameters:
  198. /// - handler: Async closure executed when a new `HTTPURLResponse` is received. Note, this closure is called on an
  199. /// arbitrary thread, so any synchronous calls in it will execute in that context.
  200. ///
  201. /// - Returns: The instance.
  202. @discardableResult
  203. public func onHTTPResponse(perform handler: @escaping @Sendable (_ response: HTTPURLResponse) async -> Void) -> Self {
  204. onHTTPResponse { response in
  205. await handler(response)
  206. return .allow
  207. }
  208. return self
  209. }
  210. /// Creates a `DataTask` to `await` a `Data` value.
  211. ///
  212. /// - Parameters:
  213. /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
  214. /// enclosing async context is cancelled. Only applies to `DataTask`'s async
  215. /// properties. `true` by default.
  216. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before completion.
  217. /// - emptyResponseCodes: HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  218. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  219. ///
  220. /// - Returns: The `DataTask`.
  221. public func serializingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true,
  222. dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
  223. emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
  224. emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) -> DataTask<Data> {
  225. serializingResponse(using: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
  226. emptyResponseCodes: emptyResponseCodes,
  227. emptyRequestMethods: emptyRequestMethods),
  228. automaticallyCancelling: shouldAutomaticallyCancel)
  229. }
  230. /// Creates a `DataTask` to `await` serialization of a `Decodable` value.
  231. ///
  232. /// - Parameters:
  233. /// - type: `Decodable` type to decode from response data.
  234. /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
  235. /// enclosing async context is cancelled. Only applies to `DataTask`'s async
  236. /// properties. `true` by default.
  237. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer.
  238. /// `PassthroughPreprocessor()` by default.
  239. /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
  240. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  241. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  242. ///
  243. /// - Returns: The `DataTask`.
  244. public func serializingDecodable<Value: Decodable>(_ type: Value.Type = Value.self,
  245. automaticallyCancelling shouldAutomaticallyCancel: Bool = true,
  246. dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<Value>.defaultDataPreprocessor,
  247. decoder: DataDecoder = JSONDecoder(),
  248. emptyResponseCodes: Set<Int> = DecodableResponseSerializer<Value>.defaultEmptyResponseCodes,
  249. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<Value>.defaultEmptyRequestMethods) -> DataTask<Value> {
  250. serializingResponse(using: DecodableResponseSerializer<Value>(dataPreprocessor: dataPreprocessor,
  251. decoder: decoder,
  252. emptyResponseCodes: emptyResponseCodes,
  253. emptyRequestMethods: emptyRequestMethods),
  254. automaticallyCancelling: shouldAutomaticallyCancel)
  255. }
  256. /// Creates a `DataTask` to `await` serialization of a `String` value.
  257. ///
  258. /// - Parameters:
  259. /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
  260. /// enclosing async context is cancelled. Only applies to `DataTask`'s async
  261. /// properties. `true` by default.
  262. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer.
  263. /// `PassthroughPreprocessor()` by default.
  264. /// - encoding: `String.Encoding` to use during serialization. Defaults to `nil`, in which case
  265. /// the encoding will be determined from the server response, falling back to the
  266. /// default HTTP character set, `ISO-8859-1`.
  267. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  268. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  269. ///
  270. /// - Returns: The `DataTask`.
  271. public func serializingString(automaticallyCancelling shouldAutomaticallyCancel: Bool = true,
  272. dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
  273. encoding: String.Encoding? = nil,
  274. emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
  275. emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) -> DataTask<String> {
  276. serializingResponse(using: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
  277. encoding: encoding,
  278. emptyResponseCodes: emptyResponseCodes,
  279. emptyRequestMethods: emptyRequestMethods),
  280. automaticallyCancelling: shouldAutomaticallyCancel)
  281. }
  282. /// Creates a `DataTask` to `await` serialization using the provided `ResponseSerializer` instance.
  283. ///
  284. /// - Parameters:
  285. /// - serializer: `ResponseSerializer` responsible for serializing the request, response, and data.
  286. /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
  287. /// enclosing async context is cancelled. Only applies to `DataTask`'s async
  288. /// properties. `true` by default.
  289. ///
  290. /// - Returns: The `DataTask`.
  291. public func serializingResponse<Serializer: ResponseSerializer>(using serializer: Serializer,
  292. automaticallyCancelling shouldAutomaticallyCancel: Bool = true)
  293. -> DataTask<Serializer.SerializedObject> {
  294. dataTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in
  295. response(queue: underlyingQueue,
  296. responseSerializer: serializer,
  297. completionHandler: $0)
  298. }
  299. }
  300. /// Creates a `DataTask` to `await` serialization using the provided `DataResponseSerializerProtocol` instance.
  301. ///
  302. /// - Parameters:
  303. /// - serializer: `DataResponseSerializerProtocol` responsible for serializing the request,
  304. /// response, and data.
  305. /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
  306. /// enclosing async context is cancelled. Only applies to `DataTask`'s async
  307. /// properties. `true` by default.
  308. ///
  309. /// - Returns: The `DataTask`.
  310. public func serializingResponse<Serializer: DataResponseSerializerProtocol>(using serializer: Serializer,
  311. automaticallyCancelling shouldAutomaticallyCancel: Bool = true)
  312. -> DataTask<Serializer.SerializedObject> {
  313. dataTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in
  314. response(queue: underlyingQueue,
  315. responseSerializer: serializer,
  316. completionHandler: $0)
  317. }
  318. }
  319. private func dataTask<Value>(automaticallyCancelling shouldAutomaticallyCancel: Bool,
  320. forResponse onResponse: @escaping (@escaping (DataResponse<Value, AFError>) -> Void) -> Void)
  321. -> DataTask<Value> {
  322. let task = Task {
  323. await withTaskCancellationHandler {
  324. await withCheckedContinuation { continuation in
  325. onResponse {
  326. continuation.resume(returning: $0)
  327. }
  328. }
  329. } onCancel: {
  330. self.cancel()
  331. }
  332. }
  333. return DataTask<Value>(request: self, task: task, shouldAutomaticallyCancel: shouldAutomaticallyCancel)
  334. }
  335. }
  336. // MARK: - DownloadTask
  337. /// Value used to `await` a `DownloadResponse` and associated values.
  338. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  339. public struct DownloadTask<Value> {
  340. /// `DownloadResponse` produced by the `DownloadRequest` and its response handler.
  341. public var response: DownloadResponse<Value, AFError> {
  342. get async {
  343. if shouldAutomaticallyCancel {
  344. return await withTaskCancellationHandler {
  345. await task.value
  346. } onCancel: {
  347. cancel()
  348. }
  349. } else {
  350. return await task.value
  351. }
  352. }
  353. }
  354. /// `Result` of any response serialization performed for the `response`.
  355. public var result: Result<Value, AFError> {
  356. get async { await response.result }
  357. }
  358. /// `Value` returned by the `response`.
  359. public var value: Value {
  360. get async throws {
  361. try await result.get()
  362. }
  363. }
  364. private let task: Task<AFDownloadResponse<Value>, Never>
  365. private let request: DownloadRequest
  366. private let shouldAutomaticallyCancel: Bool
  367. fileprivate init(request: DownloadRequest, task: Task<AFDownloadResponse<Value>, Never>, shouldAutomaticallyCancel: Bool) {
  368. self.request = request
  369. self.task = task
  370. self.shouldAutomaticallyCancel = shouldAutomaticallyCancel
  371. }
  372. /// Cancel the underlying `DownloadRequest` and `Task`.
  373. public func cancel() {
  374. task.cancel()
  375. }
  376. /// Resume the underlying `DownloadRequest`.
  377. public func resume() {
  378. request.resume()
  379. }
  380. /// Suspend the underlying `DownloadRequest`.
  381. public func suspend() {
  382. request.suspend()
  383. }
  384. }
  385. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  386. extension DownloadRequest {
  387. /// Creates a `DownloadTask` to `await` a `Data` value.
  388. ///
  389. /// - Parameters:
  390. /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
  391. /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async
  392. /// properties. `true` by default.
  393. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before completion.
  394. /// - emptyResponseCodes: HTTP response codes for which empty responses are allowed. `[204, 205]` by default.
  395. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  396. ///
  397. /// - Returns: The `DownloadTask`.
  398. public func serializingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true,
  399. dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
  400. emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
  401. emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask<Data> {
  402. serializingDownload(using: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
  403. emptyResponseCodes: emptyResponseCodes,
  404. emptyRequestMethods: emptyRequestMethods),
  405. automaticallyCancelling: shouldAutomaticallyCancel)
  406. }
  407. /// Creates a `DownloadTask` to `await` serialization of a `Decodable` value.
  408. ///
  409. /// - Note: This serializer reads the entire response into memory before parsing.
  410. ///
  411. /// - Parameters:
  412. /// - type: `Decodable` type to decode from response data.
  413. /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
  414. /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async
  415. /// properties. `true` by default.
  416. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the serializer.
  417. /// `PassthroughPreprocessor()` by default.
  418. /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
  419. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  420. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  421. ///
  422. /// - Returns: The `DownloadTask`.
  423. public func serializingDecodable<Value: Decodable>(_ type: Value.Type = Value.self,
  424. automaticallyCancelling shouldAutomaticallyCancel: Bool = true,
  425. dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<Value>.defaultDataPreprocessor,
  426. decoder: DataDecoder = JSONDecoder(),
  427. emptyResponseCodes: Set<Int> = DecodableResponseSerializer<Value>.defaultEmptyResponseCodes,
  428. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<Value>.defaultEmptyRequestMethods) -> DownloadTask<Value> {
  429. serializingDownload(using: DecodableResponseSerializer<Value>(dataPreprocessor: dataPreprocessor,
  430. decoder: decoder,
  431. emptyResponseCodes: emptyResponseCodes,
  432. emptyRequestMethods: emptyRequestMethods),
  433. automaticallyCancelling: shouldAutomaticallyCancel)
  434. }
  435. /// Creates a `DownloadTask` to `await` serialization of the downloaded file's `URL` on disk.
  436. ///
  437. /// - Parameters:
  438. /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
  439. /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async
  440. /// properties. `true` by default.
  441. ///
  442. /// - Returns: The `DownloadTask`.
  443. public func serializingDownloadedFileURL(automaticallyCancelling shouldAutomaticallyCancel: Bool = true) -> DownloadTask<URL> {
  444. serializingDownload(using: URLResponseSerializer(),
  445. automaticallyCancelling: shouldAutomaticallyCancel)
  446. }
  447. /// Creates a `DownloadTask` to `await` serialization of a `String` value.
  448. ///
  449. /// - Parameters:
  450. /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
  451. /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async
  452. /// properties. `true` by default.
  453. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  454. /// serializer. `PassthroughPreprocessor()` by default.
  455. /// - encoding: `String.Encoding` to use during serialization. Defaults to `nil`, in which case
  456. /// the encoding will be determined from the server response, falling back to the
  457. /// default HTTP character set, `ISO-8859-1`.
  458. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  459. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  460. ///
  461. /// - Returns: The `DownloadTask`.
  462. public func serializingString(automaticallyCancelling shouldAutomaticallyCancel: Bool = true,
  463. dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
  464. encoding: String.Encoding? = nil,
  465. emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
  466. emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) -> DownloadTask<String> {
  467. serializingDownload(using: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
  468. encoding: encoding,
  469. emptyResponseCodes: emptyResponseCodes,
  470. emptyRequestMethods: emptyRequestMethods),
  471. automaticallyCancelling: shouldAutomaticallyCancel)
  472. }
  473. /// Creates a `DownloadTask` to `await` serialization using the provided `ResponseSerializer` instance.
  474. ///
  475. /// - Parameters:
  476. /// - serializer: `ResponseSerializer` responsible for serializing the request, response, and data.
  477. /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
  478. /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async
  479. /// properties. `true` by default.
  480. ///
  481. /// - Returns: The `DownloadTask`.
  482. public func serializingDownload<Serializer: ResponseSerializer>(using serializer: Serializer,
  483. automaticallyCancelling shouldAutomaticallyCancel: Bool = true)
  484. -> DownloadTask<Serializer.SerializedObject> {
  485. downloadTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in
  486. response(queue: underlyingQueue,
  487. responseSerializer: serializer,
  488. completionHandler: $0)
  489. }
  490. }
  491. /// Creates a `DownloadTask` to `await` serialization using the provided `DownloadResponseSerializerProtocol`
  492. /// instance.
  493. ///
  494. /// - Parameters:
  495. /// - serializer: `DownloadResponseSerializerProtocol` responsible for serializing the request,
  496. /// response, and data.
  497. /// - shouldAutomaticallyCancel: `Bool` determining whether or not the request should be cancelled when the
  498. /// enclosing async context is cancelled. Only applies to `DownloadTask`'s async
  499. /// properties. `true` by default.
  500. ///
  501. /// - Returns: The `DownloadTask`.
  502. public func serializingDownload<Serializer: DownloadResponseSerializerProtocol>(using serializer: Serializer,
  503. automaticallyCancelling shouldAutomaticallyCancel: Bool = true)
  504. -> DownloadTask<Serializer.SerializedObject> {
  505. downloadTask(automaticallyCancelling: shouldAutomaticallyCancel) { [self] in
  506. response(queue: underlyingQueue,
  507. responseSerializer: serializer,
  508. completionHandler: $0)
  509. }
  510. }
  511. private func downloadTask<Value>(automaticallyCancelling shouldAutomaticallyCancel: Bool,
  512. forResponse onResponse: @escaping (@escaping (DownloadResponse<Value, AFError>) -> Void) -> Void)
  513. -> DownloadTask<Value> {
  514. let task = Task {
  515. await withTaskCancellationHandler {
  516. await withCheckedContinuation { continuation in
  517. onResponse {
  518. continuation.resume(returning: $0)
  519. }
  520. }
  521. } onCancel: {
  522. self.cancel()
  523. }
  524. }
  525. return DownloadTask<Value>(request: self, task: task, shouldAutomaticallyCancel: shouldAutomaticallyCancel)
  526. }
  527. }
  528. // MARK: - DataStreamTask
  529. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  530. public struct DataStreamTask {
  531. // Type of created streams.
  532. public typealias Stream<Success, Failure: Error> = StreamOf<DataStreamRequest.Stream<Success, Failure>>
  533. private let request: DataStreamRequest
  534. fileprivate init(request: DataStreamRequest) {
  535. self.request = request
  536. }
  537. /// Creates a `Stream` of `Data` values from the underlying `DataStreamRequest`.
  538. ///
  539. /// - Parameters:
  540. /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled
  541. /// which observation of the stream stops. `true` by default.
  542. /// - bufferingPolicy: ` BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
  543. ///
  544. /// - Returns: The `Stream`.
  545. public func streamingData(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, bufferingPolicy: Stream<Data, Never>.BufferingPolicy = .unbounded) -> Stream<Data, Never> {
  546. createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in
  547. request.responseStream(on: .streamCompletionQueue(forRequestID: request.id), stream: onStream)
  548. }
  549. }
  550. /// Creates a `Stream` of `UTF-8` `String`s from the underlying `DataStreamRequest`.
  551. ///
  552. /// - Parameters:
  553. /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled
  554. /// which observation of the stream stops. `true` by default.
  555. /// - bufferingPolicy: ` BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
  556. /// - Returns:
  557. public func streamingStrings(automaticallyCancelling shouldAutomaticallyCancel: Bool = true, bufferingPolicy: Stream<String, Never>.BufferingPolicy = .unbounded) -> Stream<String, Never> {
  558. createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in
  559. request.responseStreamString(on: .streamCompletionQueue(forRequestID: request.id), stream: onStream)
  560. }
  561. }
  562. /// Creates a `Stream` of `Decodable` values from the underlying `DataStreamRequest`.
  563. ///
  564. /// - Parameters:
  565. /// - type: `Decodable` type to be serialized from stream payloads.
  566. /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled
  567. /// which observation of the stream stops. `true` by default.
  568. /// - bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
  569. ///
  570. /// - Returns: The `Stream`.
  571. public func streamingDecodables<T>(_ type: T.Type = T.self,
  572. automaticallyCancelling shouldAutomaticallyCancel: Bool = true,
  573. bufferingPolicy: Stream<T, AFError>.BufferingPolicy = .unbounded)
  574. -> Stream<T, AFError> where T: Decodable {
  575. streamingResponses(serializedUsing: DecodableStreamSerializer<T>(),
  576. automaticallyCancelling: shouldAutomaticallyCancel,
  577. bufferingPolicy: bufferingPolicy)
  578. }
  579. /// Creates a `Stream` of values using the provided `DataStreamSerializer` from the underlying `DataStreamRequest`.
  580. ///
  581. /// - Parameters:
  582. /// - serializer: `DataStreamSerializer` to use to serialize incoming `Data`.
  583. /// - shouldAutomaticallyCancel: `Bool` indicating whether the underlying `DataStreamRequest` should be canceled
  584. /// which observation of the stream stops. `true` by default.
  585. /// - bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
  586. ///
  587. /// - Returns: The `Stream`.
  588. public func streamingResponses<Serializer: DataStreamSerializer>(serializedUsing serializer: Serializer,
  589. automaticallyCancelling shouldAutomaticallyCancel: Bool = true,
  590. bufferingPolicy: Stream<Serializer.SerializedObject, AFError>.BufferingPolicy = .unbounded)
  591. -> Stream<Serializer.SerializedObject, AFError> {
  592. createStream(automaticallyCancelling: shouldAutomaticallyCancel, bufferingPolicy: bufferingPolicy) { onStream in
  593. request.responseStream(using: serializer,
  594. on: .streamCompletionQueue(forRequestID: request.id),
  595. stream: onStream)
  596. }
  597. }
  598. private func createStream<Success, Failure: Error>(automaticallyCancelling shouldAutomaticallyCancel: Bool = true,
  599. bufferingPolicy: Stream<Success, Failure>.BufferingPolicy = .unbounded,
  600. forResponse onResponse: @escaping (@escaping (DataStreamRequest.Stream<Success, Failure>) -> Void) -> Void)
  601. -> Stream<Success, Failure> {
  602. StreamOf(bufferingPolicy: bufferingPolicy) {
  603. guard shouldAutomaticallyCancel,
  604. request.isInitialized || request.isResumed || request.isSuspended else { return }
  605. cancel()
  606. } builder: { continuation in
  607. onResponse { stream in
  608. continuation.yield(stream)
  609. if case .complete = stream.event {
  610. continuation.finish()
  611. }
  612. }
  613. }
  614. }
  615. /// Cancel the underlying `DataStreamRequest`.
  616. public func cancel() {
  617. request.cancel()
  618. }
  619. /// Resume the underlying `DataStreamRequest`.
  620. public func resume() {
  621. request.resume()
  622. }
  623. /// Suspend the underlying `DataStreamRequest`.
  624. public func suspend() {
  625. request.suspend()
  626. }
  627. }
  628. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  629. extension DataStreamRequest {
  630. /// Creates a `StreamOf<HTTPURLResponse>` for the instance's responses.
  631. ///
  632. /// - Parameter bufferingPolicy: `BufferingPolicy` that determines the stream's buffering behavior.`.unbounded` by default.
  633. ///
  634. /// - Returns: The `StreamOf<HTTPURLResponse>`.
  635. public func httpResponses(bufferingPolicy: StreamOf<HTTPURLResponse>.BufferingPolicy = .unbounded) -> StreamOf<HTTPURLResponse> {
  636. stream(bufferingPolicy: bufferingPolicy) { [unowned self] continuation in
  637. onHTTPResponse(on: underlyingQueue) { response in
  638. continuation.yield(response)
  639. }
  640. }
  641. }
  642. /// Sets an async closure returning a `Request.ResponseDisposition`, called whenever the `DataStreamRequest`
  643. /// produces an `HTTPURLResponse`.
  644. ///
  645. /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries).
  646. /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams,
  647. /// where responses after the first will contain the part headers.
  648. ///
  649. /// - Parameters:
  650. /// - handler: Async closure executed when a new `HTTPURLResponse` is received and returning a
  651. /// `ResponseDisposition` value. This value determines whether to continue the request or cancel it as
  652. /// if `cancel()` had been called on the instance. Note, this closure is called on an arbitrary thread,
  653. /// so any synchronous calls in it will execute in that context.
  654. ///
  655. /// - Returns: The instance.
  656. @_disfavoredOverload
  657. @discardableResult
  658. public func onHTTPResponse(perform handler: @escaping @Sendable (HTTPURLResponse) async -> ResponseDisposition) -> Self {
  659. onHTTPResponse(on: underlyingQueue) { response, completionHandler in
  660. Task {
  661. let disposition = await handler(response)
  662. completionHandler(disposition)
  663. }
  664. }
  665. return self
  666. }
  667. /// Sets an async closure called whenever the `DataStreamRequest` produces an `HTTPURLResponse`.
  668. ///
  669. /// - Note: Most requests will only produce a single response for each outgoing attempt (initial + retries).
  670. /// However, some types of response may trigger multiple `HTTPURLResponse`s, such as multipart streams,
  671. /// where responses after the first will contain the part headers.
  672. ///
  673. /// - Parameters:
  674. /// - handler: Async closure executed when a new `HTTPURLResponse` is received. Note, this closure is called on an
  675. /// arbitrary thread, so any synchronous calls in it will execute in that context.
  676. ///
  677. /// - Returns: The instance.
  678. @discardableResult
  679. public func onHTTPResponse(perform handler: @escaping @Sendable (HTTPURLResponse) async -> Void) -> Self {
  680. onHTTPResponse { response in
  681. await handler(response)
  682. return .allow
  683. }
  684. return self
  685. }
  686. /// Creates a `DataStreamTask` used to `await` streams of serialized values.
  687. ///
  688. /// - Returns: The `DataStreamTask`.
  689. public func streamTask() -> DataStreamTask {
  690. DataStreamTask(request: self)
  691. }
  692. }
  693. #if canImport(Darwin) && !canImport(FoundationNetworking) // Only Apple platforms support URLSessionWebSocketTask.
  694. // - MARK: WebSocketTask
  695. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  696. @_spi(WebSocket) public struct WebSocketTask {
  697. private let request: WebSocketRequest
  698. fileprivate init(request: WebSocketRequest) {
  699. self.request = request
  700. }
  701. public typealias EventStreamOf<Success, Failure: Error> = StreamOf<WebSocketRequest.Event<Success, Failure>>
  702. public func streamingMessageEvents(
  703. automaticallyCancelling shouldAutomaticallyCancel: Bool = true,
  704. bufferingPolicy: EventStreamOf<URLSessionWebSocketTask.Message, Never>.BufferingPolicy = .unbounded
  705. ) -> EventStreamOf<URLSessionWebSocketTask.Message, Never> {
  706. createStream(automaticallyCancelling: shouldAutomaticallyCancel,
  707. bufferingPolicy: bufferingPolicy,
  708. transform: { $0 }) { onEvent in
  709. request.streamMessageEvents(on: .streamCompletionQueue(forRequestID: request.id), handler: onEvent)
  710. }
  711. }
  712. public func streamingMessages(
  713. automaticallyCancelling shouldAutomaticallyCancel: Bool = true,
  714. bufferingPolicy: StreamOf<URLSessionWebSocketTask.Message>.BufferingPolicy = .unbounded
  715. ) -> StreamOf<URLSessionWebSocketTask.Message> {
  716. createStream(automaticallyCancelling: shouldAutomaticallyCancel,
  717. bufferingPolicy: bufferingPolicy,
  718. transform: { $0.message }) { onEvent in
  719. request.streamMessageEvents(on: .streamCompletionQueue(forRequestID: request.id), handler: onEvent)
  720. }
  721. }
  722. public func streamingDecodableEvents<Value: Decodable>(
  723. _ type: Value.Type = Value.self,
  724. automaticallyCancelling shouldAutomaticallyCancel: Bool = true,
  725. using decoder: DataDecoder = JSONDecoder(),
  726. bufferingPolicy: EventStreamOf<Value, Error>.BufferingPolicy = .unbounded
  727. ) -> EventStreamOf<Value, Error> {
  728. createStream(automaticallyCancelling: shouldAutomaticallyCancel,
  729. bufferingPolicy: bufferingPolicy,
  730. transform: { $0 }) { onEvent in
  731. request.streamDecodableEvents(Value.self,
  732. on: .streamCompletionQueue(forRequestID: request.id),
  733. using: decoder,
  734. handler: onEvent)
  735. }
  736. }
  737. public func streamingDecodable<Value: Decodable>(
  738. _ type: Value.Type = Value.self,
  739. automaticallyCancelling shouldAutomaticallyCancel: Bool = true,
  740. using decoder: DataDecoder = JSONDecoder(),
  741. bufferingPolicy: StreamOf<Value>.BufferingPolicy = .unbounded
  742. ) -> StreamOf<Value> {
  743. createStream(automaticallyCancelling: shouldAutomaticallyCancel,
  744. bufferingPolicy: bufferingPolicy,
  745. transform: { $0.message }) { onEvent in
  746. request.streamDecodableEvents(Value.self,
  747. on: .streamCompletionQueue(forRequestID: request.id),
  748. using: decoder,
  749. handler: onEvent)
  750. }
  751. }
  752. private func createStream<Success, Value, Failure: Error>(
  753. automaticallyCancelling shouldAutomaticallyCancel: Bool,
  754. bufferingPolicy: StreamOf<Value>.BufferingPolicy,
  755. transform: @escaping (WebSocketRequest.Event<Success, Failure>) -> Value?,
  756. forResponse onResponse: @escaping (@escaping (WebSocketRequest.Event<Success, Failure>) -> Void) -> Void
  757. ) -> StreamOf<Value> {
  758. StreamOf(bufferingPolicy: bufferingPolicy) {
  759. guard shouldAutomaticallyCancel,
  760. request.isInitialized || request.isResumed || request.isSuspended else { return }
  761. cancel()
  762. } builder: { continuation in
  763. onResponse { event in
  764. if let value = transform(event) {
  765. continuation.yield(value)
  766. }
  767. if case .completed = event.kind {
  768. continuation.finish()
  769. }
  770. }
  771. }
  772. }
  773. /// Send a `URLSessionWebSocketTask.Message`.
  774. ///
  775. /// - Parameter message: The `Message`.
  776. ///
  777. public func send(_ message: URLSessionWebSocketTask.Message) async throws {
  778. try await withCheckedThrowingContinuation { continuation in
  779. request.send(message, queue: .streamCompletionQueue(forRequestID: request.id)) { result in
  780. continuation.resume(with: result)
  781. }
  782. }
  783. }
  784. /// Close the underlying `WebSocketRequest`.
  785. public func close(sending closeCode: URLSessionWebSocketTask.CloseCode, reason: Data? = nil) {
  786. request.close(sending: closeCode, reason: reason)
  787. }
  788. /// Cancel the underlying `WebSocketRequest`.
  789. ///
  790. /// Cancellation will produce an `AFError.explicitlyCancelled` instance.
  791. public func cancel() {
  792. request.cancel()
  793. }
  794. /// Resume the underlying `WebSocketRequest`.
  795. public func resume() {
  796. request.resume()
  797. }
  798. /// Suspend the underlying `WebSocketRequest`.
  799. public func suspend() {
  800. request.suspend()
  801. }
  802. }
  803. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  804. extension WebSocketRequest {
  805. public func webSocketTask() -> WebSocketTask {
  806. WebSocketTask(request: self)
  807. }
  808. }
  809. #endif
  810. extension DispatchQueue {
  811. fileprivate static let singleEventQueue = DispatchQueue(label: "org.alamofire.concurrencySingleEventQueue",
  812. attributes: .concurrent)
  813. fileprivate static func streamCompletionQueue(forRequestID id: UUID) -> DispatchQueue {
  814. DispatchQueue(label: "org.alamofire.concurrencyStreamCompletionQueue-\(id)", target: .singleEventQueue)
  815. }
  816. }
  817. /// An asynchronous sequence generated from an underlying `AsyncStream`. Only produced by Alamofire.
  818. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  819. public struct StreamOf<Element>: AsyncSequence {
  820. public typealias AsyncIterator = Iterator
  821. public typealias BufferingPolicy = AsyncStream<Element>.Continuation.BufferingPolicy
  822. fileprivate typealias Continuation = AsyncStream<Element>.Continuation
  823. private let bufferingPolicy: BufferingPolicy
  824. private let onTermination: (() -> Void)?
  825. private let builder: (Continuation) -> Void
  826. fileprivate init(bufferingPolicy: BufferingPolicy = .unbounded,
  827. onTermination: (() -> Void)? = nil,
  828. builder: @escaping (Continuation) -> Void) {
  829. self.bufferingPolicy = bufferingPolicy
  830. self.onTermination = onTermination
  831. self.builder = builder
  832. }
  833. public func makeAsyncIterator() -> Iterator {
  834. var continuation: AsyncStream<Element>.Continuation?
  835. let stream = AsyncStream<Element>(bufferingPolicy: bufferingPolicy) { innerContinuation in
  836. continuation = innerContinuation
  837. builder(innerContinuation)
  838. }
  839. return Iterator(iterator: stream.makeAsyncIterator()) {
  840. continuation?.finish()
  841. onTermination?()
  842. }
  843. }
  844. public struct Iterator: AsyncIteratorProtocol {
  845. private final class Token {
  846. private let onDeinit: () -> Void
  847. init(onDeinit: @escaping () -> Void) {
  848. self.onDeinit = onDeinit
  849. }
  850. deinit {
  851. onDeinit()
  852. }
  853. }
  854. private var iterator: AsyncStream<Element>.AsyncIterator
  855. private let token: Token
  856. init(iterator: AsyncStream<Element>.AsyncIterator, onCancellation: @escaping () -> Void) {
  857. self.iterator = iterator
  858. token = Token(onDeinit: onCancellation)
  859. }
  860. public mutating func next() async -> Element? {
  861. await iterator.next()
  862. }
  863. }
  864. }
  865. #endif