SPB Git

Repository Public

KitBridge.swift 3.3 KB 67 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: App/Next/KitBridge.swift3// Description: The seam between this app and the shared VQuantKit package: names, the transport adapter over the app's APIClient, and the cipher that seals the sync replica with the cache key.4import Foundation5import VQuantCore6import VQuantKit78/// Both modules export a `VQuantAPI`. Inside the app the unqualified name stays the 1.x client (every existing call9/// site keeps compiling); the kit's entry point is `VQNextAPI`.10typealias VQuantAPI = VQuantCore.VQuantAPI11typealias VQNextAPI = VQuantKit.VQuantAPI1213/// VQuantKit's network seam, served by the app's own `APIClient`: same base URL, same Keychain token, same14/// `X-VQ-Client` header, never an `Origin`. The kit reads statuses itself (409 bodies, `Retry-After`), so the15/// response is returned whatever its status; a 401 additionally runs the app's sign-out path.16struct MacVQTransport: VQTransport {17    let client: APIClient18    let http: HTTPTransport19    /// Called on a 401 answer to an authenticated request (the same handler the 1.x client uses).20    let onUnauthorized: @Sendable () -> Void2122    private func urlRequest(_ r: VQRequest) throws -> URLRequest {23        var q: [String: String?] = [:]24        for item in r.query { q[item.name] = item.value }25        var req = try client.request(HTTPMethod(rawValue: r.method.rawValue) ?? .get, r.path, query: q, accept: r.accept)26        if let body = r.body {27            req.httpBody = body28            // nil = JSON; the dataset upload of the research agent sends multipart/form-data with its own boundary29            req.setValue(r.contentType ?? "application/json", forHTTPHeaderField: "Content-Type")30        }31        req.timeoutInterval = r.timeout32        return req33    }3435    func send(_ r: VQRequest) async throws -> VQResponse {36        let (data, response) = try await http.data(for: try urlRequest(r))37        if response.statusCode == 401 { onUnauthorized() }38        return VQResponse(data: data, http: response)39    }4041    func stream(_ r: VQRequest) async throws -> VQByteStream {42        let (lines, response) = try await http.lines(for: try urlRequest(r))43        if response.statusCode == 401 { onUnauthorized() }44        // the app's reader yields lines: give each one back its line end (the kit's parser dispatches per `data:` line)45        let chunks = AsyncThrowingStream<Data, Error> { c in46            let task = Task {47                do { for try await l in lines { c.yield(Data((l + "\n").utf8)) }; c.finish() } catch { c.finish(throwing: error) }48            }49            c.onTermination = { _ in task.cancel() }50        }51        return VQByteStream(http: response, chunks: chunks)52    }53}5455/// Seals the sync replica with the key of the encrypted cache (AES-GCM, key in the Keychain): the replica is as56/// unreadable from a copy of the disk as everything else the app keeps from the server.57struct CacheCipher: VQSyncCipher {58    let cache: DiskCache59    func seal(_ plaintext: Data) throws -> Data { try cache.seal(plaintext, context: "vq-sync-replica") }60    func open(_ sealed: Data) throws -> Data { try cache.open(sealed, context: "vq-sync-replica") }61}6263extension VQError {64    /// A sentence for a toast or a banner.65    var userMessage: String { errorDescription ?? "The server refused the request." }66}67
Files main
Menu

Theme