SPB Git

Repository Public

HTTPTransport.swift 7.2 KB 130 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Core/Networking/HTTPTransport.swift3// Description: HTTP transport abstraction and its URLSession implementation (streaming bodies, upload progress, no implicit cookies or caches).4import Foundation56public struct HTTPResponse: Sendable {7    public let status: Int8    public let headers: [String: String]9    public let url: URL?10    public init(status: Int, headers: [String: String], url: URL? = nil) {11        self.status = status; self.url = url12        self.headers = Dictionary(headers.map { ($0.key.lowercased(), $0.value) }, uniquingKeysWith: { a, _ in a })13    }14    public func header(_ name: String) -> String? { headers[name.lowercased()] }15    public var contentType: String { header("content-type") ?? "" }16    public var isJSON: Bool { contentType.contains("application/json") }17}1819/// The only door to the network. Tests replace it with a scripted transport.20public protocol HTTPTransport: Sendable {21    func send(_ request: URLRequest) async throws -> (Data, HTTPResponse)22    /// Response headers first, then the body as it arrives. Cancelling the consuming task cancels the request.23    func stream(_ request: URLRequest) async throws -> (HTTPResponse, AsyncThrowingStream<Data, Error>)24    func upload(_ request: URLRequest, body: Data, progress: @escaping @Sendable (Double) -> Void) async throws -> (Data, HTTPResponse)25}2627/// URLSession transport. Ephemeral: no cookie jar, no URL cache, no credential storage on disk — the session token is28/// managed explicitly by `CookieJar` and kept in the Keychain. TLS validation is the system default (never weakened).29public final class URLSessionTransport: NSObject, HTTPTransport, URLSessionDataDelegate, @unchecked Sendable {30    private var session: URLSession!31    private let lock = NSLock()32    private struct StreamState { var head: CheckedContinuation<HTTPResponse, Error>?; var body: AsyncThrowingStream<Data, Error>.Continuation }33    private var streams: [Int: StreamState] = [:]34    private var progress: [Int: @Sendable (Double) -> Void] = [:]3536    public init(timeout: TimeInterval = 60) {37        super.init()38        let c = URLSessionConfiguration.ephemeral39        c.httpCookieStorage = nil; c.httpShouldSetCookies = false; c.httpCookieAcceptPolicy = .never40        c.urlCache = nil; c.urlCredentialStorage = nil; c.requestCachePolicy = .reloadIgnoringLocalCacheData41        c.timeoutIntervalForRequest = timeout; c.timeoutIntervalForResource = 30 * 6042        c.waitsForConnectivity = false43        c.tlsMinimumSupportedProtocolVersion = .TLSv1244        c.httpAdditionalHeaders = ["Accept-Language": "fr-CA,fr;q=0.9,en;q=0.8"]45        session = URLSession(configuration: c, delegate: self, delegateQueue: nil)46    }4748    deinit { session.invalidateAndCancel() }4950    private static func response(_ r: URLResponse?) throws -> HTTPResponse {51        guard let h = r as? HTTPURLResponse else { throw URLError(.badServerResponse) }52        var headers: [String: String] = [:]53        for (k, v) in h.allHeaderFields { if let k = k as? String, let v = v as? String { headers[k] = v } }54        return HTTPResponse(status: h.statusCode, headers: headers, url: h.url)55    }5657    public func send(_ request: URLRequest) async throws -> (Data, HTTPResponse) {58        let (data, resp) = try await session.data(for: request)59        return (data, try Self.response(resp))60    }6162    public func upload(_ request: URLRequest, body: Data, progress: @escaping @Sendable (Double) -> Void) async throws -> (Data, HTTPResponse) {63        let delegate = UploadProgress(progress)64        let (data, resp) = try await session.upload(for: request, from: body, delegate: delegate)65        return (data, try Self.response(resp))66    }6768    public func stream(_ request: URLRequest) async throws -> (HTTPResponse, AsyncThrowingStream<Data, Error>) {69        let task = session.dataTask(with: request)70        let (body, continuation) = AsyncThrowingStream<Data, Error>.makeStream(bufferingPolicy: .unbounded)71        continuation.onTermination = { @Sendable _ in task.cancel() }72        let head: HTTPResponse = try await withTaskCancellationHandler {73            try await withCheckedThrowingContinuation { (cc: CheckedContinuation<HTTPResponse, Error>) in74                lock.withLock { streams[task.taskIdentifier] = StreamState(head: cc, body: continuation) }75                task.resume()76            }77        } onCancel: { task.cancel() }78        return (head, body)79    }8081    // MARK: URLSessionDataDelegate8283    public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {84        let head = lock.withLock { () -> CheckedContinuation<HTTPResponse, Error>? in85            let h = streams[dataTask.taskIdentifier]?.head; streams[dataTask.taskIdentifier]?.head = nil; return h86        }87        do { head?.resume(returning: try Self.response(response)); completionHandler(.allow) }88        catch { head?.resume(throwing: error); completionHandler(.cancel) }89    }9091    public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {92        let body = lock.withLock { streams[dataTask.taskIdentifier]?.body }93        body?.yield(data)94    }9596    public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {97        let state = lock.withLock { streams.removeValue(forKey: task.taskIdentifier) }98        guard let state else { return }99        if let head = state.head { head.resume(throwing: error ?? URLError(.badServerResponse)) }100        if let error { state.body.finish(throwing: error) } else { state.body.finish() }101    }102}103104private final class UploadProgress: NSObject, URLSessionTaskDelegate, Sendable {105    let report: @Sendable (Double) -> Void106    init(_ report: @escaping @Sendable (Double) -> Void) { self.report = report }107    func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {108        guard totalBytesExpectedToSend > 0 else { return }109        report(min(0.99, Double(totalBytesSent) / Double(totalBytesExpectedToSend)))110    }111}112113/// multipart/form-data body builder (uploads, speech-to-text).114public struct MultipartForm: Sendable {115    public let boundary: String116    private var body = Data()117    public init(boundary: String = "spchat-" + UUID().uuidString) { self.boundary = boundary }118119    public mutating func add(field name: String, value: String) {120        body.append(Data("--\(boundary)\r\nContent-Disposition: form-data; name=\"\(name)\"\r\n\r\n\(value)\r\n".utf8))121    }122    public mutating func add(file name: String, filename: String, mime: String, data: Data) {123        let safe = filename.replacingOccurrences(of: "\"", with: "'").replacingOccurrences(of: "\r", with: " ").replacingOccurrences(of: "\n", with: " ")124        body.append(Data("--\(boundary)\r\nContent-Disposition: form-data; name=\"\(name)\"; filename=\"\(safe)\"\r\nContent-Type: \(mime)\r\n\r\n".utf8))125        body.append(data); body.append(Data("\r\n".utf8))126    }127    public var contentType: String { "multipart/form-data; boundary=\(boundary)" }128    public var data: Data { var d = body; d.append(Data("--\(boundary)--\r\n".utf8)); return d }129}130
Files main
Menu

Theme