SPB Git

Repository Public

HTTPByteStream.swift 3.5 KB 72 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Networking/HTTPByteStream.swift3// Description: One HTTP response read as it arrives (head, then body chunks), for downloads and streaming.4import Foundation56/// One HTTP response read as it arrives: the head first, then the body in chunks. Used by downloads and by the7/// streaming audio source, which both need byte ranges and must write as they receive.8public final class HTTPByteStream: NSObject, URLSessionDataDelegate, @unchecked Sendable {9    public struct Head: Sendable {10        public let status: Int11        public let headers: [String: String]12        public func header(_ name: String) -> String? { headers[name.lowercased()] }13    }1415    private let lock = NSLock()16    private var headContinuation: CheckedContinuation<Head, Error>?17    private var bodyContinuation: AsyncThrowingStream<Data, Error>.Continuation?18    private var session: URLSession?19    private var task: URLSessionDataTask?20    public let body: AsyncThrowingStream<Data, Error>2122    public override init() {23        var c: AsyncThrowingStream<Data, Error>.Continuation!24        body = AsyncThrowingStream(bufferingPolicy: .unbounded) { c = $0 }25        super.init()26        bodyContinuation = c27    }2829    /// Sends the request and returns when the response head is in. The body then flows through `body`.30    public func start(_ request: URLRequest) async throws -> Head {31        let config = URLSessionConfiguration.ephemeral32        config.httpCookieStorage = nil; config.httpShouldSetCookies = false; config.urlCache = nil33        config.timeoutIntervalForRequest = 30; config.waitsForConnectivity = false34        let s = URLSession(configuration: config, delegate: self, delegateQueue: nil)35        let t = s.dataTask(with: request)36        return try await withTaskCancellationHandler {37            try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Head, Error>) in38                lock.withLock { headContinuation = cont; session = s; task = t }39                t.resume()40            }41        } onCancel: { self.cancel() }42    }4344    public func cancel() {45        let t = lock.withLock { task }46        t?.cancel()47    }4849    public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse,50                           completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {51        let cont = lock.withLock { let c = headContinuation; headContinuation = nil; return c }52        if let http = response as? HTTPURLResponse {53            var headers: [String: String] = [:]54            for (k, v) in http.allHeaderFields { headers[String(describing: k).lowercased()] = String(describing: v) }55            cont?.resume(returning: Head(status: http.statusCode, headers: headers))56        } else { cont?.resume(throwing: APIError.invalidResponse) }57        completionHandler(.allow)58    }5960    public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {61        let c = lock.withLock { bodyContinuation }62        c?.yield(data)63    }6465    public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {66        let (head, bodyC) = lock.withLock { let h = headContinuation; headContinuation = nil; let b = bodyContinuation; bodyContinuation = nil; return (h, b) }67        if let error { head?.resume(throwing: error); bodyC?.finish(throwing: error) }68        else { head?.resume(throwing: APIError.invalidResponse); bodyC?.finish() }69        session.finishTasksAndInvalidate()70    }71}72
Files main
Menu

Theme