SPB Git

Repository Public

Transport.swift 15.8 KB 259 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Next/Transport.swift3// Description: SPDriveNext — the SP Drive 2.0 API (docs/next/API-NEXT.md of sp-drive.git) for the native clients. This file: the small transport protocol an app implements (base URL, bearer token, URLSession, client header), the client built on it, errors, loose JSON, and the Server-Sent Events reader. The package depends on nothing but Foundation, so macOS and iOS link the same code.4import Foundation56/// What SPDriveNext needs from the app: where the server is, how to authenticate, which URLSession to use.7public protocol NextTransport: Sendable {8    /// Origin of the server, e.g. https://drive.spboucher.ai (the client appends `/api/v1`).9    var baseURL: URL { get }10    var session: URLSession { get }11    /// `X-SPD-Client` value: `<platform>/<app version> (<os version>)`, platform ∈ macos | ios | ipados. nil = not sent.12    var clientHeader: String? { get }13    /// The device session token, or nil when nobody is signed in (authenticated calls then throw `.unauthenticated`).14    func bearerToken() async throws -> String?15}1617/// A ready-made transport for apps that have nothing special to do.18public struct BasicNextTransport: NextTransport {19    public let baseURL: URL20    public let session: URLSession21    public let clientHeader: String?22    private let token: @Sendable () async throws -> String?23    public init(baseURL: URL, session: URLSession = BasicNextTransport.defaultSession(), clientHeader: String?, token: @escaping @Sendable () async throws -> String?) {24        self.baseURL = baseURL; self.session = session; self.clientHeader = clientHeader; self.token = token25    }26    public func bearerToken() async throws -> String? { try await token() }27    /// Ephemeral, no cookies, no cache; long resource timeout for event streams.28    public static func defaultSession() -> URLSession {29        let c = URLSessionConfiguration.ephemeral30        c.httpCookieStorage = nil; c.httpShouldSetCookies = false; c.urlCache = nil; c.requestCachePolicy = .reloadIgnoringLocalCacheData31        c.timeoutIntervalForRequest = 60; c.timeoutIntervalForResource = 24 * 3600; c.waitsForConnectivity = false32        return URLSession(configuration: c)33    }34    /// Builds the header value: `macos/2.0.0 (27.0)`.35    public static func clientHeader(platform: String, appVersion: String, osVersion: String) -> String { "\(platform)/\(appVersion) (\(osVersion))" }36}3738public enum NextError: Error, Sendable, Equatable, LocalizedError {39    /// No network, or the server did not answer.40    case offline(String)41    case unauthenticated42    /// The server refused; `code` is its stable code (`not_found`, `forbidden`, `ai_unavailable`…).43    case server(status: Int, code: String, message: String, extra: [String: NextJSON])44    case invalidResponse(String)45    case cancelled4647    public var code: String {48        switch self { case .offline: "offline"; case .unauthenticated: "unauthenticated"; case .server(_, let c, _, _): c; case .invalidResponse: "invalid_response"; case .cancelled: "cancelled" }49    }50    public var status: Int? { if case .server(let s, _, _, _) = self { return s }; return nil }51    public var extra: [String: NextJSON] { if case .server(_, _, _, let e) = self { return e }; return [:] }52    public var isNotFound: Bool { status == 404 }53    /// A live grant whose role is too weak for the action (API-NEXT D1): grey the action out, the folder still exists.54    public var isForbidden: Bool { status == 403 }55    /// Seconds the server asks to wait (`retryAfterS` of `rate_limited`, `busy`…), when it says.56    public var retryAfterSeconds: Double? { extra["retryAfterS"]?.double }57    /// The server is momentarily at capacity for this call (`503 busy`, `503 too_many_streams`, `429`): try again later, nothing is wrong with the request.58    public var isBusy: Bool { status == 503 || status == 429 }59    public var errorDescription: String? {60        switch self {61        case .offline(let m): return m62        case .unauthenticated: return "unauthenticated"63        case .server(_, let code, let message, _): return message.isEmpty ? code : message64        case .invalidResponse(let m): return m65        case .cancelled: return "cancelled"66        }67    }68    public static func wrap(_ error: Error) -> NextError {69        if let e = error as? NextError { return e }70        if error is CancellationError { return .cancelled }71        let ns = error as NSError72        if ns.domain == NSURLErrorDomain { return ns.code == NSURLErrorCancelled ? .cancelled : .offline(ns.localizedDescription) }73        return .invalidResponse(ns.localizedDescription)74    }75}7677/// Loosely typed JSON (activity metadata, error details, administration blobs).78public enum NextJSON: Codable, Sendable, Hashable {79    case null, bool(Bool), number(Double), string(String), array([NextJSON]), object([String: NextJSON])80    public init(from decoder: Decoder) throws {81        let c = try decoder.singleValueContainer()82        if c.decodeNil() { self = .null }83        else if let b = try? c.decode(Bool.self) { self = .bool(b) }84        else if let n = try? c.decode(Double.self) { self = .number(n) }85        else if let s = try? c.decode(String.self) { self = .string(s) }86        else if let a = try? c.decode([NextJSON].self) { self = .array(a) }87        else { self = .object(try c.decode([String: NextJSON].self)) }88    }89    public func encode(to encoder: Encoder) throws {90        var c = encoder.singleValueContainer()91        switch self {92        case .null: try c.encodeNil(); case .bool(let b): try c.encode(b); case .number(let n): try c.encode(n)93        case .string(let s): try c.encode(s); case .array(let a): try c.encode(a); case .object(let o): try c.encode(o)94        }95    }96    public var string: String? { if case .string(let s) = self { return s }; return nil }97    public var double: Double? { if case .number(let n) = self { return n }; return nil }98    public var int: Int? { double.map { Int($0) } }99    public var bool: Bool? { if case .bool(let b) = self { return b }; return nil }100    public var array: [NextJSON]? { if case .array(let a) = self { return a }; return nil }101    public var object: [String: NextJSON]? { if case .object(let o) = self { return o }; return nil }102    public subscript(key: String) -> NextJSON? { object?[key] }103    public var isNull: Bool { self == .null }104}105106/// One Server-Sent Event as it came off the wire.107public struct SSEMessage: Sendable, Equatable { public var event: String; public var data: String }108109/// Incremental parser of the `text/event-stream` format (events, multi-line data, comments).110public struct SSEParser: Sendable {111    private var event = "", data: [String] = []112    public init() {}113    /// Feeds one line (without its line break). Returns a message when the line completed one (a blank line).114    public mutating func feed(line: String) -> SSEMessage? {115        if line.isEmpty {116            defer { event = ""; data = [] }117            return data.isEmpty && event.isEmpty ? nil : SSEMessage(event: event.isEmpty ? "message" : event, data: data.joined(separator: "\n"))118        }119        if line.hasPrefix(":") { return nil } // a comment (": ping")120        let field: Substring, value: Substring121        if let colon = line.firstIndex(of: ":") { field = line[..<colon]; var v = line[line.index(after: colon)...]; if v.hasPrefix(" ") { v = v.dropFirst() }; value = v }122        else { field = Substring(line); value = "" }123        switch field { case "event": event = String(value); case "data": data.append(String(value)); default: break }124        return nil125    }126}127128/// The 2.0 client. A value type: cheap to create and to pass around.129public struct NextClient: Sendable {130    public let transport: NextTransport131    public init(_ transport: NextTransport) { self.transport = transport }132133    public static let decoder: JSONDecoder = {134        let d = JSONDecoder()135        d.dateDecodingStrategy = .custom { dec in136            let s = try dec.singleValueContainer().decode(String.self)137            if let date = NextClient.parseDate(s) { return date }138            throw DecodingError.dataCorrupted(.init(codingPath: dec.codingPath, debugDescription: "date: \(s)"))139        }140        return d141    }()142    public static let encoder: JSONEncoder = {143        let e = JSONEncoder()144        e.dateEncodingStrategy = .custom { date, enc in var c = enc.singleValueContainer(); try c.encode(NextClient.isoString(date)) }145        return e146    }()147    public static func parseDate(_ s: String) -> Date? {148        let f = ISO8601DateFormatter(); f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]149        if let d = f.date(from: s) { return d }150        f.formatOptions = [.withInternetDateTime]151        if let d = f.date(from: s) { return d }152        f.formatOptions = [.withFullDate]153        return f.date(from: s)154    }155    public static func isoString(_ d: Date) -> String { let f = ISO8601DateFormatter(); f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]; return f.string(from: d) }156157    // MARK: Requests158    /// A request for `/api/v1` + path, carrying the bearer token (when `authenticated`) and the client header.159    public func request(_ method: String, _ path: String, query: [String: String?] = [:], body: Data? = nil, contentType: String = "application/json",160                        headers: [String: String] = [:], authenticated: Bool = true) async throws -> URLRequest {161        guard var comps = URLComponents(url: transport.baseURL.appendingPathComponent("api/v1" + path), resolvingAgainstBaseURL: false) else { throw NextError.invalidResponse("bad URL") }162        let items = query.compactMap { k, v in v.map { URLQueryItem(name: k, value: $0) } }.sorted { $0.name < $1.name }163        if !items.isEmpty { comps.queryItems = items; comps.percentEncodedQuery = comps.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B") }164        guard let url = comps.url else { throw NextError.invalidResponse("bad URL") }165        var r = URLRequest(url: url)166        r.httpMethod = method167        r.setValue("application/json", forHTTPHeaderField: "Accept")168        if let c = transport.clientHeader { r.setValue(c, forHTTPHeaderField: "X-SPD-Client") }169        if authenticated {170            guard let token = try await transport.bearerToken(), !token.isEmpty else { throw NextError.unauthenticated }171            r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")172        }173        if let body { r.httpBody = body; r.setValue(contentType, forHTTPHeaderField: "Content-Type") }174        for (k, v) in headers { r.setValue(v, forHTTPHeaderField: k) }175        return r176    }177    /// Throws the server's error for a non-2xx answer.178    @discardableResult public static func check(_ data: Data, _ response: URLResponse) throws -> Data {179        guard let http = response as? HTTPURLResponse else { throw NextError.invalidResponse("no HTTP response") }180        if (200..<300).contains(http.statusCode) { return data }181        let body = (try? JSONDecoder().decode([String: NextJSON].self, from: data)) ?? [:]182        let code = body["error"]?.string ?? "http_\(http.statusCode)"183        if http.statusCode == 401 { throw NextError.unauthenticated }184        throw NextError.server(status: http.statusCode, code: code, message: body["message"]?.string ?? "", extra: body.filter { $0.key != "error" && $0.key != "message" })185    }186    public func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) {187        do {188            let (d, r) = try await transport.session.data(for: request)189            try NextClient.check(d, r)190            return (d, r as! HTTPURLResponse)191        } catch { throw NextError.wrap(error) }192    }193    func decode<T: Decodable>(_ type: T.Type = T.self, _ data: Data) throws -> T {194        do { return try NextClient.decoder.decode(T.self, from: data) } catch { throw NextError.invalidResponse("\(T.self): \(error)") }195    }196    public func get<T: Decodable>(_ path: String, query: [String: String?] = [:], authenticated: Bool = true) async throws -> T {197        try decode(T.self, try await data(for: try await request("GET", path, query: query, authenticated: authenticated)).0)198    }199    public func send<B: Encodable, T: Decodable>(_ method: String, _ path: String, query: [String: String?] = [:], body: B) async throws -> T {200        try decode(T.self, try await data(for: try await request(method, path, query: query, body: try NextClient.encoder.encode(body))).0)201    }202    public func send<T: Decodable>(_ method: String, _ path: String, query: [String: String?] = [:]) async throws -> T {203        try decode(T.self, try await data(for: try await request(method, path, query: query, body: method == "GET" || method == "DELETE" ? nil : Data("{}".utf8))).0)204    }205    struct OK: Decodable { var ok: Bool? }206207    // MARK: Server-Sent Events208    /// Opens an event stream and yields its messages until the connection ends (then the stream finishes) or fails209    /// (then it throws). An error answered before the stream starts (401, 429 `too_many_streams`, 4xx of `ai/ask`) is210    /// thrown as `NextError`. Reconnection is the caller's decision.211    /// - Parameter idleTimeout: seconds without a single byte (events or `: ping` comments) after which the stream is212    ///   declared dead and throws `.offline`. A server that stops without closing the connection is only noticed this213    ///   way. nil = wait for ever (answers that are not kept alive by pings, e.g. `ai/ask`, rely on the session's timeouts).214    public func events(_ request: URLRequest, idleTimeout: Double? = nil) -> AsyncThrowingStream<SSEMessage, Error> {215        let session = transport.session216        return AsyncThrowingStream { continuation in217            let lastByte = LastActivity()218            let task = Task {219                do {220                    var req = request; req.setValue("text/event-stream", forHTTPHeaderField: "Accept")221                    let (bytes, response) = try await session.bytes(for: req)222                    guard let http = response as? HTTPURLResponse else { throw NextError.invalidResponse("no HTTP response") }223                    if !(200..<300).contains(http.statusCode) {224                        var body = Data(); for try await b in bytes { body.append(b); if body.count > 65536 { break } }225                        try NextClient.check(body, response)226                    }227                    var parser = SSEParser(), line = [UInt8]()228                    for try await byte in bytes {229                        if byte == 0x0A {230                            lastByte.touch()231                            if line.last == 0x0D { line.removeLast() }232                            if let m = parser.feed(line: String(decoding: line, as: UTF8.self)) { continuation.yield(m) }233                            line.removeAll(keepingCapacity: true)234                        } else { line.append(byte) }235                    }236                    continuation.finish()237                } catch { continuation.finish(throwing: lastByte.expired ? NextError.offline("event stream silent") : NextError.wrap(error)) }238            }239            let watchdog = idleTimeout.map { limit in240                Task {241                    while !Task.isCancelled {242                        try? await Task.sleep(nanoseconds: UInt64(min(limit / 4, 5) * 1e9))243                        if lastByte.idle > limit { lastByte.expire(); task.cancel(); return }244                    }245                }246            }247            continuation.onTermination = { _ in task.cancel(); watchdog?.cancel() }248        }249    }250}251/// When the last line of a stream arrived (shared between the reader and its watchdog).252final class LastActivity: @unchecked Sendable {253    private let lock = NSLock(); private var at = Date(); private var dead = false254    func touch() { lock.withLock { at = Date() } }255    var idle: TimeInterval { lock.withLock { Date().timeIntervalSince(at) } }256    func expire() { lock.withLock { dead = true } }257    var expired: Bool { lock.withLock { dead } }258}259
Files main
Menu

Theme