SPB Git

Repository Public

ParityShared.swift 6.7 KB 149 lines swift

1// SP Notes Core2// File: Sources/SPNotesAPI/ParityShared.swift3// Description: What the "parity" route groups share (databases, search, graph links, inbox, research, AI bookkeeping,4//              agents, dashboard, settings): their stable error codes, typed error accessors and lenient decoding.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910/// The stable error codes of the 2.x route groups typed for parity with the web app (`APIError.code`). Many 2.x11/// errors carry NO code (`{"error": "Database not found"}`): test the HTTP status first, the code when there is one.12public enum ParityCode {13    // Databases14    /// `409` — the client id of a property, view or row belongs to another database (or the page id is in use).15    public static let idTaken = "id_taken"16    /// `409` — the client id belongs to a deleted row: restore it (`restoreDatabaseRows`) or use a new id.17    public static let rowDeleted = "row_deleted"18    // Inbox19    /// `409` — the capture has already been triaged.20    public static let notInInbox = "not_in_inbox"21    /// `400` — Smart Inbox apply with an empty selection.22    public static let nothingToApply = "nothing_to_apply"23    public static let badSection = "bad_section"24    public static let badDestination = "bad_destination"25    public static let badRelation = "bad_relation"26    /// `404` — Smart Inbox suggestions asked with `cachedOnly` and never generated.27    public static let notGenerated = "not_generated"28    /// `502` — the provider failed, refused or answered something unusable.29    public static let providerError = "provider_error"30    public static let refused = "refused"31    public static let badOutput = "bad_output"32    // Research33    /// `400` — not a DOI, or a reference without DOI asked to verify.34    public static let invalidDOI = "invalid_doi"35    /// `404` — Crossref does not know the DOI.36    public static let doiNotFound = "doi_not_found"37    /// `502/503` — Crossref cannot be reached: retry later.38    public static let crossrefUnreachable = "crossref_unreachable"39    public static let bibtexEmpty = "bibtex_empty"40    public static let fileTooLarge = "file_too_large"41    public static let typeMismatch = "type_mismatch"42    public static let badID = "bad_id"43    public static let badFormat = "bad_format"44    public static let tooManyIDs = "too_many_ids"45    // Agents46    /// `400` — not an agent of the catalogue.47    public static let unknownAgent = "unknown_agent"48    /// `409` — a run needs `confirmCost: true` (the owner saw the scope and the cost limit).49    public static let confirmRequired = "confirm_required"50    /// `400` — this agent needs a page.51    public static let pageRequired = "page_required"52    /// `409` — another run is pending or running; the body carries its `id`.53    public static let alreadyRunning = "already_running"54    /// `503` — the job queue is unreachable: nothing was started.55    public static let queueUnavailable = "queue_unavailable"56    /// `409` — only a failed job can be retried.57    public static let notFailed = "not_failed"58}5960extension APIError {61    /// `409 not_in_inbox`: the capture was triaged meanwhile (by another device): refresh the inbox.62    public var isNotInInbox: Bool { status == 409 && code == ParityCode.notInInbox }6364    /// `409 row_deleted`: the client id of a database row belongs to a deleted row.65    public var isRowDeleted: Bool { status == 409 && code == ParityCode.rowDeleted }6667    /// `409 id_taken`: the client id is used by something else.68    public var isIDTaken: Bool { status == 409 && code == ParityCode.idTaken }6970    /// `409 confirm_required`: an agent run must be confirmed by the owner (`confirmCost: true`).71    public var needsCostConfirmation: Bool { status == 409 && code == ParityCode.confirmRequired }7273    /// The execution already pending or running (`409 already_running` of `POST /api/agents`).74    public var runningExecutionID: String? {75        guard status == 409, code == ParityCode.alreadyRunning else { return nil }76        return detailString("id")77    }78}7980// MARK: - Lenient decoding (internal)8182/// A few aggregate routes let PostgreSQL types through as text (`count(*)` → `"4"`): read numbers from either form.83extension KeyedDecodingContainer {84    func lenientInt(_ key: Key) -> Int? {85        if let v = try? decodeIfPresent(Int.self, forKey: key) { return v }86        if let v = try? decodeIfPresent(Double.self, forKey: key) { return Int(v) }87        if let v = try? decodeIfPresent(String.self, forKey: key) { return Int(v) ?? Double(v).map { Int($0) } }88        return nil89    }9091    func lenientDouble(_ key: Key) -> Double? {92        if let v = try? decodeIfPresent(Double.self, forKey: key) { return v }93        if let v = try? decodeIfPresent(String.self, forKey: key) { return Double(v) }94        return nil95    }9697    /// A date in any form `APIDate` reads; `nil` when absent, null or unreadable (never throws).98    func lenientDate(_ key: Key) -> Date? {99        guard let text = try? decodeIfPresent(String.self, forKey: key) else { return nil }100        return APIDate.parse(text)101    }102103    /// A raw JSON value, `nil` when the key is absent or null.104    func rawIfPresent(_ key: Key) -> RawJSON? {105        guard contains(key), (try? decodeNil(forKey: key)) == false else { return nil }106        return try? decode(RawJSON.self, forKey: key)107    }108}109110extension JSONValue {111    var arrayValue: [JSONValue]? { if case .array(let a) = self { return a }; return nil }112    var intValue: Int? {113        switch self {114        case .int(let i): return Int(i)115        case .double(let d): return Int(d)116        case .string(let s): return Int(s)117        default: return nil118        }119    }120}121122extension RawJSON {123    /// The value of a key of a JSON object, as raw JSON (`nil` when absent or null).124    func member(_ key: String) -> JSONValue? {125        guard let value = (try? JSONValue(parsing: data))?[key], !value.isNull else { return nil }126        return value127    }128}129130extension NotesAPI {131    static func segment(_ id: String) -> String { HTTPRequest.segment(id) }132133    static func item(_ name: String, _ value: String?) -> [URLQueryItem] {134        value.map { [URLQueryItem(name: name, value: $0)] } ?? []135    }136137    static func flag(_ name: String, _ on: Bool) -> [URLQueryItem] {138        on ? [URLQueryItem(name: name, value: "1")] : []139    }140141    /// Sends a request whose answer is text (CSV, BibTeX, LaTeX) and returns it with its headers.142    func text(_ request: HTTPRequest, accept: String) async throws -> (text: String, response: HTTPResponse) {143        var request = request144        request.accept = accept145        let response = try await client.send(request)146        return (String(decoding: response.data, as: UTF8.self), response)147    }148}149
Files main
Menu

Theme