Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Networking/APIClient.swift3// Description: Authenticated JSON client of the VQuant backend: request building, the device token, and one error vocabulary.4import Foundation5import os67public struct APIError: Error, Sendable, Equatable, LocalizedError {8 public enum Kind: Sendable, Equatable {9 /// no route to the server (offline, DNS, TLS, timeout)10 case network11 /// the server no longer accepts this device (signed out, revoked, expired)12 case unauthorized13 /// a fresh passkey check is required for this operation14 case reauthRequired15 case forbidden, notFound, conflict, rateLimited, gone16 /// the request was understood and refused (validation)17 case rejected18 case server19 /// the body is not what this client version understands20 case decoding21 }22 public let kind: Kind23 public let status: Int24 public let message: String25 public init(_ kind: Kind, status: Int = 0, _ message: String) { self.kind = kind; self.status = status; self.message = message }26 public var errorDescription: String? { message }27 public var isOffline: Bool { kind == .network }28}2930public enum HTTPMethod: String, Sendable { case get = "GET", post = "POST", put = "PUT", patch = "PATCH", delete = "DELETE" }3132public struct ClientIdentity: Sendable, Equatable {33 public var version: String34 public var build: String35 public var deviceName: String36 public init(version: String, build: String, deviceName: String) { self.version = version; self.build = build; self.deviceName = deviceName }37 /// The value of X-VQ-Client. The server refuses native calls without it.38 public var header: String { "vquant-macos/\(version)" }39}4041public final class APIClient: Sendable {42 public let baseURL: URL43 public let identity: ClientIdentity44 public let tokens: TokenStore45 private let transport: HTTPTransport46 private let unauthorizedHandler = OSAllocatedUnfairLock<(@Sendable () -> Void)?>(initialState: nil)4748 public init(baseURL: URL, identity: ClientIdentity, tokens: TokenStore, transport: HTTPTransport) {49 self.baseURL = baseURL; self.identity = identity; self.tokens = tokens; self.transport = transport50 }5152 /// Called (once per failing request) when the server answers that this device is locked out.53 public func onUnauthorized(_ handler: @escaping @Sendable () -> Void) { unauthorizedHandler.withLock { $0 = handler } }5455 public var hasToken: Bool { tokens.read() != nil }5657 public func request(_ method: HTTPMethod, _ path: String, query: [String: String?] = [:], body: JSONValue? = nil, authenticated: Bool = true, accept: String? = nil) throws -> URLRequest {58 guard var comps = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) else { throw APIError(.rejected, "Invalid server address.") }59 comps.percentEncodedPath = path60 let items = query.compactMap { k, v in v.map { URLQueryItem(name: k, value: $0) } }.sorted { $0.name < $1.name }61 if !items.isEmpty {62 comps.queryItems = items63 // "+" must not reach the server as a space, "^" (index symbols) is sent encoded64 comps.percentEncodedQuery = comps.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")65 }66 guard let url = comps.url else { throw APIError(.rejected, "Invalid request path.") }67 var r = URLRequest(url: url)68 r.httpMethod = method.rawValue69 r.setValue(identity.header, forHTTPHeaderField: "X-VQ-Client")70 if let accept { r.setValue(accept, forHTTPHeaderField: "Accept") }71 if authenticated, let t = tokens.read() { r.setValue("Bearer \(t)", forHTTPHeaderField: "Authorization") }72 if let body {73 r.setValue("application/json", forHTTPHeaderField: "Content-Type")74 r.httpBody = body.data()75 } else if method != .get {76 r.setValue("application/json", forHTTPHeaderField: "Content-Type")77 r.httpBody = Data("{}".utf8)78 }79 return r80 }8182 /// Sends a request and returns the body of a 2xx answer; anything else is thrown as an `APIError`.83 @discardableResult84 public func data(_ method: HTTPMethod, _ path: String, query: [String: String?] = [:], body: JSONValue? = nil, authenticated: Bool = true, accept: String? = nil) async throws -> Data {85 let req = try request(method, path, query: query, body: body, authenticated: authenticated, accept: accept)86 let (data, http): (Data, HTTPURLResponse)87 do { (data, http) = try await transport.data(for: req) }88 catch is CancellationError { throw CancellationError() }89 catch let e as URLError where e.code == .cancelled { throw CancellationError() }90 catch { throw APIError(.network, "The VQuant server cannot be reached. \(Self.reason(error))") }91 try check(http, data, authenticated: authenticated)92 return data93 }9495 public func json(_ method: HTTPMethod, _ path: String, query: [String: String?] = [:], body: JSONValue? = nil, authenticated: Bool = true) async throws -> JSONValue {96 let d = try await data(method, path, query: query, body: body, authenticated: authenticated)97 do { return try JSONValue.parse(d) } catch { throw APIError(.decoding, "The server sent an answer this version cannot read (\(path)).") }98 }99100 public func decode<T: Decodable>(_ type: T.Type, _ method: HTTPMethod, _ path: String, query: [String: String?] = [:], body: JSONValue? = nil, authenticated: Bool = true) async throws -> T {101 let d = try await data(method, path, query: query, body: body, authenticated: authenticated)102 do { return try JSONDecoder().decode(T.self, from: d) }103 catch { throw APIError(.decoding, "The server sent an answer this version cannot read (\(path)): \(Self.describe(error))") }104 }105106 /// Opens a server-sent event stream. The HTTP status is checked before the first line is returned.107 public func lines(_ method: HTTPMethod, _ path: String, query: [String: String?] = [:], body: JSONValue? = nil) async throws -> AsyncThrowingStream<String, Error> {108 let req = try request(method, path, query: query, body: body, accept: "text/event-stream")109 let (stream, http): (AsyncThrowingStream<String, Error>, HTTPURLResponse)110 do { (stream, http) = try await transport.lines(for: req) }111 catch is CancellationError { throw CancellationError() }112 catch let e as URLError where e.code == .cancelled { throw CancellationError() }113 catch { throw APIError(.network, "The VQuant server cannot be reached. \(Self.reason(error))") }114 if !(200..<300).contains(http.statusCode) {115 // an error answer is a short JSON body: read it to report the server's own words116 var body = ""117 do { for try await l in stream { body += l; if body.count > 4000 { break } } } catch {}118 try check(http, Data(body.utf8), authenticated: true)119 }120 return stream121 }122123 private func check(_ http: HTTPURLResponse, _ data: Data, authenticated: Bool) throws {124 let s = http.statusCode125 guard !(200..<300).contains(s) else { return }126 let parsed = try? JSONValue.parse(data)127 let code = parsed?["error"]?.stringValue ?? parsed?["message"]?.stringValue ?? ""128 switch s {129 case 401:130 if authenticated, http.value(forHTTPHeaderField: "x-vq-locked") == "1" || tokens.read() != nil {131 let handler = unauthorizedHandler.withLock { $0 }132 handler?()133 }134 throw APIError(.unauthorized, status: s, code == "refused" ? "The server refused this passkey." : "This Mac is no longer signed in to VQuant.")135 case 403:136 if code == "reauth_required" { throw APIError(.reauthRequired, status: s, "Confirm with your passkey to continue.") }137 throw APIError(.forbidden, status: s, "The server refused this request.")138 case 404: throw APIError(.notFound, status: s, Self.human(code, fallback: "Not found."))139 case 409: throw APIError(.conflict, status: s, Self.human(code, fallback: "The request conflicts with the current state."))140 case 410: throw APIError(.gone, status: s, "This setup link has expired or was already used.")141 case 429: throw APIError(.rateLimited, status: s, Self.human(code, fallback: "Too many requests. Try again in a minute."))142 case 400, 422: throw APIError(.rejected, status: s, Self.human(code, fallback: "The server rejected the request."))143 default: throw APIError(.server, status: s, Self.human(code, fallback: "The server reported an error (HTTP \(s))."))144 }145 }146147 /// Server error bodies are either a sentence or a short code; codes are spelled out.148 private static func human(_ code: String, fallback: String) -> String {149 switch code {150 case "": return fallback151 case "limited": return "Too many attempts. Try again in a minute."152 case "last_passkey": return "This is the only passkey of the account: it cannot be removed."153 case "not_found": return "Not found."154 case "use_logout": return "Use Sign Out to end the session of this Mac."155 case "internal": return "The server reported an internal error."156 case "refused", "forbidden", "expired": return fallback157 default: return code158 }159 }160161 static func reason(_ error: Error) -> String {162 guard let e = error as? URLError else { return "" }163 switch e.code {164 case .notConnectedToInternet, .networkConnectionLost, .dataNotAllowed: return "This Mac appears to be offline."165 case .timedOut: return "The request timed out."166 case .cannotFindHost, .dnsLookupFailed: return "The server name could not be resolved."167 case .cannotConnectToHost: return "The server refused the connection."168 case .secureConnectionFailed, .serverCertificateUntrusted, .serverCertificateHasBadDate, .serverCertificateNotYetValid, .serverCertificateHasUnknownRoot: return "The secure connection could not be established."169 default: return ""170 }171 }172173 static func describe(_ error: Error) -> String {174 guard let e = error as? DecodingError else { return "\(error)" }175 func path(_ c: DecodingError.Context) -> String { c.codingPath.map { $0.intValue.map { "[\($0)]" } ?? $0.stringValue }.joined(separator: ".") }176 switch e {177 case .keyNotFound(let k, let c): return "missing “\(k.stringValue)” at \(path(c))"178 case .typeMismatch(_, let c), .valueNotFound(_, let c), .dataCorrupted(let c): return "\(c.debugDescription) at \(path(c))"179 @unknown default: return "\(e)"180 }181 }182183 /// Percent-encodes one path segment (ticker symbols such as ^GSPC or BRK-B, identifiers).184 public static func segment(_ s: String) -> String {185 var allowed = CharacterSet.alphanumerics; allowed.insert(charactersIn: "-._~")186 return s.addingPercentEncoding(withAllowedCharacters: allowed) ?? s187 }188}189