SPB Git

Repository Public

VQURLSessionTransport.swift 4.4 KB 87 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/Core/VQURLSessionTransport.swift3// Description: A ready-made `VQTransport` on URLSession, for apps that would rather hand the package a token provider4//              than write an adapter (also used by the package's live tests).5import Foundation67public final class VQURLSessionTransport: VQTransport {8    public let baseURL: URL9    /// Value of `X-VQ-Client`: `vquant-macos/<version>` or `vquant-ios/<version> (<build>)`.10    public let clientHeader: String11    private let token: @Sendable () -> String?12    private let onLocked: (@Sendable () -> Void)?13    private let session: URLSession1415    /// - Parameters:16    ///   - token: reads the device token (`vqn_…`) from wherever the app keeps it (Keychain). Called per request.17    ///   - onLocked: called when the server answers 401 with `x-vq-locked: 1` (the session of this device is dead).18    public init(baseURL: URL, clientHeader: String, token: @escaping @Sendable () -> String?, onLocked: (@Sendable () -> Void)? = nil) {19        self.baseURL = baseURL; self.clientHeader = clientHeader; self.token = token; self.onLocked = onLocked20        let c = URLSessionConfiguration.ephemeral21        c.httpCookieStorage = nil22        c.httpShouldSetCookies = false23        c.urlCache = nil24        c.requestCachePolicy = .reloadIgnoringLocalCacheData25        c.timeoutIntervalForResource = 60 * 60 * 626        c.waitsForConnectivity = false27        session = URLSession(configuration: c)28    }2930    public func urlRequest(_ r: VQRequest) throws -> URLRequest {31        guard var comps = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) else { throw URLError(.badURL) }32        let prefix = comps.percentEncodedPath.hasSuffix("/") ? String(comps.percentEncodedPath.dropLast()) : comps.percentEncodedPath33        comps.percentEncodedPath = prefix + r.path34        if !r.query.isEmpty {35            comps.queryItems = r.query.map { URLQueryItem(name: $0.name, value: $0.value) }36            // "+" must not reach the server as a space37            comps.percentEncodedQuery = comps.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")38        }39        guard let url = comps.url else { throw URLError(.badURL) }40        var req = URLRequest(url: url)41        req.httpMethod = r.method.rawValue42        req.timeoutInterval = r.timeout43        req.setValue(clientHeader, forHTTPHeaderField: "X-VQ-Client")44        req.setValue(r.accept ?? "application/json", forHTTPHeaderField: "Accept")45        if let t = token() { req.setValue("Bearer \(t)", forHTTPHeaderField: "Authorization") }46        if let body = r.body {47            req.setValue(r.contentType ?? "application/json", forHTTPHeaderField: "Content-Type")48            req.httpBody = body49        }50        return req51    }5253    public func send(_ request: VQRequest) async throws -> VQResponse {54        let (data, response) = try await session.data(for: try urlRequest(request))55        guard let http = response as? HTTPURLResponse else { throw URLError(.badServerResponse) }56        noteLocked(http)57        return VQResponse(data: data, http: http)58    }5960    public func stream(_ request: VQRequest) async throws -> VQByteStream {61        var req = try urlRequest(request)62        req.timeoutInterval = 90   // the server sends a heartbeat every 25 s: 90 s of silence is a dead stream63        let (bytes, response) = try await session.bytes(for: req)64        guard let http = response as? HTTPURLResponse else { throw URLError(.badServerResponse) }65        noteLocked(http)66        let chunks = AsyncThrowingStream<Data, Error> { continuation in67            let task = Task {68                do {69                    var buffer = Data()70                    for try await byte in bytes {71                        buffer.append(byte)72                        if byte == 0x0A { continuation.yield(buffer); buffer.removeAll(keepingCapacity: true) }73                    }74                    if !buffer.isEmpty { continuation.yield(buffer) }75                    continuation.finish()76                } catch { continuation.finish(throwing: error) }77            }78            continuation.onTermination = { _ in task.cancel() }79        }80        return VQByteStream(http: http, chunks: chunks)81    }8283    private func noteLocked(_ http: HTTPURLResponse) {84        if http.statusCode == 401, http.value(forHTTPHeaderField: "x-vq-locked") == "1" { onLocked?() }85    }86}87
Files main
Menu

Theme