SPB Git

Repository Public

APIClient.swift 17.4 KB 398 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Vrai-Prix iOS9// File             : VraiPrix/Core/API/APIClient.swift10// Description      : client de l'API Vrai-Prix v2 — acteur, sonde du service11//                    (www puis préproduction), cache de réponses sur disque,12//                    repli hors ligne.13// Module           : VraiPrix14// Repository       : https://git.spboucher.ai/vrai-prix-ios-v315// Project Website  : https://www.vrai-prix.com16// Created          : 2026-11-2617// Last Modified    : 2026-11-2818//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation9293enum APIError: Error, LocalizedError, Sendable, Equatable {94    case notFound95    /// 410 : une inscription retirée, une route supprimée96    case gone97    /// 429 : trop de requêtes98    case rateLimited99    /// 503 de l'API v3 : le moteur de valeur ne se lit pas pour l'instant (jamais une valeur de repli)100    case unavailable101    case http(Int)102    case server(String)103    case offline104    case decoding(String)105    case invalidURL106107    var errorDescription: String? {108        switch self {109        case .notFound: "Introuvable."110        case .gone: "Cette page n'existe plus."111        case .rateLimited: "Trop de requêtes. Réessayez dans une minute."112        case .unavailable: "Les valeurs sont en cours de mise à jour. Réessayez dans un instant."113        case .http(let code): "Le serveur a répondu \(code)."114        case .server(let message): message115        case .offline: "Connexion impossible. Vérifiez votre accès à Internet."116        case .decoding: "Réponse illisible."117        case .invalidURL: "Adresse invalide."118        }119    }120121    var isOffline: Bool { self == .offline }122}123124/// Identité du service : `GET /api/version` (voir `ServiceInfo`).125typealias APIVersion = ServiceInfo126127/// Résultat d'une lecture : la valeur, et si elle vient du cache faute de réseau.128struct Fetched<T: Sendable>: Sendable {129    var value: T130    var stale: Bool131}132133/// Client HTTP de l'API. Une seule instance (`APIClient.shared`).134///135/// L'app parle à la v2 du service. Elle sonde d'abord `https://www.vrai-prix.com/api/version` et n'utilise la136/// production que si elle répond `api: 2` (bascule future) ; sinon, la préproduction.137actor APIClient {138    static let shared = APIClient()139140    static let primary = URL(string: "https://www.vrai-prix.com")!141    static let fallback = URL(string: "https://vraiprix-v2.51-161-112-61.sslip.io")!142    /// Adresse publique du site (liens partagés).143    static let site = URL(string: "https://www.vrai-prix.com")!144    private static let baseKey = "api.base"145146    private let session: URLSession147    private var base: URL148    private var resolved = false149    private var resolving: Task<URL, Never>?150151    init() {152        let cfg = URLSessionConfiguration.default153        cfg.timeoutIntervalForRequest = 25154        cfg.timeoutIntervalForResource = 90155        cfg.waitsForConnectivity = false156        cfg.requestCachePolicy = .useProtocolCachePolicy157        cfg.urlCache = URLCache(memoryCapacity: 16 << 20, diskCapacity: 64 << 20, directory: nil)158        cfg.httpAdditionalHeaders = ["Accept": "application/json", "Accept-Language": "fr-CA"]159        session = URLSession(configuration: cfg)160        let saved = UserDefaults.standard.string(forKey: APIClient.baseKey).flatMap(URL.init(string:))161        base = APIClient.forcedBase ?? saved ?? APIClient.fallback162    }163164    /// Adresse imposée par argument de lancement ou variable d'environnement (tests et développement).165    /// Adresse imposée (tests, API de développement) : en Debug seulement, jamais dans un binaire Release.166    private static var forcedBase: URL? {167        #if DEBUG168        (UserDefaults.standard.string(forKey: "VPBaseURL") ?? ProcessInfo.processInfo.environment["VRAIPRIX_BASE_URL"]).flatMap(URL.init(string:))169        #else170        nil171        #endif172    }173174    static var candidates: [URL] {175        if let f = forcedBase { return [f] }176        return [primary, fallback]177    }178179    /// Une réponse de `/api/version` désigne-t-elle une v2 ?180    static func isV2(_ data: Data) -> APIVersion? {181        guard let v = try? JSONDecoder().decode(APIVersion.self, from: data), v.api >= 2 else { return nil }182        return v183    }184185    private static func probe(_ url: URL, session: URLSession) async -> Bool {186        var req = URLRequest(url: url.appending(path: "api/version"))187        req.timeoutInterval = 6188        req.cachePolicy = .reloadIgnoringLocalCacheData189        guard let (data, resp) = try? await session.data(for: req), (resp as? HTTPURLResponse)?.statusCode == 200,190              let v = isV2(data) else { return false }191        ServiceInfo.store(v)192        return true193    }194195    /// Service retenu ; sondé une fois par lancement.196    func resolve() async -> URL {197        if resolved { return base }198        if let t = resolving { return await t.value }199        let session = self.session200        let current = base201        let t = Task<URL, Never> {202            for candidate in APIClient.candidates where await APIClient.probe(candidate, session: session) { return candidate }203            // aucune v2 ne répond (hors ligne) : dernier service connu, le cache de réponses porte la même forme204            return APIClient.forcedBase ?? current205        }206        resolving = t207        let b = await t.value208        base = b209        resolved = true210        resolving = nil211        if APIClient.forcedBase == nil { UserDefaults.standard.set(b.absoluteString, forKey: APIClient.baseKey) }212        return b213    }214215    func baseURL() async -> URL { await resolve() }216217    /// URL absolue d'un chemin de l'API (liens PDF).218    func url(_ path: String, query: [String: String?] = [:]) async -> URL? {219        APIClient.compose(base: await resolve(), path: path, query: query)220    }221222    static func compose(base: URL, path: String, query: [String: String?]) -> URL? {223        guard var comps = URLComponents(url: base.appending(path: path), resolvingAgainstBaseURL: false) else { return nil }224        let items = query.compactMap { k, v -> URLQueryItem? in225            guard let v, !v.isEmpty else { return nil }226            return URLQueryItem(name: k, value: v)227        }.sorted { $0.name < $1.name }228        if !items.isEmpty { comps.queryItems = items }229        comps.percentEncodedQuery = comps.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")230        return comps.url231    }232233    /// Lit des octets ; en cas de panne réseau, sert la dernière réponse en cache si elle existe.234    private func load(_ request: URLRequest, cacheKey: URL?) async throws -> (Data, Bool) {235        var req = request236        // validation conditionnelle : l'ETag de la copie gardée sur disque ; 304 = la copie est à jour237        let conditional = req.httpMethod ?? "GET" == "GET" ? cacheKey.flatMap { k in ResponseCache.etag(k).map { (k, $0) } } : nil238        if let (_, tag) = conditional {239            req.setValue(tag, forHTTPHeaderField: "If-None-Match")240            req.cachePolicy = .reloadIgnoringLocalCacheData241        }242        do {243            let (d, resp) = try await session.data(for: req)244            let http = resp as? HTTPURLResponse245            let code = http?.statusCode ?? 0246            switch code {247            case 304:248                if let (k, _) = conditional, let cached = ResponseCache.read(k) { notModified += 1; return (cached, false) }249                throw APIError.http(304)250            case 200..<300:251                if let k = cacheKey { ResponseCache.setEtag(k, http?.value(forHTTPHeaderField: "ETag")) }252                return (d, false)253            case 404: throw APIError.notFound254            case 410: throw APIError.gone255            case 429: throw APIError.rateLimited256            default:257                let e = ServerError.read(d)258                if code == 503, e?.code == "engine_unavailable" { throw APIError.unavailable }259                if let m = e?.message, code < 500 { throw APIError.server(m) }260                throw APIError.http(code)261            }262        } catch let e as APIError {263            throw e264        } catch is CancellationError {265            throw CancellationError()266        } catch let e as URLError where e.code == .cancelled {267            throw CancellationError()268        } catch {269            if let k = cacheKey, let cached = ResponseCache.read(k) { return (cached, true) }270            throw APIError.offline271        }272    }273274    /// Nombre de réponses 304 reçues depuis le lancement (tests).275    private(set) var notModified = 0276277    /// Les deux enveloppes d'erreur du service : `{"error": "texte"}` (API 2) et278    /// `{"error": {"code", "message", "request_id"}}` (API v3).279    struct ServerError: Sendable, Equatable {280        var code: String?281        var message: String?282        static func read(_ data: Data) -> ServerError? {283            guard let e = JSONValue.parse(data)?["error"], !e.isNull else { return nil }284            if let s = e.text { return ServerError(code: nil, message: s) }285            return ServerError(code: e["code"].text, message: e["message"].text)286        }287    }288289    /// GET JSON, avec l'origine de la réponse (réseau ou cache hors ligne).290    func fetch<T: Decodable & Sendable>(_ path: String, query: [String: String?] = [:], as type: T.Type = T.self) async throws -> Fetched<T> {291        guard let u = await url(path, query: query) else { throw APIError.invalidURL }292        let (data, stale) = try await load(URLRequest(url: u), cacheKey: u)293        do {294            let value = try JSONDecoder().decode(T.self, from: data)295            if !stale { ResponseCache.write(u, data) }296            return Fetched(value: value, stale: stale)297        } catch {298            ResponseCache.setEtag(u, nil)   // la copie gardée ne correspond pas à cette réponse299            throw APIError.decoding(String(describing: error).prefix(300).description)300        }301    }302303    func get<T: Decodable & Sendable>(_ path: String, query: [String: String?] = [:], as type: T.Type = T.self) async throws -> T {304        try await fetch(path, query: query, as: type).value305    }306307    /// GET brut (réponses conservées telles quelles).308    func raw(_ path: String, query: [String: String?] = [:]) async throws -> Data {309        guard let u = await url(path, query: query) else { throw APIError.invalidURL }310        let (data, stale) = try await load(URLRequest(url: u), cacheKey: u)311        if !stale { ResponseCache.write(u, data) }312        return data313    }314315    /// POST JSON (estimation sans adresse, méthode du coût). Jamais mis en cache.316    func post<T: Decodable & Sendable>(_ path: String, query: [String: String?] = [:], body: Data, as type: T.Type = T.self) async throws -> T {317        guard let u = await url(path, query: query) else { throw APIError.invalidURL }318        var req = URLRequest(url: u)319        req.httpMethod = "POST"320        req.setValue("application/json", forHTTPHeaderField: "Content-Type")321        req.httpBody = body322        let (data, _) = try await load(req, cacheKey: nil)323        do { return try JSONDecoder().decode(T.self, from: data) } catch {324            throw APIError.decoding(String(describing: error).prefix(300).description)325        }326    }327328    /// Télécharge un rapport PDF dans un fichier temporaire.329    func download(_ path: String, query: [String: String?], fileName: String) async throws -> URL {330        guard let u = await url(path, query: query) else { throw APIError.invalidURL }331        var req = URLRequest(url: u)332        req.setValue("application/pdf", forHTTPHeaderField: "Accept")333        req.timeoutInterval = 60334        let (data, _) = try await load(req, cacheKey: nil)335        guard data.prefix(4) == Data("%PDF".utf8) else { throw APIError.decoding("pas un PDF") }336        let dir = FileManager.default.temporaryDirectory.appending(path: "rapports", directoryHint: .isDirectory)337        try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)338        let file = dir.appending(path: fileName)339        try data.write(to: file, options: .atomic)340        return file341    }342}343344/// Dernières réponses JSON gardées sur disque : fiches consultées, favoris et listes restent lisibles hors ligne.345enum ResponseCache {346    private static let dir: URL = {347        let d = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appending(path: "api", directoryHint: .isDirectory)348        try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true)349        return d350    }()351352    /// Clé stable, indépendante de l'hôte (préproduction ou production).353    static func key(_ url: URL) -> String {354        let key = url.path + "?" + (url.query ?? "")355        var h: UInt64 = 1469598103934665603356        for b in key.utf8 { h = (h ^ UInt64(b)) &* 1099511628211 }357        return String(h, radix: 36)358    }359360    private static func file(_ url: URL) -> URL { dir.appending(path: key(url) + ".json") }361362    static func write(_ url: URL, _ data: Data) {363        guard data.count < 3_000_000 else { return }364        try? data.write(to: file(url), options: .atomic)365    }366367    static func read(_ url: URL) -> Data? { try? Data(contentsOf: file(url)) }368369    private static func etagFile(_ url: URL) -> URL { dir.appending(path: key(url) + ".etag") }370371    /// ETag de la copie gardée, seulement si cette copie existe encore.372    static func etag(_ url: URL) -> String? {373        guard FileManager.default.fileExists(atPath: file(url).path), let d = try? Data(contentsOf: etagFile(url)) else { return nil }374        return String(data: d, encoding: .utf8)375    }376377    static func setEtag(_ url: URL, _ tag: String?) {378        if let tag, !tag.isEmpty { try? Data(tag.utf8).write(to: etagFile(url), options: .atomic) }379        else { try? FileManager.default.removeItem(at: etagFile(url)) }380    }381382    /// Purge les entrées de plus de 30 jours (appelée au lancement).383    static func prune() {384        let limit = Date().addingTimeInterval(-30 * 86400)385        let items = (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: [.contentModificationDateKey])) ?? []386        for f in items {387            if let d = try? f.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate, d < limit {388                try? FileManager.default.removeItem(at: f)389            }390        }391    }392393    static func clear() {394        let items = (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)) ?? []395        for f in items { try? FileManager.default.removeItem(at: f) }396    }397}398
Files main
Menu

Theme