// The databases this device holds, at the boundary. // // A person has ONE personal database — made at first run, nobody else can // enter, the default — and any number of project databases, each its own file // (owner decision 3 Oct 2026, Cotton notes 174779b2 and 0a22168c). The app // shows one at a time; only Today, search and "Asked of you" read across. // // This file is the Swift half of that: the row a held database is, the order // the Databases screen draws them in, the name rule, the toolkits // "What is it for?" offers, and the wrapper that names the shown database on // every call. `DatabasesCalling` is the seam and `CoreDatabases` answers it // over the core's own `read.databases`, `databases.show` / `databases.hide` // and `databases.create`. import Foundation /// One database this device holds. public struct HeldDatabase: Codable, Equatable, Hashable, Identifiable, Sendable { public enum Kind: String, Codable, Sendable { case personal case shared } /// What this person may do in a database. public enum Rights: String, Codable, Sendable { case owner case admin case member } public let databaseId: String public var name: String public var kind: Kind /// Who else is in it, by first name; empty is "only you". public var people: [String] /// This person's rights in it. The switcher refreshes these from the /// live membership; a list without rights never grants administration. public var rights: Rights /// The cap colour the people in it chose, by its name (`CapColour`'s raw /// value), or `nil` for the one the app assigns from the held ids. public var colour: String? /// Where this database's copy stands on this device when it is not here /// yet (`read.databases`' `arrival`); `nil` once it has arrived. public var arrival: DatabaseArrival? /// Joined at ANOTHER PERSON'S Mac (`read.databases`' `theirs`): this /// device holds no name for the Mac that serves it, so its page says /// "their Mac not reachable" and never a name. public var theirs: Bool /// Why this device could not read its own copy just now /// (`read.databases`' `unreadable`); `nil` when it reads. The row stays /// on the sheet and says so — 12 Oct 2026, one unreadable file emptied /// the owner's whole sheet. public var unreadable: String? public var id: String { databaseId } /// Its copy is on its way: nothing in it can be read yet, and the screen /// says so on the cap rather than as an error. public var isArriving: Bool { arrival != nil } public var isPersonal: Bool { kind == .personal } /// Admit a person is offered only on a shared database, to its owner or /// an admin — never on the personal one. public var canAdmit: Bool { kind == .shared && rights != .member } public init( databaseId: String, name: String, kind: Kind, people: [String] = [], rights: Rights = .owner, colour: String? = nil, arrival: DatabaseArrival? = nil, theirs: Bool = false, unreadable: String? = nil ) { self.databaseId = databaseId self.name = name self.kind = kind self.people = people self.rights = rights self.colour = colour self.arrival = arrival self.theirs = theirs self.unreadable = unreadable } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) databaseId = try container.decode(String.self, forKey: .databaseId) name = try container.decode(String.self, forKey: .name) kind = try container.decodeIfPresent(Kind.self, forKey: .kind) ?? .shared people = try container.decodeIfPresent([String].self, forKey: .people) ?? [] rights = try container.decodeIfPresent(Rights.self, forKey: .rights) ?? .member colour = try container.decodeIfPresent(String.self, forKey: .colour) arrival = try container.decodeIfPresent(DatabaseArrival.self, forKey: .arrival) theirs = try container.decodeIfPresent(Bool.self, forKey: .theirs) ?? false unreadable = try container.decodeIfPresent(String.self, forKey: .unreadable) } /// The quiet line under a database's name: the cap, the board head and /// the Settings row all read this one line. A database this device was /// removed from is never a row here — `read.databases` leaves it out, and /// its copy is in the Bin on this device (architect's ruling, 16 Oct 2026). public var peopleLine: String { if let arrival { return arrival.line } if let unreadable { return "can't be read: " + unreadable } return people.isEmpty ? "only you" : "with " + people.joined(separator: ", ") } } /// Where a held database's copy stands while it is not on this device yet — /// a state the cap draws, never an error. public struct DatabaseArrival: Codable, Equatable, Hashable, Sendable { public enum State: String, Codable, Sendable { /// Listed, and no byte of it has moved yet. case waiting /// Its body is coming: `bytesWritten` of `totalBytes`. case arriving /// The last try stopped; the next starts by itself. case failed } public var state: State public var bytesWritten: Int? public var totalBytes: Int? public var reason: String? public init(state: State, bytesWritten: Int? = nil, totalBytes: Int? = nil, reason: String? = nil) { self.state = state self.bytesWritten = bytesWritten self.totalBytes = totalBytes self.reason = reason } /// Bytes have moved: never back, and a figure with a whole beats one without. public func moved(written: Int, total: Int?) -> DatabaseArrival { let whole = total ?? totalBytes let kept = whole == totalBytes ? max(written, bytesWritten ?? 0) : written return DatabaseArrival(state: .arriving, bytesWritten: kept, totalBytes: whole) } /// The line under the cap: "9 of 11 MB" while it comes. public var line: String { switch state { case .waiting: return "arriving" case .failed: return "arriving — trying again" case .arriving: let written = Self.megabytes(bytesWritten ?? 0) guard let totalBytes else { return "\(written) MB so far" } return "\(written) of \(Self.megabytes(totalBytes)) MB" } } /// The one calm sentence a page of it shows in place of its contents. public func sentence(name: String) -> String { switch state { case .arriving where totalBytes != nil: return "\(name) is arriving — \(line)." default: return "\(name) is arriving on this device. It opens here when its copy has come." } } private static func megabytes(_ bytes: Int) -> Int { (bytes + 1_048_575) / 1_048_576 } } /// A database the person joined on ANOTHER of their devices that this device /// does not hold — `read.databases`' `elsewhere`, from the synced /// `cotton_joined_places`. The switcher offers each, and `databases.present` /// fetches it here as another device of the same person. public struct ElsewhereDatabase: Decodable, Equatable, Hashable, Identifiable, Sendable { public let databaseId: String public let name: String /// The serving Mac's address, as the device that joined recorded it. public let origin: String public let serverDeviceId: String public var id: String { databaseId } public init(databaseId: String, name: String, origin: String = "", serverDeviceId: String = "") { self.databaseId = databaseId self.name = name self.origin = origin self.serverDeviceId = serverDeviceId } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) databaseId = try container.decode(String.self, forKey: .databaseId) name = try container.decodeIfPresent(String.self, forKey: .name) ?? "" origin = try container.decodeIfPresent(String.self, forKey: .origin) ?? "" serverDeviceId = try container.decodeIfPresent(String.self, forKey: .serverDeviceId) ?? "" } private enum CodingKeys: String, CodingKey { case databaseId, name, origin, serverDeviceId } /// The quiet line under its cap. public static let capLine = "on your other device — tap to get it here" } /// The whole `read.databases` answer: what this device holds, what its /// windows pin, and what the person holds on another device only. `shown` /// and `elsewhere` may be absent (an older core): both read as empty. public struct DatabasesListing: Decodable, Equatable, Sendable { public var databases: [HeldDatabase] public var shown: [String] public var elsewhere: [ElsewhereDatabase] public init(databases: [HeldDatabase], shown: [String] = [], elsewhere: [ElsewhereDatabase] = []) { self.databases = databases self.shown = shown self.elsewhere = elsewhere } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) databases = try container.decode([HeldDatabase].self, forKey: .databases) shown = try container.decodeIfPresent([String].self, forKey: .shown) ?? [] elsewhere = try container.decodeIfPresent([ElsewhereDatabase].self, forKey: .elsewhere) ?? [] } private enum CodingKeys: String, CodingKey { case databases, shown, elsewhere } } /// What `databases.present` answers: the database is joined here. A copy that /// did not arrive yet says `copyPending` with the reason in `message`; the /// next pass over the joined databases fetches it. public struct PresentedDatabase: Decodable, Equatable, Sendable { public let databaseId: String public let joined: Bool public let written: Bool public let copyPending: Bool public let message: String? public init(databaseId: String, joined: Bool = true, written: Bool = true, copyPending: Bool = false, message: String? = nil) { self.databaseId = databaseId self.joined = joined self.written = written self.copyPending = copyPending self.message = message } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) databaseId = try container.decode(String.self, forKey: .databaseId) joined = try container.decodeIfPresent(Bool.self, forKey: .joined) ?? true written = try container.decodeIfPresent(Bool.self, forKey: .written) ?? true copyPending = try container.decodeIfPresent(Bool.self, forKey: .copyPending) ?? false message = try container.decodeIfPresent(String.self, forKey: .message) } private enum CodingKeys: String, CodingKey { case databaseId, joined, written, copyPending, message } } /// The order every surface draws databases in: the personal one first, then /// the project databases in the order they were given (the owner's own). public enum DatabaseOrder { public static func shown(_ databases: [HeldDatabase]) -> [HeldDatabase] { databases.filter(\.isPersonal) + databases.filter { !$0.isPersonal } } /// The database to open on: the last one opened if it is still held, /// else the personal one. public static func opening(last: String?, in databases: [HeldDatabase]) -> HeldDatabase? { let order = shown(databases) return order.first { $0.databaseId == last } ?? order.first } } /// The name a new database may take. public enum DatabaseName { /// The personal database's name, reserved: the server refuses it at make /// and at adoption, and the phone refuses it before either. public static let personal = "Personal" /// Why this name cannot be used, or nil when it can. public static func refusal(_ name: String, held: [HeldDatabase] = []) -> String? { let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) if trimmed.isEmpty { return "Give the database a name." } let taken = [personal] + held.filter(\.isPersonal).map(\.name) if taken.contains(where: { $0.caseInsensitiveCompare(trimmed) == .orderedSame }) { return "\(trimmed) is your own database's name. Choose another." } return nil } } /// What "What is it for?" offers. A toolkit is a template, not a kind: it only /// decides which tools the new database starts with, and two databases may be /// made from one toolkit. public struct DatabaseToolkit: Decodable, Equatable, Hashable, Identifiable, Sendable { public let id: String public let name: String public let startingTools: [String] public init(id: String, name: String, startingTools: [String] = []) { self.id = id; self.name = name; self.startingTools = startingTools } public static let all: [DatabaseToolkit] = [ DatabaseToolkit(id: "family", name: "Family"), DatabaseToolkit(id: "partner", name: "Me & partner"), DatabaseToolkit(id: "friends", name: "Friends"), DatabaseToolkit(id: "tech-team", name: "Tech team"), DatabaseToolkit(id: "yoga-studio", name: "Yoga studio"), DatabaseToolkit(id: "yoga-trainer", name: "Yoga trainer"), DatabaseToolkit(id: "teaching", name: "Teaching"), DatabaseToolkit(id: "blank", name: "Blank"), ] } extension CottonMethod { /// The databases this device holds, personal first. Read off the /// connection record: listing opens no file. public static let readDatabases = "read.databases" public static let readDatabase = "read.database" /// What every device of the person keeps of one database (Spec 10.5). public static let readDatabaseStorage = "read.databaseStorage" /// One window starts drawing a database. The pin is COUNTED: one `show` /// per window, undone by one `hide`. public static let databasesShow = "databases.show" /// One window stopped drawing a database. public static let databasesHide = "databases.hide" /// Make a database beside the personal one. The serving Mac makes it on /// its server; every other device mints the file itself, with no network. public static let databasesCreate = "databases.create" public static let databasesToolkits = "databases.toolkits" } /// The calls the Databases screen makes. public protocol DatabasesCalling: Sendable { /// Every database this device holds. func databases() async throws -> [HeldDatabase] func toolkits() async throws -> [DatabaseToolkit] /// One window starts drawing this database: pin it, so no pass closes it. func show(_ databaseId: String) async throws /// One window stopped drawing this database: undo that window's pin. func hide(_ databaseId: String) async throws /// Make a database, here and now, from a toolkit. func create(name: String, toolkit: DatabaseToolkit) async throws -> HeldDatabase /// `read.database` — the database page's facts (Spec 10.2). func page(_ databaseId: String) async throws -> DatabasePage /// `read.databaseStorage` — what each device keeps of the database (Spec 10.5). func storage(_ databaseId: String) async throws -> DatabaseStorage /// The whole `read.databases` answer, with what the person holds on /// another device only. func listing() async throws -> DatabasesListing /// `databases.leave` — this device forgets a shared database and tells /// the Mac that served it; answers whether that Mac has been told now. func leave(_ databaseId: String) async throws -> Bool /// `databases.present` — fetch a database the person joined on another /// device, as another device of the same person. func present(_ databaseId: String) async throws -> PresentedDatabase } extension DatabasesCalling { public func toolkits() async throws -> [DatabaseToolkit] { DatabaseToolkit.all } /// A source that knows only what it holds holds nothing elsewhere. public func listing() async throws -> DatabasesListing { DatabasesListing(databases: try await databases()) } public func present(_ databaseId: String) async throws -> PresentedDatabase { throw CottonCallError(code: "unknown_method", message: CottonCallError.notOnThisDevice) } public func leave(_ databaseId: String) async throws -> Bool { throw CottonCallError(code: "unknown_method", message: CottonCallError.notOnThisDevice) } public func page(_ databaseId: String) async throws -> DatabasePage { throw CottonCallError(code: "unknown_method", message: CottonCallError.notOnThisDevice) } public func storage(_ databaseId: String) async throws -> DatabaseStorage { throw CottonCallError(code: "unknown_method", message: CottonCallError.notOnThisDevice) } } /// The core's own answers. public struct CoreDatabases: DatabasesCalling { private let core: any CottonCalling /// What this device is called, sent with `databases.present` so the /// serving Mac's device list names it. private let deviceName: String? private let publicKey: @Sendable () async throws -> String? private let privateKey: @Sendable () async throws -> String private let pause: @Sendable () async throws -> Void public init( core: any CottonCalling, deviceName: String? = nil, publicKey: @escaping @Sendable () async throws -> String? = { try await Task.detached { try VaultKeyring().publicKey() }.value }, privateKey: @escaping @Sendable () async throws -> String = { try await Task.detached { try VaultKeyring().privateKey() }.value }, pause: @escaping @Sendable () async throws -> Void = { try await Task.sleep(for: .seconds(1)) } ) { self.core = core self.deviceName = deviceName self.publicKey = publicKey self.privateKey = privateKey self.pause = pause } private struct Present: Encodable { let databaseId: String let name: String? let platform: String } /// The platform `databases.present` names this device by. #if os(macOS) static let platform = "mac" #else static let platform = "ios" #endif private struct Pin: Encodable { let databaseId: String } private struct Make: Encodable { let name: String let toolkit: String } private struct Made: Decodable { let id: String let name: String } private struct Kits: Decodable { let toolkits: [DatabaseToolkit] } public func toolkits() async throws -> [DatabaseToolkit] { try await core.call(CottonMethod.databasesToolkits, as: Kits.self).toolkits } public func page(_ databaseId: String) async throws -> DatabasePage { try await core.call(CottonMethod.readDatabase, PageOf(databaseId: databaseId), as: DatabasePage.self) } private struct PageOf: Encodable { let databaseId: String } public func storage(_ databaseId: String) async throws -> DatabaseStorage { try await core.call(CottonMethod.readDatabaseStorage, StorageOf(database: databaseId), as: DatabaseStorage.self) } private struct StorageOf: Encodable { let database: String } public func databases() async throws -> [HeldDatabase] { try await listing().databases } public func listing() async throws -> DatabasesListing { try await core.call(CottonMethod.readDatabases, as: DatabasesListing.self) } public func present(_ databaseId: String) async throws -> PresentedDatabase { let name = deviceName?.trimmingCharacters(in: .whitespacesAndNewlines) func ask() async throws -> PresentedDatabase { try await core.call( CottonMethod.databasesPresent, Present(databaseId: databaseId, name: name?.isEmpty == false ? name : nil, platform: Self.platform), as: PresentedDatabase.self ) } do { return try await ask() } catch let error as CottonCallError where ["vault_locked", "vault_key_unpublished", "no_person_key"].contains(error.code) { // The person key signs the device statement only while the vault // is unlocked: the same publish-and-unlock a make and a join run, // then the one second ask. try await unlockVault(or: error) return try await ask() } } /// Leave a shared database: the Mac that served it is told by a removal /// the person key signs, so the vault is unlocked the way `present` does /// when the core says it is locked — nothing is forgotten until then. public func leave(_ databaseId: String) async throws -> Bool { struct Left: Decodable { let serverTold: Bool } func ask() async throws -> Bool { try await core.call(CottonMethod.databasesLeave, Pin(databaseId: databaseId), as: Left.self).serverTold } do { return try await ask() } catch let error as CottonCallError where ["vault_locked", "vault_key_unpublished", "no_person_key"].contains(error.code) { try await unlockVault(or: error) return try await ask() } } /// Publish this device's vault key and unlock the vault behind Keychain /// presence, as a make and a join do; `error` stands when there is no key. private func unlockVault(or error: CottonCallError) async throws { struct PublicKey: Encodable { let publicKey: String } guard let publicKey = try await publicKey(), !publicKey.isEmpty else { throw error } try Task.checkCancellation() _ = try await core.callJSON("vault.publishKey", PublicKey(publicKey: publicKey)) let secret = try await privateKey() try Task.checkCancellation() try await PersonalSigner.unlock(core: core, privateKey: secret, pause: pause) } public func show(_ databaseId: String) async throws { _ = try await core.callJSON(CottonMethod.databasesShow, Pin(databaseId: databaseId)) } public func hide(_ databaseId: String) async throws { _ = try await core.callJSON(CottonMethod.databasesHide, Pin(databaseId: databaseId)) } public func create(name: String, toolkit: DatabaseToolkit) async throws -> HeldDatabase { func make() async throws -> Made { try await core.call(CottonMethod.databasesCreate, Make(name: name, toolkit: toolkit.id), as: Made.self) } let made: Made do { made = try await make() } catch let error as CottonCallError where ["creator_identity_unavailable", "vault_locked", "no_person_key"].contains(error.code) { // Creating a database signs its owner's membership. The private // vault key stays behind Keychain presence, as it does for Reveal. try await unlockVault(or: error) made = try await make() } return HeldDatabase(databaseId: made.id, name: made.name, kind: .shared) } } /// The database one window's screens are reading, as its calls see it: the /// shown project database's id, or nil for the personal one. One per window, /// set by that window's scene when it turns to another database. public final class ShownDatabase: @unchecked Sendable { private let lock = NSLock() private var shown: String? public init(_ id: String? = nil) { shown = id } public var id: String? { get { lock.withLock { shown } } set { lock.withLock { shown = newValue } } } } /// The shown database, reaching every call: `database` beside the screen's own /// arguments, for every method, when the shown database is not the device's /// own. The personal database is the attachment and needs no name. public struct DatabaseScopedCore: CottonCalling { private let underlying: any CottonCalling private let shown: ShownDatabase /// - Parameter database: the shown project database, or nil for the /// personal one. public init(underlying: any CottonCalling, database: String?) { self.init(underlying: underlying, shown: ShownDatabase(database)) } /// One window's calls: each names the database the window shows at the /// moment it is made. public init(underlying: any CottonCalling, shown: ShownDatabase) { self.underlying = underlying self.shown = shown } /// The core under the scope, and the database the scope names now — what /// a database's definitions are cached by (`DefinitionCatalogues`). public var unscoped: any CottonCalling { underlying } public var databaseID: String? { shown.id } public func callRaw(_ method: String, requestJSON: String) async throws -> String { try await underlying.callRaw(method, requestJSON: Self.request(requestJSON, database: shown.id)) } public func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async { await underlying.subscribe(handler) } public func close() async { await underlying.close() } /// The request with `database` at its top level. Unchanged for the /// personal database, for a request that already names one — at its top /// level or in its `args`, where a scaffolded read carries its arguments /// (a feed reading `"all"`, a link opening a record in its own database) — /// and for a body that is not a JSON object. public static func request(_ json: String, database: String?) -> String { guard let database, let parsed = try? JSONSerialization.jsonObject(with: Data(json.utf8)), var object = parsed as? [String: Any], object["database"] == nil, (object["args"] as? [String: Any])?["database"] == nil else { return json } object["database"] = database guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) else { return json } return String(decoding: data, as: UTF8.self) } } /// `read.databaseStorage {database}` (Spec 10.5): what each of the person's /// devices keeps of one database — this one measured now, another as it last /// reported. A device that never measured answers `nil`, never zero. public struct DatabaseStorage: Decodable, Equatable, Sendable { public let devices: [Device] public struct Device: Decodable, Equatable, Sendable { public let deviceId: String public let name: String public let thisDevice: Bool public let keptBytes: Int? public let freeableBytes: Int? public init(deviceId: String, name: String, thisDevice: Bool, keptBytes: Int? = nil, freeableBytes: Int? = nil) { self.deviceId = deviceId self.name = name self.thisDevice = thisDevice self.keptBytes = keptBytes self.freeableBytes = freeableBytes } } public init(devices: [Device]) { self.devices = devices } } /// `read.database {databaseId}` (Spec 10.2): one database's page in one read. public struct DatabasePage: Decodable, Equatable, Sendable { public let databaseId: String public let name: String public let colour: String? public let personal: Bool public let canLeave: Bool /// What THIS device keeps of it; `nil` while the storage rules have not measured it. public let keptHere: KeptHere? public struct KeptHere: Decodable, Equatable, Sendable { public let heldBytes: Int public let freeableBytes: Int public let heldCount: Int public init(heldBytes: Int, freeableBytes: Int, heldCount: Int) { self.heldBytes = heldBytes self.freeableBytes = freeableBytes self.heldCount = heldCount } } public init(databaseId: String, name: String, colour: String? = nil, personal: Bool, canLeave: Bool, keptHere: KeptHere? = nil) { self.databaseId = databaseId self.name = name self.colour = colour self.personal = personal self.canLeave = canLeave self.keptHere = keptHere } }