Repository Public
1//2// VQuant iOS3// File: Core/Networking/APIClient.swift4// Description: HTTPS client of the VQuant backend: bearer device session, typed errors, JSON decoding, SSE streams.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import Foundation1112struct APIError: Error, LocalizedError, Equatable, Sendable {13 enum Kind: Sendable, Equatable {14 case unauthorized, reauthRequired, forbidden, notFound, conflict, rateLimited, badRequest, server, network, offline, decoding, cancelled15 }16 var kind: Kind17 var message: String18 var status: Int?19 var code: String?20 var errorDescription: String? { message }2122 static let cancelled = APIError(kind: .cancelled, message: "Annulé.")23 static func from(_ error: Error) -> APIError {24 if let e = error as? APIError { return e }25 if error is CancellationError { return .cancelled }26 if let u = error as? URLError {27 switch u.code {28 case .cancelled: return .cancelled29 case .notConnectedToInternet, .dataNotAllowed, .internationalRoamingOff: return APIError(kind: .offline, message: "Aucune connexion Internet.")30 default: return APIError(kind: .network, message: "Le serveur VQuant est injoignable (\(u.code.rawValue)).")31 }32 }33 if error is DecodingError { return APIError(kind: .decoding, message: "Réponse du serveur illisible.") }34 return APIError(kind: .network, message: error.localizedDescription)35 }36}3738/// Where the device session token lives (Keychain in the app, memory in tests).39protocol SessionTokenStore: Sendable {40 func load() -> String?41 func save(_ token: String)42 func clear()43}4445final class MemoryTokenStore: SessionTokenStore, @unchecked Sendable {46 private let lock = NSLock()47 private var token: String?48 init(_ token: String? = nil) { self.token = token }49 func load() -> String? { lock.withLock { token } }50 func save(_ token: String) { lock.withLock { self.token = token } }51 func clear() { lock.withLock { token = nil } }52}5354struct APIRequest: Sendable {55 var method: String = "GET"56 var path: String57 var query: [String: String] = [:]58 var body: Data?59 var contentType: String? = "application/json"60 var timeout: TimeInterval = 3061 var accept: String = "application/json"6263 static func get(_ path: String, query: [String: String] = [:], timeout: TimeInterval = 30) -> APIRequest {64 APIRequest(path: path, query: query, timeout: timeout)65 }66 static func json<B: Encodable>(_ method: String, _ path: String, _ body: B, timeout: TimeInterval = 30) throws -> APIRequest {67 APIRequest(method: method, path: path, body: try JSONEncoder().encode(body), timeout: timeout)68 }69 static func send(_ method: String, _ path: String) -> APIRequest { APIRequest(method: method, path: path, body: Data("{}".utf8)) }70}7172/// One client per backend origin. Thread-safe; every call is `async` and runs off the main actor.73final class APIClient: Sendable {74 let baseURL: URL75 let tokens: SessionTokenStore76 let session: URLSession77 let clientTag: String78 /// Called when the server refuses the session (revoked device, rotated key): the app signs out locally.79 private let unauthorizedHandler = HandlerBox()8081 init(baseURL: URL, tokens: SessionTokenStore, session: URLSession? = nil, clientTag: String = "vquant-ios/2.0.0 (2)") {82 self.baseURL = baseURL83 self.tokens = tokens84 self.clientTag = clientTag85 if let session { self.session = session } else {86 let cfg = URLSessionConfiguration.ephemeral // no cookie jar, no shared URL cache on disk87 cfg.httpCookieStorage = nil88 cfg.httpShouldSetCookies = false89 cfg.urlCache = nil90 cfg.requestCachePolicy = .reloadIgnoringLocalCacheData91 cfg.waitsForConnectivity = false92 cfg.timeoutIntervalForRequest = 3093 cfg.allowsExpensiveNetworkAccess = true94 cfg.tlsMinimumSupportedProtocolVersion = .TLSv1295 self.session = URLSession(configuration: cfg)96 }97 }9899 func onUnauthorized(_ handler: @escaping @Sendable () -> Void) { unauthorizedHandler.set(handler) }100101 // MARK: requests102103 func urlRequest(_ r: APIRequest) throws -> URLRequest {104 guard var comps = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) else { throw APIError(kind: .badRequest, message: "Adresse invalide.") }105 comps.percentEncodedPath = r.path.addingPercentEncoding(withAllowedCharacters: Self.pathAllowed) ?? r.path106 if !r.query.isEmpty { comps.queryItems = r.query.sorted { $0.key < $1.key }.map { URLQueryItem(name: $0.key, value: $0.value) } }107 guard let url = comps.url else { throw APIError(kind: .badRequest, message: "Adresse invalide.") }108 // Only HTTPS leaves the device; plain HTTP is accepted for a loopback development server alone.109 guard url.scheme == "https" || (url.scheme == "http" && ["localhost", "127.0.0.1"].contains(url.host ?? "")) else {110 throw APIError(kind: .badRequest, message: "Connexion non chiffrée refusée.")111 }112 var req = URLRequest(url: url, timeoutInterval: r.timeout)113 req.httpMethod = r.method114 req.httpBody = r.body115 if r.body != nil, let ct = r.contentType { req.setValue(ct, forHTTPHeaderField: "Content-Type") }116 req.setValue(r.accept, forHTTPHeaderField: "Accept")117 req.setValue(clientTag, forHTTPHeaderField: "X-VQ-Client")118 if let t = tokens.load() { req.setValue("Bearer \(t)", forHTTPHeaderField: "Authorization") }119 return req120 }121122 private static let pathAllowed: CharacterSet = {123 var s = CharacterSet.urlPathAllowed; s.remove(charactersIn: "^%?#"); return s124 }()125126 func data(_ r: APIRequest) async throws -> Data {127 let req = try urlRequest(r)128 let data: Data, response: URLResponse129 do { (data, response) = try await session.data(for: req) } catch { throw APIError.from(error) }130 try check(response, data: data, hadToken: req.value(forHTTPHeaderField: "Authorization") != nil)131 return data132 }133134 func decode<T: Decodable>(_ r: APIRequest) async throws -> T { try await decode(T.self, r) }135136 func decode<T: Decodable>(_ type: T.Type, _ r: APIRequest) async throws -> T {137 let d = try await data(r)138 do { return try JSONDecoder().decode(T.self, from: d) } catch { throw APIError(kind: .decoding, message: "Réponse du serveur illisible (\(r.path)).") }139 }140141 /// Opens a `text/event-stream` response and yields the decoded events of an analysis.142 func stream(_ r: APIRequest) -> AsyncThrowingStream<StreamItem, Error> {143 var r = r144 r.accept = "text/event-stream"145 r.timeout = 3600146 let request: URLRequest147 do { request = try urlRequest(r) } catch { return AsyncThrowingStream { $0.finish(throwing: error) } }148 let session = self.session149 return AsyncThrowingStream(bufferingPolicy: .unbounded) { continuation in150 let task = Task.detached(priority: .userInitiated) { [weak self] in151 do {152 let (bytes, response) = try await session.bytes(for: request)153 if let http = response as? HTTPURLResponse, http.statusCode != 200 {154 var body = Data()155 for try await b in bytes { body.append(b); if body.count > 4096 { break } }156 try self?.check(response, data: body, hadToken: request.value(forHTTPHeaderField: "Authorization") != nil)157 throw APIError(kind: .server, message: "Réponse inattendue (\(http.statusCode)).", status: http.statusCode)158 }159 for try await item in SSEStream.items(from: bytes) { continuation.yield(item) }160 continuation.finish()161 } catch { continuation.finish(throwing: APIError.from(error)) }162 }163 continuation.onTermination = { _ in task.cancel() }164 }165 }166167 func check(_ response: URLResponse, data: Data, hadToken: Bool) throws {168 guard let http = response as? HTTPURLResponse else { throw APIError(kind: .network, message: "Réponse invalide.") }169 guard !(200..<300).contains(http.statusCode) else { return }170 struct Body: Decodable { var error: String? }171 let raw = (try? JSONDecoder().decode(Body.self, from: data))?.error172 let s = http.statusCode173 switch s {174 case 401:175 // `x-vq-locked` is the gate refusing the session itself (revoked, expired after 90 idle days, key rotated).176 // A 401 without it is a refused passkey ceremony: the session is still good.177 let locked = http.value(forHTTPHeaderField: "x-vq-locked") == "1"178 if hadToken && locked { unauthorizedHandler.call() }179 throw APIError(kind: .unauthorized, message: locked ? "Session expirée ou révoquée. Connectez-vous de nouveau." : "Vérification refusée par le serveur.", status: s, code: raw)180 case 403:181 if raw == "reauth_required" { throw APIError(kind: .reauthRequired, message: "Vérification récente requise.", status: s, code: raw) }182 throw APIError(kind: .forbidden, message: raw ?? "Action refusée.", status: s, code: raw)183 case 404: throw APIError(kind: .notFound, message: raw ?? "Introuvable.", status: s, code: raw)184 case 409: throw APIError(kind: .conflict, message: Self.readable(raw) ?? "Conflit.", status: s, code: raw)185 case 410: throw APIError(kind: .notFound, message: "Ce lien d’invitation n’est plus valide.", status: s, code: raw)186 case 429: throw APIError(kind: .rateLimited, message: raw == "limited" || raw == nil ? "Trop de requêtes. Réessayez dans un instant." : raw!, status: s, code: raw)187 case 400..<500: throw APIError(kind: .badRequest, message: Self.readable(raw) ?? "Requête refusée (\(s)).", status: s, code: raw)188 default: throw APIError(kind: .server, message: raw ?? "Erreur du serveur (\(s)).", status: s, code: raw)189 }190 }191192 private static func readable(_ code: String?) -> String? {193 switch code {194 case "last_passkey": "Impossible de supprimer la dernière clé d’accès du compte."195 case "refused": "Vérification refusée par le serveur."196 default: code197 }198 }199}200201private final class HandlerBox: @unchecked Sendable {202 private let lock = NSLock()203 private var handler: (@Sendable () -> Void)?204 func set(_ h: @escaping @Sendable () -> Void) { lock.withLock { handler = h } }205 func call() { lock.withLock { handler }?() }206}207