Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/API/APIClient.swift3// Description: HTTPS client of the SP Drive API: bearer device session, JSON coding, error mapping, bounded retries of idempotent calls. Everything is injected (base URL, token store, session configuration).4import Foundation56/// Where the device session token lives. The app and its extensions share one store (a keychain access group).7public protocol TokenStore: Sendable {8 func readToken() throws -> String?9 func writeToken(_ token: String) throws10 func deleteToken() throws11}12/// Token kept in memory only (tests, tools).13public final class MemoryTokenStore: TokenStore, @unchecked Sendable {14 private let lock = NSLock(); private var token: String?15 public init(_ token: String? = nil) { self.token = token }16 public func readToken() -> String? { lock.withLock { token } }17 public func writeToken(_ t: String) { lock.withLock { token = t } }18 public func deleteToken() { lock.withLock { token = nil } }19}2021public final class APIClient: Sendable {22 public let baseURL: URL23 public let tokens: TokenStore24 public let session: URLSession25 public let userAgent: String26 /// `X-SPD-Client` (SP Drive 2.0): `<platform>/<app version> (<os version>)`, sent on every request when set.27 public let clientHeader: String?2829 /// - Parameters:30 /// - baseURL: origin of the server, e.g. https://drive.spboucher.ai. Plain HTTP is refused except for a loopback address.31 /// - configuration: defaults to an ephemeral configuration without cookies and without cache.32 public init(baseURL: URL, tokens: TokenStore, userAgent: String, configuration: URLSessionConfiguration? = nil, clientHeader: String? = nil) throws {33 self.clientHeader = clientHeader34 guard let scheme = baseURL.scheme?.lowercased(), let host = baseURL.host else { throw DriveError.local("adresse de serveur invalide") }35 let loopback = host == "127.0.0.1" || host == "localhost" || host == "::1"36 guard scheme == "https" || (scheme == "http" && loopback) else { throw DriveError.local("le serveur doit être joint en HTTPS") }37 self.baseURL = baseURL; self.tokens = tokens38 self.userAgent = String(String.UnicodeScalarView(userAgent.unicodeScalars.filter { $0.isASCII && $0.value >= 0x20 && $0.value < 0x7F }))39 let c = configuration ?? APIClient.defaultConfiguration()40 self.session = URLSession(configuration: c)41 }42 public static func defaultConfiguration() -> URLSessionConfiguration {43 let c = URLSessionConfiguration.ephemeral44 c.httpCookieStorage = nil; c.httpShouldSetCookies = false; c.httpCookieAcceptPolicy = .never45 c.urlCache = nil; c.requestCachePolicy = .reloadIgnoringLocalCacheData46 c.timeoutIntervalForRequest = 30; c.timeoutIntervalForResource = 360047 c.waitsForConnectivity = false48 c.httpMaximumConnectionsPerHost = 849 return c50 }5152 public static let decoder: JSONDecoder = {53 let d = JSONDecoder()54 d.dateDecodingStrategy = .custom { dec in55 let s = try dec.singleValueContainer().decode(String.self)56 if let v = try? Date(s, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true)) { return v }57 if let v = try? Date(s, strategy: .iso8601) { return v }58 throw DecodingError.dataCorrupted(.init(codingPath: dec.codingPath, debugDescription: "date: \(s)"))59 }60 return d61 }()62 public static let encoder: JSONEncoder = {63 let e = JSONEncoder()64 e.dateEncodingStrategy = .custom { date, enc in var c = enc.singleValueContainer(); try c.encode(date.formatted(Date.ISO8601FormatStyle(includingFractionalSeconds: true))) }65 return e66 }()6768 // MARK: Requests6970 /// A request for `/api/v1` + path, carrying the bearer token when `authenticated`.71 public func request(_ method: String, _ path: String, query: [String: String?] = [:], body: Data? = nil, contentType: String = "application/json",72 headers: [String: String] = [:], authenticated: Bool = true) throws -> URLRequest {73 guard var comps = URLComponents(url: baseURL.appendingPathComponent("api/v1" + path), resolvingAgainstBaseURL: false) else { throw DriveError.local("adresse invalide") }74 let items = query.compactMap { k, v in v.map { URLQueryItem(name: k, value: $0) } }.sorted { $0.name < $1.name }75 if !items.isEmpty { comps.queryItems = items; comps.percentEncodedQuery = comps.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B") }76 guard let url = comps.url else { throw DriveError.local("adresse invalide") }77 var r = URLRequest(url: url)78 r.httpMethod = method79 r.setValue(userAgent, forHTTPHeaderField: "User-Agent")80 r.setValue("application/json", forHTTPHeaderField: "Accept")81 if let clientHeader { r.setValue(clientHeader, forHTTPHeaderField: "X-SPD-Client") }82 // the server asks every state-changing call without a bearer (sign-in, device linking) for this header; harmless on the others83 r.setValue("1", forHTTPHeaderField: "X-SPD-CSRF")84 if authenticated {85 guard let token = try tokens.readToken(), !token.isEmpty else { throw DriveError.unauthenticated }86 r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")87 }88 if let body { r.httpBody = body; r.setValue(contentType, forHTTPHeaderField: "Content-Type") }89 for (k, v) in headers { r.setValue(v, forHTTPHeaderField: k) }90 return r91 }9293 /// Runs a request and returns its body for a 2xx answer; maps every failure to a `DriveError`.94 public func data(for request: URLRequest, retries: Int? = nil) async throws -> (Data, HTTPURLResponse) {95 // only calls that change nothing are repeated blindly; uploads have their own resynchronisation96 let idempotent = ["GET", "HEAD"].contains(request.httpMethod ?? "GET")97 var left = retries ?? (idempotent ? 2 : 0), delay: UInt64 = 400_000_00098 while true {99 do {100 try Task.checkCancellation()101 let (data, response) = try await session.data(for: request)102 return (try APIClient.check(data, response), response as! HTTPURLResponse)103 } catch {104 let e = DriveError.wrap(error)105 guard left > 0, e.isTransient else { throw e }106 left -= 1107 var wait = delay108 if let s = e.extra["retryAfterS"]?.int { wait = UInt64(min(max(s, 1), 30)) * 1_000_000_000 }109 try await Task.sleep(nanoseconds: wait); delay *= 3110 }111 }112 }113 /// Checks the status of an answer; throws the server's own error code when it gave one.114 @discardableResult public static func check(_ data: Data, _ response: URLResponse) throws -> Data {115 guard let http = response as? HTTPURLResponse else { throw DriveError.invalidResponse("pas de réponse HTTP") }116 if (200..<300).contains(http.statusCode) { return data }117 struct Body: Decodable { var error: String?; var message: String? }118 let body = try? decoder.decode(Body.self, from: data)119 var extra = (try? decoder.decode([String: JSONValue].self, from: data)) ?? [:]120 extra["error"] = nil; extra["message"] = nil121 let code = body?.error ?? (http.statusCode == 404 ? "not_found" : "http_\(http.statusCode)")122 if http.statusCode == 401, code == "unauthenticated" { throw DriveError.unauthenticated }123 // gateways (502/503/504) answer HTML: the application behind them is restarting or unreachable124 if body?.error == nil, [502, 503, 504].contains(http.statusCode) { throw DriveError.offline("passerelle \(http.statusCode)") }125 throw DriveError.server(status: http.statusCode, code: code, message: body?.message ?? "HTTP \(http.statusCode)", extra: extra)126 }127128 public func get<T: Decodable>(_ path: String, query: [String: String?] = [:], authenticated: Bool = true) async throws -> T {129 try decode(try await data(for: request("GET", path, query: query, authenticated: authenticated)).0)130 }131 public func send<B: Encodable, T: Decodable>(_ method: String, _ path: String, query: [String: String?] = [:], body: B, authenticated: Bool = true) async throws -> T {132 try decode(try await data(for: request(method, path, query: query, body: APIClient.encoder.encode(body), authenticated: authenticated)).0)133 }134 public func send<T: Decodable>(_ method: String, _ path: String, query: [String: String?] = [:], authenticated: Bool = true) async throws -> T {135 try decode(try await data(for: request(method, path, query: query, body: Data("{}".utf8), authenticated: authenticated)).0)136 }137 func decode<T: Decodable>(_ data: Data) throws -> T {138 do { return try APIClient.decoder.decode(T.self, from: data) } catch { throw DriveError.invalidResponse(String(describing: error).prefix(200).description) }139 }140}141public struct OK: Decodable, Sendable { public var ok: Bool? }142