DataStreamRequest.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. //
  2. // DataStreamRequest.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 streams HTTP response `Data` through a `Handler` closure.
  26. public final class DataStreamRequest: Request, @unchecked Sendable {
  27. /// Closure type handling `DataStreamRequest.Stream` values.
  28. public typealias Handler<Success, Failure: Error> = @Sendable (Stream<Success, Failure>) throws -> Void
  29. /// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used
  30. /// to stop the stream at any time.
  31. public struct Stream<Success, Failure: Error>: Sendable where Success: Sendable, Failure: Sendable {
  32. /// Latest `Event` from the stream.
  33. public let event: Event<Success, Failure>
  34. /// Token used to cancel the stream.
  35. public let token: CancellationToken
  36. /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
  37. public func cancel() {
  38. token.cancel()
  39. }
  40. }
  41. /// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed
  42. /// `Data` or the completion of the stream.
  43. public enum Event<Success, Failure: Error>: Sendable where Success: Sendable, Failure: Sendable {
  44. /// Output produced every time the instance receives additional `Data`. The associated value contains the
  45. /// `Result` of processing the incoming `Data`.
  46. case stream(Result<Success, Failure>)
  47. /// Output produced when the instance has completed, whether due to stream end, cancellation, or an error.
  48. /// Associated `Completion` value contains the final state.
  49. case complete(Completion)
  50. }
  51. /// Value containing the state of a `DataStreamRequest` when the stream was completed.
  52. public struct Completion: Sendable {
  53. /// Last `URLRequest` issued by the instance.
  54. public let request: URLRequest?
  55. /// Last `HTTPURLResponse` received by the instance.
  56. public let response: HTTPURLResponse?
  57. /// Last `URLSessionTaskMetrics` produced for the instance.
  58. public let metrics: URLSessionTaskMetrics?
  59. /// `AFError` produced for the instance, if any.
  60. public let error: AFError?
  61. }
  62. /// Type used to cancel an ongoing stream.
  63. public struct CancellationToken: Sendable {
  64. weak var request: DataStreamRequest?
  65. init(_ request: DataStreamRequest) {
  66. self.request = request
  67. }
  68. /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
  69. public func cancel() {
  70. request?.cancel()
  71. }
  72. }
  73. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  74. public let convertible: any URLRequestConvertible
  75. /// Whether or not the instance will be cancelled if stream parsing encounters an error.
  76. public let automaticallyCancelOnStreamError: Bool
  77. /// Internal mutable state specific to this type.
  78. struct StreamMutableState {
  79. /// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called.
  80. var outputStream: OutputStream?
  81. /// Stream closures called as `Data` is received.
  82. var streams: [@Sendable (_ data: Data) -> Void] = []
  83. /// Number of currently executing streams. Used to ensure completions are only fired after all streams are
  84. /// enqueued.
  85. var numberOfExecutingStreams = 0
  86. /// Completion calls enqueued while streams are still executing.
  87. var enqueuedCompletionEvents: [@Sendable () -> Void] = []
  88. /// Handler for any `HTTPURLResponse`s received.
  89. var httpResponseHandler: (queue: DispatchQueue,
  90. handler: @Sendable (_ response: HTTPURLResponse,
  91. _ completionHandler: @escaping @Sendable (ResponseDisposition) -> Void) -> Void)?
  92. }
  93. let streamMutableState = Protected(StreamMutableState())
  94. /// Creates a `DataStreamRequest` using the provided parameters.
  95. ///
  96. /// - Parameters:
  97. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()`
  98. /// by default.
  99. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this
  100. /// instance.
  101. /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error`
  102. /// is thrown while serializing stream `Data`.
  103. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  104. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default
  105. /// targets
  106. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  107. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  108. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  109. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by
  110. /// the `Request`.
  111. init(id: UUID = UUID(),
  112. convertible: any URLRequestConvertible,
  113. automaticallyCancelOnStreamError: Bool,
  114. underlyingQueue: DispatchQueue,
  115. serializationQueue: DispatchQueue,
  116. eventMonitor: (any EventMonitor)?,
  117. interceptor: (any RequestInterceptor)?,
  118. delegate: any RequestDelegate) {
  119. self.convertible = convertible
  120. self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError
  121. super.init(id: id,
  122. underlyingQueue: underlyingQueue,
  123. serializationQueue: serializationQueue,
  124. eventMonitor: eventMonitor,
  125. interceptor: interceptor,
  126. delegate: delegate)
  127. }
  128. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  129. let copiedRequest = request
  130. return session.dataTask(with: copiedRequest)
  131. }
  132. override func finish(error: AFError? = nil) {
  133. streamMutableState.write { state in
  134. state.outputStream?.close()
  135. }
  136. super.finish(error: error)
  137. }
  138. func didReceive(data: Data) {
  139. streamMutableState.write { state in
  140. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  141. if let stream = state.outputStream {
  142. underlyingQueue.async {
  143. var bytes = Array(data)
  144. stream.write(&bytes, maxLength: bytes.count)
  145. }
  146. }
  147. #endif
  148. state.numberOfExecutingStreams += state.streams.count
  149. underlyingQueue.async { [streams = state.streams] in streams.forEach { $0(data) } }
  150. }
  151. }
  152. func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {
  153. streamMutableState.read { dataMutableState in
  154. guard let httpResponseHandler = dataMutableState.httpResponseHandler else {
  155. underlyingQueue.async { completionHandler(.allow) }
  156. return
  157. }
  158. httpResponseHandler.queue.async {
  159. httpResponseHandler.handler(response) { disposition in
  160. if disposition == .cancel {
  161. self.mutableState.write { mutableState in
  162. mutableState.state = .cancelled
  163. mutableState.error = mutableState.error ?? AFError.explicitlyCancelled
  164. }
  165. }
  166. self.underlyingQueue.async {
  167. completionHandler(disposition.sessionDisposition)
  168. }
  169. }
  170. }
  171. }
  172. }
  173. /// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure.
  174. ///
  175. /// - Parameter validation: `Validation` closure used to validate the request and response.
  176. ///
  177. /// - Returns: The `DataStreamRequest`.
  178. @discardableResult
  179. public func validate(_ validation: @escaping Validation) -> Self {
  180. let validator: @Sendable () -> Void = { [unowned self] in
  181. guard error == nil, let response else { return }
  182. let result = validation(request, response)
  183. if case let .failure(error) = result {
  184. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  185. }
  186. eventMonitor?.request(self,
  187. didValidateRequest: request,
  188. response: response,
  189. withResult: result)
  190. }
  191. validators.write { $0.append(validator) }
  192. return self
  193. }
  194. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  195. /// Produces an `InputStream` that receives the `Data` received by the instance.
  196. ///
  197. /// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`.
  198. /// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or
  199. /// not the creating session has `startRequestsImmediately` set to `true`.
  200. ///
  201. /// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`.
  202. ///
  203. /// - Returns: The `InputStream` bound to the internal `OutboundStream`.
  204. public func asInputStream(bufferSize: Int = 1024) -> InputStream? {
  205. defer { resume() }
  206. var inputStream: InputStream?
  207. streamMutableState.write { state in
  208. Foundation.Stream.getBoundStreams(withBufferSize: bufferSize,
  209. inputStream: &inputStream,
  210. outputStream: &state.outputStream)
  211. state.outputStream?.open()
  212. }
  213. return inputStream
  214. }
  215. #endif
  216. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion
  217. /// handler to return a `ResponseDisposition` value.
  218. ///
  219. /// - Parameters:
  220. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  221. /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided
  222. /// MUST be called, otherwise the request will never complete.
  223. ///
  224. /// - Returns: The instance.
  225. @_disfavoredOverload
  226. @preconcurrency
  227. @discardableResult
  228. public func onHTTPResponse(
  229. on queue: DispatchQueue = .main,
  230. perform handler: @escaping @Sendable (_ response: HTTPURLResponse,
  231. _ completionHandler: @escaping @Sendable (ResponseDisposition) -> Void) -> Void
  232. ) -> Self {
  233. streamMutableState.write { mutableState in
  234. mutableState.httpResponseHandler = (queue, handler)
  235. }
  236. return self
  237. }
  238. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`.
  239. ///
  240. /// - Parameters:
  241. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  242. /// - handler: Closure called when the instance produces an `HTTPURLResponse`.
  243. ///
  244. /// - Returns: The instance.
  245. @preconcurrency
  246. @discardableResult
  247. public func onHTTPResponse(on queue: DispatchQueue = .main,
  248. perform handler: @escaping @Sendable (HTTPURLResponse) -> Void) -> Self {
  249. onHTTPResponse(on: queue) { response, completionHandler in
  250. handler(response)
  251. completionHandler(.allow)
  252. }
  253. return self
  254. }
  255. func capturingError(from closure: () throws -> Void) {
  256. do {
  257. try closure()
  258. } catch {
  259. self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
  260. cancel()
  261. }
  262. }
  263. func appendStreamCompletion<Success, Failure>(on queue: DispatchQueue,
  264. stream: @escaping Handler<Success, Failure>) where Success: Sendable, Failure: Sendable {
  265. appendResponseSerializer {
  266. self.underlyingQueue.async {
  267. self.responseSerializerDidComplete {
  268. self.streamMutableState.write { state in
  269. guard state.numberOfExecutingStreams == 0 else {
  270. state.enqueuedCompletionEvents.append {
  271. self.enqueueCompletion(on: queue, stream: stream)
  272. }
  273. return
  274. }
  275. self.enqueueCompletion(on: queue, stream: stream)
  276. }
  277. }
  278. }
  279. }
  280. }
  281. func enqueueCompletion<Success, Failure>(on queue: DispatchQueue,
  282. stream: @escaping Handler<Success, Failure>) where Success: Sendable, Failure: Sendable {
  283. queue.async {
  284. do {
  285. let completion = Completion(request: self.request,
  286. response: self.response,
  287. metrics: self.metrics,
  288. error: self.error)
  289. try stream(.init(event: .complete(completion), token: .init(self)))
  290. } catch {
  291. // Ignore error, as errors on Completion can't be handled anyway.
  292. }
  293. }
  294. }
  295. // MARK: Response Serialization
  296. /// Adds a `StreamHandler` which performs no parsing on incoming `Data`.
  297. ///
  298. /// - Parameters:
  299. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  300. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  301. ///
  302. /// - Returns: The `DataStreamRequest`.
  303. @preconcurrency
  304. @discardableResult
  305. public func responseStream(on queue: DispatchQueue = .main, stream: @escaping Handler<Data, Never>) -> Self {
  306. let parser = { @Sendable [unowned self] (data: Data) in
  307. queue.async {
  308. self.capturingError {
  309. try stream(.init(event: .stream(.success(data)), token: .init(self)))
  310. }
  311. self.updateAndCompleteIfPossible()
  312. }
  313. }
  314. streamMutableState.write { $0.streams.append(parser) }
  315. appendStreamCompletion(on: queue, stream: stream)
  316. return self
  317. }
  318. /// Adds a `StreamHandler` which uses the provided `DataStreamSerializer` to process incoming `Data`.
  319. ///
  320. /// - Parameters:
  321. /// - serializer: `DataStreamSerializer` used to process incoming `Data`. Its work is done on the `serializationQueue`.
  322. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  323. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  324. ///
  325. /// - Returns: The `DataStreamRequest`.
  326. @preconcurrency
  327. @discardableResult
  328. public func responseStream<Serializer: DataStreamSerializer>(using serializer: Serializer,
  329. on queue: DispatchQueue = .main,
  330. stream: @escaping Handler<Serializer.SerializedObject, AFError>) -> Self {
  331. let parser = { @Sendable [unowned self] (data: Data) in
  332. serializationQueue.async {
  333. // Start work on serialization queue.
  334. let result = Result { try serializer.serialize(data) }
  335. .mapError { $0.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: $0))) }
  336. // End work on serialization queue.
  337. self.underlyingQueue.async {
  338. self.eventMonitor?.request(self, didParseStream: result)
  339. if result.isFailure, self.automaticallyCancelOnStreamError {
  340. self.cancel()
  341. }
  342. queue.async {
  343. self.capturingError {
  344. try stream(.init(event: .stream(result), token: .init(self)))
  345. }
  346. self.updateAndCompleteIfPossible()
  347. }
  348. }
  349. }
  350. }
  351. streamMutableState.write { $0.streams.append(parser) }
  352. appendStreamCompletion(on: queue, stream: stream)
  353. return self
  354. }
  355. /// Adds a `StreamHandler` which parses incoming `Data` as a UTF8 `String`.
  356. ///
  357. /// - Parameters:
  358. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  359. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  360. ///
  361. /// - Returns: The `DataStreamRequest`.
  362. @preconcurrency
  363. @discardableResult
  364. public func responseStreamString(on queue: DispatchQueue = .main,
  365. stream: @escaping Handler<String, Never>) -> Self {
  366. let parser = { @Sendable [unowned self] (data: Data) in
  367. serializationQueue.async {
  368. // Start work on serialization queue.
  369. let string = String(decoding: data, as: UTF8.self)
  370. // End work on serialization queue.
  371. self.underlyingQueue.async {
  372. self.eventMonitor?.request(self, didParseStream: .success(string))
  373. queue.async {
  374. self.capturingError {
  375. try stream(.init(event: .stream(.success(string)), token: .init(self)))
  376. }
  377. self.updateAndCompleteIfPossible()
  378. }
  379. }
  380. }
  381. }
  382. streamMutableState.write { $0.streams.append(parser) }
  383. appendStreamCompletion(on: queue, stream: stream)
  384. return self
  385. }
  386. private func updateAndCompleteIfPossible() {
  387. streamMutableState.write { state in
  388. state.numberOfExecutingStreams -= 1
  389. guard state.numberOfExecutingStreams == 0, !state.enqueuedCompletionEvents.isEmpty else { return }
  390. let completionEvents = state.enqueuedCompletionEvents
  391. self.underlyingQueue.async { completionEvents.forEach { $0() } }
  392. state.enqueuedCompletionEvents.removeAll()
  393. }
  394. }
  395. /// Adds a `StreamHandler` which parses incoming `Data` using the provided `DataDecoder`.
  396. ///
  397. /// - Parameters:
  398. /// - type: `Decodable` type to parse incoming `Data` into.
  399. /// - queue: `DispatchQueue` on which to perform `StreamHandler` closure.
  400. /// - decoder: `DataDecoder` used to decode the incoming `Data`.
  401. /// - preprocessor: `DataPreprocessor` used to process the incoming `Data` before it's passed to the `decoder`.
  402. /// - stream: `StreamHandler` closure called as `Data` is received. May be called multiple times.
  403. ///
  404. /// - Returns: The `DataStreamRequest`.
  405. @preconcurrency
  406. @discardableResult
  407. public func responseStreamDecodable<T: Decodable>(of type: T.Type = T.self,
  408. on queue: DispatchQueue = .main,
  409. using decoder: any DataDecoder = JSONDecoder(),
  410. preprocessor: any DataPreprocessor = PassthroughPreprocessor(),
  411. stream: @escaping Handler<T, AFError>) -> Self where T: Sendable {
  412. responseStream(using: DecodableStreamSerializer<T>(decoder: decoder, dataPreprocessor: preprocessor),
  413. on: queue,
  414. stream: stream)
  415. }
  416. }
  417. extension DataStreamRequest.Stream {
  418. /// Incoming `Result` values from `Event.stream`.
  419. public var result: Result<Success, Failure>? {
  420. guard case let .stream(result) = event else { return nil }
  421. return result
  422. }
  423. /// `Success` value of the instance, if any.
  424. public var value: Success? {
  425. guard case let .success(value) = result else { return nil }
  426. return value
  427. }
  428. /// `Failure` value of the instance, if any.
  429. public var error: Failure? {
  430. guard case let .failure(error) = result else { return nil }
  431. return error
  432. }
  433. /// `Completion` value of the instance, if any.
  434. public var completion: DataStreamRequest.Completion? {
  435. guard case let .complete(completion) = event else { return nil }
  436. return completion
  437. }
  438. }
  439. // MARK: - Serialization
  440. /// A type which can serialize incoming `Data`.
  441. public protocol DataStreamSerializer: Sendable {
  442. /// Type produced from the serialized `Data`.
  443. associatedtype SerializedObject: Sendable
  444. /// Serializes incoming `Data` into a `SerializedObject` value.
  445. ///
  446. /// - Parameter data: `Data` to be serialized.
  447. ///
  448. /// - Throws: Any error produced during serialization.
  449. func serialize(_ data: Data) throws -> SerializedObject
  450. }
  451. /// `DataStreamSerializer` which uses the provided `DataPreprocessor` and `DataDecoder` to serialize the incoming `Data`.
  452. public struct DecodableStreamSerializer<T: Decodable>: DataStreamSerializer where T: Sendable {
  453. /// `DataDecoder` used to decode incoming `Data`.
  454. public let decoder: any DataDecoder
  455. /// `DataPreprocessor` incoming `Data` is passed through before being passed to the `DataDecoder`.
  456. public let dataPreprocessor: any DataPreprocessor
  457. /// Creates an instance with the provided `DataDecoder` and `DataPreprocessor`.
  458. /// - Parameters:
  459. /// - decoder: ` DataDecoder` used to decode incoming `Data`. `JSONDecoder()` by default.
  460. /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the
  461. /// `decoder`. `PassthroughPreprocessor()` by default.
  462. public init(decoder: any DataDecoder = JSONDecoder(), dataPreprocessor: any DataPreprocessor = PassthroughPreprocessor()) {
  463. self.decoder = decoder
  464. self.dataPreprocessor = dataPreprocessor
  465. }
  466. public func serialize(_ data: Data) throws -> T {
  467. let processedData = try dataPreprocessor.preprocess(data)
  468. do {
  469. return try decoder.decode(T.self, from: processedData)
  470. } catch {
  471. throw AFError.responseSerializationFailed(reason: .decodingFailed(error: error))
  472. }
  473. }
  474. }
  475. /// `DataStreamSerializer` which performs no serialization on incoming `Data`.
  476. public struct PassthroughStreamSerializer: DataStreamSerializer {
  477. /// Creates an instance.
  478. public init() {}
  479. public func serialize(_ data: Data) throws -> Data { data }
  480. }
  481. /// `DataStreamSerializer` which serializes incoming stream `Data` into `UTF8`-decoded `String` values.
  482. public struct StringStreamSerializer: DataStreamSerializer {
  483. /// Creates an instance.
  484. public init() {}
  485. public func serialize(_ data: Data) throws -> String {
  486. String(decoding: data, as: UTF8.self)
  487. }
  488. }
  489. extension DataStreamSerializer {
  490. /// Creates a `DecodableStreamSerializer` instance with the provided `DataDecoder` and `DataPreprocessor`.
  491. ///
  492. /// - Parameters:
  493. /// - type: `Decodable` type to decode from stream data.
  494. /// - decoder: ` DataDecoder` used to decode incoming `Data`. `JSONDecoder()` by default.
  495. /// - dataPreprocessor: `DataPreprocessor` used to process incoming `Data` before it's passed through the
  496. /// `decoder`. `PassthroughPreprocessor()` by default.
  497. public static func decodable<T: Decodable>(of type: T.Type,
  498. decoder: any DataDecoder = JSONDecoder(),
  499. dataPreprocessor: any DataPreprocessor = PassthroughPreprocessor()) -> Self where Self == DecodableStreamSerializer<T> {
  500. DecodableStreamSerializer<T>(decoder: decoder, dataPreprocessor: dataPreprocessor)
  501. }
  502. }
  503. extension DataStreamSerializer where Self == PassthroughStreamSerializer {
  504. /// Provides a `PassthroughStreamSerializer` instance.
  505. public static var passthrough: PassthroughStreamSerializer { PassthroughStreamSerializer() }
  506. }
  507. extension DataStreamSerializer where Self == StringStreamSerializer {
  508. /// Provides a `StringStreamSerializer` instance.
  509. public static var string: StringStreamSerializer { StringStreamSerializer() }
  510. }