SPB Git

Repository Public

HTTPTransport.swift 2.5 KB 54 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Networking/HTTPTransport.swift3// Description: The HTTP seam of the app: one protocol, the URLSession implementation used in production, and nothing else.4import Foundation56/// Everything the app sends goes through this protocol, so tests can stand in for the network without touching the7/// code under test. Production uses `URLSessionTransport` only.8public protocol HTTPTransport: Sendable {9    func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse)10    /// A response read line by line as it arrives (server-sent events).11    func lines(for request: URLRequest) async throws -> (AsyncThrowingStream<String, Error>, HTTPURLResponse)12}1314public final class URLSessionTransport: HTTPTransport {15    private let session: URLSession1617    public init(timeout: TimeInterval = 30) {18        let c = URLSessionConfiguration.ephemeral19        // The session credential is a Bearer token kept in the Keychain: no cookie jar, no shared cache on disk.20        c.httpCookieStorage = nil21        c.httpShouldSetCookies = false22        c.urlCache = nil23        c.requestCachePolicy = .reloadIgnoringLocalCacheData24        c.timeoutIntervalForRequest = timeout25        c.timeoutIntervalForResource = 60 * 60 * 626        c.waitsForConnectivity = false27        c.httpAdditionalHeaders = ["Accept": "application/json"]28        session = URLSession(configuration: c)29    }3031    public func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) {32        let (d, r) = try await session.data(for: request)33        guard let h = r as? HTTPURLResponse else { throw URLError(.badServerResponse) }34        return (d, h)35    }3637    public func lines(for request: URLRequest) async throws -> (AsyncThrowingStream<String, Error>, HTTPURLResponse) {38        var req = request39        req.timeoutInterval = 90   // the server sends a comment line every 20 s: silence for 90 s is a dead stream40        let (bytes, r) = try await session.bytes(for: req)41        guard let h = r as? HTTPURLResponse else { throw URLError(.badServerResponse) }42        let stream = AsyncThrowingStream<String, Error> { continuation in43            let task = Task {44                do {45                    for try await line in bytes.lines { continuation.yield(line) }46                    continuation.finish()47                } catch { continuation.finish(throwing: error) }48            }49            continuation.onTermination = { _ in task.cancel() }50        }51        return (stream, h)52    }53}54
Files main
Menu

Theme