SPB Git

Repository Public

NextTransport.swift 4.0 KB 91 lines swift

1//2//  VQuant iOS3//  File: VQuant/Next/NextTransport.swift4//  Description: Adapts the app's APIClient to the VQuantKit transport seam (same bearer session, same client header,5//               same sign-out path on a dead session) and seals the sync replica with the app's cache key.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import CryptoKit12import Foundation13import VQuantKit1415/// The kit's entry point. The app's own `VQuantAPI` (Core) keeps the 1.0 routes; this one carries `/api/v2`.16typealias KitAPI = VQuantKit.VQuantAPI17/// A panel of a synced workspace (VQuantUI also has a `VQPanel`, a surface view).18typealias KitPanel = VQuantKit.VQPanel1920struct IOSVQTransport: VQTransport {21    let client: APIClient2223    /// `VQRequest.path` is percent-encoded per segment; `APIClient.urlRequest` encodes the path again, so it is handed24    /// the decoded path (`/api/v2/data/bars/^GSPC` goes out as `%5EGSPC`, checked by `NextTransportTests`).25    func urlRequest(_ r: VQRequest) throws -> URLRequest {26        var a = APIRequest(method: r.method.rawValue, path: r.path.removingPercentEncoding ?? r.path,27                           query: Dictionary(r.query.map { ($0.name, $0.value) }, uniquingKeysWith: { $1 }),28                           body: r.body, timeout: r.timeout)29        a.contentType = r.contentType ?? "application/json"     // multipart for the dataset upload30        a.accept = r.accept ?? "application/json"31        return try client.urlRequest(a)32    }3334    func send(_ r: VQRequest) async throws -> VQResponse {35        let (data, response) = try await client.session.data(for: try urlRequest(r))36        guard let http = response as? HTTPURLResponse else { throw URLError(.badServerResponse) }37        if http.statusCode == 401 { try? client.check(response, data: data, hadToken: true) }   // runs the app's sign-out handler on `x-vq-locked`38        return VQResponse(data: data, http: http)39    }4041    func stream(_ r: VQRequest) async throws -> VQByteStream {42        var req = try urlRequest(r)43        req.timeoutInterval = 90                              // the server pings every 25 s44        let (bytes, response) = try await client.session.bytes(for: req)45        guard let http = response as? HTTPURLResponse else { throw URLError(.badServerResponse) }46        if http.statusCode == 401 { try? client.check(response, data: Data(), hadToken: true) }47        let chunks = AsyncThrowingStream<Data, Error> { c in48            let task = Task {49                do {50                    var line = Data()51                    for try await b in bytes { line.append(b); if b == 0x0A { c.yield(line); line.removeAll(keepingCapacity: true) } }52                    if !line.isEmpty { c.yield(line) }53                    c.finish()54                } catch { c.finish(throwing: error) }55            }56            c.onTermination = { _ in task.cancel() }57        }58        return VQByteStream(http: http, chunks: chunks)59    }60}6162/// Seals the sync replica with the key that already protects the disk cache (AES-256-GCM, key in the Keychain,63/// destroyed at sign-out).64struct AppSyncCipher: VQSyncCipher {65    let keys: CacheKeyProvider66    struct Unreadable: Error {}67    func seal(_ plaintext: Data) throws -> Data {68        guard let combined = try AES.GCM.seal(plaintext, using: keys.key()).combined else { throw Unreadable() }69        return combined70    }71    func open(_ sealed: Data) throws -> Data {72        try AES.GCM.open(try AES.GCM.SealedBox(combined: sealed), using: keys.key())73    }74}7576extension VQError {77    /// The app's wording for a kit failure (French, like the rest of the interface).78    var userMessage: String {79        switch kind {80        case .network: return "Le serveur VQuant est injoignable."81        case .rateLimited: return "Trop de requêtes. Réessayez dans un instant."82        default: return message.isEmpty ? "Action impossible (\(status))." : message83        }84    }85}8687func nextMessage(_ error: Error) -> String {88    if let e = error as? VQError { return e.userMessage }89    return APIError.from(error).message90}91
Files main
Menu

Theme