Cotton code
220 lines · 10.5 KB · SwiftRaw
// Every definition a database draws — its tables, its boards, the theme it// wears — as ONE answer of the core (`definitions.catalogue`,// `crates/cotton-ffi/src/phone/catalogue.rs`), asked once per database and// kept until a definitions row of that database moves.//// ONE DECODER OF THE DEFINITION FORMAT (architect, 14 Oct 2026): the core// reads, resolves and decodes the definitions; the app draws what it hands// over. A database draws the tables its own definition rows describe and no// other (tools are records only, 21 Oct 2026); a stored definition the core// cannot draw is said once in Feedback by the core, and every served row the// answer leaves out of its tables — a storage table with no face, a row the// core refused — comes named with why (`undrawn`), for the reader to log.//// This side carries the answer as JSON, because what a definition MEANS is// CottonUI's; it checks only the shape, so a core speaking another shape is// refused here, plainly and whole.import Foundationimport os/// One database's catalogue, as the core answered it.public struct RawCatalogue: Sendable {    /// Each table the database draws, as its JSON.    public let tables: [Data]    /// Each table's id, at the same index as `tables` ("" when the table names    /// none) — so a reader that wants a few tables decodes only those.    public let tableIDs: [String]    /// Each table's page as the core resolved it (its parts and their    /// order), by the table's id — the app draws this and derives no page.    public let pages: [String: Data]    /// What the core says of each table, by the table's id (`TableSaid`).    public let said: [String: Data]    /// Each board by id, as `definitions.board` answered one.    public let boards: [String: DrawnBoard]    /// The theme the database wears.    public let theme: WornTheme    /// Every theme this build ships, by id, as its row's JSON.    public let themes: [String: Data]    /// The definition rows the database serves that it draws nowhere: a    /// storage table with no face (`kept_as_rows`), then a row the core could    /// not read (`refused`) — each by id with why. The reader says them once    /// (`DefinitionCatalogue.sayUndrawn`), never silently.    public let undrawn: [Undrawn]    /// The database the answer is of; nil in the last resort, which is of none.    public let database: String?}/// A served definition row the catalogue does not draw, and why.public struct Undrawn: Sendable, Equatable {    /// Whether the row is drawn nowhere by design (a storage table, kept as    /// rows) rather than refused.    public enum Kind: Sendable, Equatable { case keptAsRows, refused }    public let id: String    public let reason: String    public let kind: Kind    public init(id: String, reason: String, kind: Kind) {        self.id = id        self.reason = reason        self.kind = kind    }}public enum CatalogueRefusal: Error, Equatable, CustomStringConvertible {    /// The core speaks a shape this build does not read.    case shape(Int?)    /// The answer is not the object the shape describes.    case malformed(String)    public var description: String {        switch self {        case .shape(let shape):            return "This build reads shape \(DefinitionCatalogues.shape) of the definitions, and its core answered shape \(shape.map(String.init) ?? "none")."        case .malformed(let why):            return "The core's definitions could not be read: \(why)"        }    }}public final class DefinitionCatalogues: Sendable {    /// The shape of `definitions.catalogue` this build reads (`CATALOGUE_SHAPE`).    public static let shape = 10    /// The process's one cache: each core's databases, each asked once.    public static let shared = DefinitionCatalogues()    private struct Key: Hashable {        let core: ObjectIdentifier        let database: String    }    /// Held under a lock rather than on an actor, so an invalidation lands    /// before the redraw it causes reads again.    private let held = OSAllocatedUnfairLock<[Key: Held]>(initialState: [:])    /// One kept answer, and the core it was asked of — held weakly, so a    /// later core at the same address never reads another's answer.    private struct Held: @unchecked Sendable {        weak var core: AnyObject?        let task: Task<RawCatalogue, Error>    }    /// The catalogue of the database `core` names. Kept for a core that is an    /// object (the app's), asked afresh for any other.    public func catalogue(_ core: any CottonCalling) async throws -> RawCatalogue {        guard let (key, root) = Self.key(core) else { return try await Self.ask(core) }        let task = held.withLock { held in            if let kept = held[key], kept.core === root.object { return kept.task }            let task = Task { try await Self.ask(core) }            held[key] = Held(core: root.object, task: task)            return task        }        do {            return try await task.value        } catch {            // A failed ask is not kept: the next read asks again.            held.withLock { held in if held[key]?.task == task { held[key] = nil } }            throw error        }    }    /// A definitions row of `database` moved (nil: of any): its catalogue is    /// asked again at the next read. The personal database is also the one a    /// core with no scope names, so a named one clears that too.    public func invalidate(database: String?) {        held.withLock { held in            guard let database else { return held.removeAll() }            held = held.filter { $0.key.database != database && !$0.key.database.isEmpty }        }    }    /// This device wrote a definition of the database `core` names: its    /// catalogue is asked again at the next read, without waiting on the    /// write's event.    public func invalidate(_ core: any CottonCalling) {        let scoped = core as? DatabaseScopedCore        invalidate(database: scoped?.databaseID ?? "")    }    /// The tables whose moving changes a catalogue.    public static let tables: Set<String> = [        "cotton_table_definitions", "cotton_tool_definitions", "cotton_board_definitions", "cotton_theme_definitions",    ]    /// The core as an object, carried into the lock.    private struct Root: @unchecked Sendable { let object: AnyObject }    private static func key(_ core: any CottonCalling) -> (Key, Root)? {        let scoped = core as? DatabaseScopedCore        let root = scoped?.unscoped ?? core        guard type(of: root) is AnyClass else { return nil }        let object = root as AnyObject        return (Key(core: ObjectIdentifier(object), database: scoped?.databaseID ?? ""), Root(object: object))    }    /// Ask the core for a database's catalogue, or (`shipped`) for the    /// last-resort answer — this build's boards and themes, no table.    public static func ask(_ core: any CottonCalling, shipped: Bool = false) async throws -> RawCatalogue {        let raw = try await core.callRaw(CottonMethod.definitionsCatalogue, requestJSON: shipped ? #"{"shipped":true}"# : "{}")        guard let envelope = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [String: Any] else {            throw CatalogueRefusal.malformed("the answer is not an envelope")        }        guard envelope["ok"] as? Bool == true, let data = envelope["data"] else {            if let error = envelope["error"],                let said = try? JSONDecoder().decode(CottonCallError.self, from: JSONSerialization.data(withJSONObject: error))            {                throw said            }            throw CatalogueRefusal.malformed("the core refused without saying why")        }        return try read(JSONSerialization.data(withJSONObject: data))    }    /// Read one answer's JSON. The shape and the envelope are refused whole.    public static func read(_ data: Data) throws -> RawCatalogue {        guard let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else {            throw CatalogueRefusal.malformed("the answer is not a JSON object")        }        let shape = object["shape"] as? Int        guard shape == Self.shape else { throw CatalogueRefusal.shape(shape) }        guard let tables = object["tables"] as? [Any], let pages = object["pages"] as? [String: Any],            let boards = object["boards"] as? [String: Any],            let theme = object["theme"] as? [String: Any], let themes = object["themes"] as? [String: Any],            let kept = object["kept_as_rows"] as? [Any], let refused = object["refused"] as? [Any]        else { throw CatalogueRefusal.malformed(ShellLines.line("definitions", "catalogue.missing_sections")) }        func undrawn(_ rows: [Any], _ kind: Undrawn.Kind) throws -> [Undrawn] {            try rows.map { row in                guard let row = row as? [String: Any], let id = row["id"] as? String, let reason = row["reason"] as? String else {                    throw CatalogueRefusal.malformed(ShellLines.line("definitions", "catalogue.undrawn_missing_id"))                }                return Undrawn(id: id, reason: reason, kind: kind)            }        }        func json(_ value: Any) throws -> Data { try JSONSerialization.data(withJSONObject: value) }        func drawn(_ value: Any) throws -> (Data, String?) {            guard let resolved = value as? [String: Any], let definition = resolved["definition"] else {                throw CatalogueRefusal.malformed("a board or theme carries no definition")            }            return (try json(definition), resolved["passed_over"] as? String)        }        var drawnBoards: [String: DrawnBoard] = [:]        for (id, board) in boards {            let (definition, passedOver) = try drawn(board)            drawnBoards[id] = DrawnBoard(definition: definition, passedOver: passedOver)        }        let worn = try drawn(theme)        let own = (theme["drawn"] as? String) != WornTheme.defaultDrawn        return RawCatalogue(            tables: try tables.map(json),            tableIDs: tables.map { (($0 as? [String: Any])?["id"] as? String) ?? "" },            pages: try pages.mapValues(json),            said: try ((object["said"] as? [String: Any]) ?? [:]).mapValues(json),            boards: drawnBoards,            theme: WornTheme(definition: worn.0, passedOver: worn.1, own: own),            themes: try themes.mapValues(json),            undrawn: try undrawn(kept, .keptAsRows) + undrawn(refused, .refused),            database: object["database"] as? String        )    }}