SPB Git

Repository Public

APIClient.swift 6.3 KB 129 lines swift

1import Foundation2import HTTPTypes3import OpenAPIRuntime4import OpenAPIURLSession56/// Short name for the contract's schemas: `API.Node`, `API.Alert`...7public typealias API = Components.Schemas89/// The generated client (`Client`) behind the transport policy of the product: bearer injection, single-flight10/// refresh, structured errors, GET-only retries, offline guard, timeouts. Use `call { try await $0.getMe().ok.body.json }`.11public final class APIClient: Sendable {12    /// Origin of the server, for example `https://clustr.spboucher.ai`.13    public let origin: URL14    /// `origin` + `/api/v1`.15    public let apiURL: URL16    public let client: Client17    public let tokens: TokenManager18    public let connectivity: Connectivity19    public let urlSession: URLSession20    public let sessionStore: SessionStore2122    /// - Parameters:23    ///   - origin: server origin (scheme + host + port).24    ///   - secureStore: where the tokens live (Keychain in the apps).25    ///   - protocolClasses: URLProtocol stubs (unit tests).26    public init(origin: URL, secureStore: any SecureStore, userAgent: String = APIClient.defaultUserAgent(),27                protocolClasses: [AnyClass]? = nil, requestTimeout: TimeInterval = 20, getRetries: Int = 3) {28        self.origin = origin29        self.apiURL = origin.appendingPathComponent("api/v1")30        let config = URLSessionConfiguration.ephemeral31        config.httpCookieAcceptPolicy = .never32        config.httpShouldSetCookies = false33        config.urlCache = nil34        config.requestCachePolicy = .reloadIgnoringLocalCacheData35        config.timeoutIntervalForRequest = requestTimeout36        config.timeoutIntervalForResource = 12037        config.waitsForConnectivity = false38        config.httpAdditionalHeaders = ["User-Agent": userAgent, "Accept-Language": Localization.shared.language.rawValue]39        if let protocolClasses { config.protocolClasses = protocolClasses }40        let session = URLSession(configuration: config)41        self.urlSession = session42        let store = SessionStore(store: secureStore, baseURL: origin)43        self.sessionStore = store44        let connectivity = Connectivity()45        self.connectivity = connectivity46        let transport = URLSessionTransport(configuration: .init(session: session))47        let configuration = Configuration(dateTranscoder: FlexibleDateTranscoder())48        // The refresh call uses a bare client: no bearer, no refresh-on-401 recursion, no retry (the refresh token49        // rotates: replaying it would look like a reuse).50        let bare = Client(serverURL: apiURL, configuration: configuration, transport: transport, middlewares: [51            ErrorMappingMiddleware(connectivity: connectivity, guardOffline: false)52        ])53        let tokens = TokenManager(store: store) { refreshToken in54            do {55                let pair = try await bare.refreshSession(body: .json(.init(refreshToken: refreshToken))).ok.body.json56                return SessionTokens(accessToken: pair.accessToken, accessExpiresAt: pair.accessExpiresAt,57                                     refreshToken: pair.refreshToken, refreshExpiresAt: pair.refreshExpiresAt)58            } catch {59                throw APIClient.unwrap(error)60            }61        }62        self.tokens = tokens63        self.client = Client(serverURL: apiURL, configuration: configuration, transport: transport, middlewares: [64            ErrorMappingMiddleware(connectivity: connectivity, guardOffline: true),65            RetryMiddleware(maxAttempts: getRetries),66            AuthMiddleware(tokens: tokens),67        ])68    }6970    /// Runs a generated operation and normalises whatever it throws to `APIError`.71    public func call<T: Sendable>(_ operation: (Client) async throws -> T) async throws -> T {72        do {73            return try await operation(client)74        } catch {75            throw Self.unwrap(error)76        }77    }7879    static func unwrap(_ error: any Error) -> APIError {80        if let e = error as? APIError { return e }81        if let c = error as? ClientError { return APIError.from(c.underlyingError) }82        return APIError.from(error)83    }8485    public static func defaultUserAgent(bundle: Bundle = .main) -> String {86        let v = bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0"87        let b = bundle.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "0"88        #if os(macOS)89        let platform = "macOS"90        #else91        let platform = "iOS"92        #endif93        let os = ProcessInfo.processInfo.operatingSystemVersion94        return "MacLustrCommandCenter/\(v) (\(b); \(platform) \(os.majorVersion).\(os.minorVersion).\(os.patchVersion))"95    }9697    /// A raw authenticated GET for the two non-JSON downloads of the contract (audit export, calendar .ics).98    /// Applies the same bearer + refresh policy as the generated client.99    public func download(path: String, query: [URLQueryItem]) async throws -> (Data, HTTPURLResponse) {100        var comps = URLComponents(url: apiURL.appendingPathComponent(path), resolvingAgainstBaseURL: false)!101        if !query.isEmpty { comps.queryItems = query }102        func send(_ token: String?) async throws -> (Data, HTTPURLResponse) {103            var req = URLRequest(url: comps.url!)104            if let token { req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") }105            do {106                let (data, resp) = try await urlSession.data(for: req)107                connectivity.recordResponse()108                return (data, resp as! HTTPURLResponse)109            } catch {110                let e = APIError.from(error)111                if e.isTransport { connectivity.recordTransportFailure() }112                throw e113            }114        }115        let token = try await tokens.accessToken()116        var (data, resp) = try await send(token)117        if resp.statusCode == 401, let token {118            let fresh = try await tokens.refreshAfterRejection(of: token)119            (data, resp) = try await send(fresh)120        }121        guard resp.statusCode < 400 else {122            var fields = HTTPFields()123            if let c = resp.value(forHTTPHeaderField: "X-Correlation-Id") { fields[.correlationID] = c }124            throw ErrorMappingMiddleware.decode(status: resp.statusCode, headers: fields, body: data)125        }126        return (data, resp)127    }128}129
Files main
Menu

Theme