SPB Git

Repository Public

APIError.swift 8.4 KB 202 lines swift

1// SP Notes Core2// File: Sources/SPNotesAPI/APIError.swift3// Description: The single error type of the network layer: transport failures, HTTP errors with the server's stable4//              codes, and the two typed 409 answers (edit conflict, expensive AI request).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910/// The server copy returned by a refused `PATCH /api/pages/<id>` (`409 conflict`): nothing was written.11public struct PageConflict: Sendable, Equatable, Codable {12    public var version: Int13    public var title: String14    /// The document on the server (raw JSON).15    public var content: RawJSON16    /// The properties on the server (raw JSON object).17    public var properties: RawJSON18    public var updatedAt: Date1920    public init(version: Int, title: String, content: RawJSON, properties: RawJSON, updatedAt: Date) {21        self.version = version22        self.title = title23        self.content = content24        self.properties = properties25        self.updatedAt = updatedAt26    }27}2829/// Every failure of a backend call.30public enum APIError: Error, Sendable, Equatable {31    /// The device has no connectivity: the request did not leave.32    case offline33    /// The connection failed (DNS, TLS, connection lost, host unreachable…).34    case transport(URLError.Code)35    /// No answer in time. A mutating request may or may not have been applied: retry with the same idempotency key.36    case timeout37    /// The calling task was cancelled.38    case cancelled39    /// The answer is not an HTTP response the client understands.40    case invalidResponse41    /// A 2xx answer whose body does not match the expected shape.42    case decoding(String)43    /// A local file could not be read or written (upload source, download destination).44    case file(String)45    /// A non-2xx answer. `code` is the stable code of the backend when it sent one; `body` is the raw answer.46    case http(status: Int, code: String?, message: String, body: Data)47    /// `409 conflict` with the server copy: the page changed since `baseVersion`; nothing was written.48    case conflict(server: PageConflict, message: String)49    /// `409 confirm_expensive`: the AI request needs `confirmExpensive: true`; `plan` describes the cost.50    case confirmExpensive(plan: RawJSON, message: String)5152    // MARK: stable codes of the contract5354    public enum Code {55        public static let unauthenticated = "unauthenticated"56        public static let reauthRequired = "reauth_required"57        public static let csrf = "csrf"58        public static let conflict = "conflict"59        public static let badDocument = "bad_document"60        public static let rateLimited = "rate_limited"61        public static let notEnrolled = "not_enrolled"62        public static let confirmExpensive = "confirm_expensive"63        public static let notConfigured = "not_configured"64        public static let noModel = "no_model"65        public static let inProgress = "in_progress"66        public static let badIdempotencyKey = "bad_idempotency_key"67        public static let idempotencyMismatch = "idempotency_mismatch"68    }6970    // MARK: accessors7172    /// HTTP status, when the server answered.73    public var status: Int? {74        switch self {75        case .http(let status, _, _, _): return status76        case .conflict, .confirmExpensive: return 40977        default: return nil78        }79    }8081    /// Stable error code of the backend, when it sent one.82    public var code: String? {83        switch self {84        case .http(_, let code, _, _): return code85        case .conflict: return Code.conflict86        case .confirmExpensive: return Code.confirmExpensive87        default: return nil88        }89    }9091    /// Human-readable message (the server's `error` text for HTTP errors; English).92    public var message: String {93        switch self {94        case .offline: return "The device is offline."95        case .transport(let code): return "The connection failed (URLError \(code.rawValue))."96        case .timeout: return "The server did not answer in time."97        case .cancelled: return "Cancelled."98        case .invalidResponse: return "The server answer is not valid."99        case .decoding(let detail): return "The server answer could not be read: \(detail)"100        case .file(let detail): return "File error: \(detail)"101        case .http(_, _, let message, _): return message102        case .conflict(_, let message): return message103        case .confirmExpensive(_, let message): return message104        }105    }106107    /// The server copy of a refused page write.108    public var serverCopy: PageConflict? {109        if case .conflict(let server, _) = self { return server }110        return nil111    }112113    /// The cost plan of an AI request that needs confirmation.114    public var plan: RawJSON? {115        if case .confirmExpensive(let plan, _) = self { return plan }116        return nil117    }118119    // MARK: classification120121    /// `409 conflict`: the page (or the conflict being resolved) moved on the server.122    public var isConflict: Bool { status == 409 && code == Code.conflict }123124    /// `403 reauth_required`: run a step-up (`AuthService.stepUp()`) and send the request again.125    public var needsReauth: Bool { status == 403 && code == Code.reauthRequired }126127    /// `401`: there is no valid session any more (the client has already forgotten its token).128    public var isUnauthenticated: Bool { status == 401 }129130    /// `429`.131    public var isRateLimited: Bool { status == 429 }132133    public var isOffline: Bool { self == .offline }134135    public var isCancelled: Bool { self == .cancelled }136137    /// `404`.138    public var isNotFound: Bool { status == 404 }139140    /// Worth sending again later unchanged: offline, connection failures, timeouts, 5xx, 429 and `409 in_progress`141    /// (the first attempt with the same idempotency key is still running). `503 not_configured | no_model` are not:142    /// they need an action on the server.143    public var isRetryable: Bool {144        switch self {145        case .offline, .transport, .timeout: return true146        case .cancelled, .invalidResponse, .decoding, .file, .conflict, .confirmExpensive: return false147        case .http(let status, let code, _, _):148            if code == Code.inProgress { return true }149            if code == Code.notConfigured || code == Code.noModel { return false }150            return status == 429 || status == 408 || (500...599).contains(status)151        }152    }153154    // MARK: mapping155156    /// Builds the error of a non-2xx answer from its JSON body `{ error, code?, ...extra }`.157    public static func fromResponse(status: Int, body: Data) -> APIError {158        let json = try? JSONValue(parsing: body)159        let code = json?["code"]?.stringValue160        let message = json?["error"]?.stringValue ?? "HTTP \(status)"161        if status == 409, code == Code.conflict, let server = json?["server"],162           let copy = try? server.raw().decode(PageConflict.self) {163            return .conflict(server: copy, message: message)164        }165        if status == 409, code == Code.confirmExpensive, let plan = json?["plan"] {166            return .confirmExpensive(plan: plan.raw(), message: message)167        }168        return .http(status: status, code: code, message: message, body: body)169    }170171    /// Maps what `URLSession` (or Swift concurrency) throws.172    public static func fromTransport(_ error: Error) -> APIError {173        if let e = error as? APIError { return e }174        if error is CancellationError { return .cancelled }175        let ns = error as NSError176        guard ns.domain == NSURLErrorDomain else { return .transport(.unknown) }177        let code = URLError.Code(rawValue: ns.code)178        switch code {179        case .cancelled: return .cancelled180        case .timedOut: return .timeout181        case .notConnectedToInternet, .dataNotAllowed, .internationalRoamingOff: return .offline182        default: return .transport(code)183        }184    }185}186187extension APIError: LocalizedError {188    public var errorDescription: String? { message }189}190191extension APIError: CustomStringConvertible {192    /// Never includes the request (no cookie, no token).193    public var description: String {194        switch self {195        case .http(let status, let code, let message, _): return "APIError.http(\(status), \(code ?? "-"), \(message))"196        case .conflict(let server, _): return "APIError.conflict(server version \(server.version))"197        case .confirmExpensive(_, let message): return "APIError.confirmExpensive(\(message))"198        default: return "APIError(\(message))"199        }200    }201}202
Files main
Menu

Theme