Cotton code
148 lines · 6.2 KB · SwiftRaw
// Who is in a database — the membership facts (keys-sharing KS3) as the app// reads them, and the rules a screen applies before it offers anything.//// A member is a PERSON key admitted to a database with `member` or `admin`// rights. The owner is not a rights value: the database's maker, named by the// registry, who holds every right and can never be removed. The core reads// the database's own admission/removal facts and this device's live statement.import Foundation/// One person in a database, as the People screen draws them.public struct Member: Codable, Equatable, Hashable, Identifiable, Sendable {    /// What a person may do. Stored values only — the owner is a fact about    /// the database, not a right.    public enum Rights: String, Codable, Sendable {        /// Reads and writes records.        case member        /// Also admits and removes members.        case admin    }    /// The person's public key, base64url — the row id of `cotton_person_keys`.    public let personKey: String    public var name: String    public var rights: Rights    /// The database's maker. Holds every right; never removable.    public var isOwner: Bool    public var id: String { personKey }    public init(personKey: String, name: String, rights: Rights, isOwner: Bool = false) {        self.personKey = personKey        self.name = name        self.rights = rights        self.isOwner = isOwner    }    /// The key as a person reads it aloud: its first eight characters in two    /// groups of four. A key too short to have one is shown whole.    public var fingerprint: String { Fingerprint.of(personKey) ?? personKey }    /// The one word under the name.    public var rightsWord: String { isOwner ? "owner" : rights.rawValue }}/// The first eight characters of a key's base64url, in two groups of four —/// the same reading the Join screens give a device key.public enum Fingerprint {    public static let length = 8    public static let group = 4    public static func of(_ key: String?) -> String? {        let key = key?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""        guard key.count >= length else { return nil }        let head = Array(key.prefix(length))        return stride(from: 0, to: head.count, by: group)            .map { String(head[$0..<min($0 + group, head.count)]) }            .joined(separator: " ")    }}/// What one read of a database's membership answers.public struct MembersRead: Decodable, Equatable, Sendable {    public var members: [Member]    /// The person key THIS device signs as, when it is one of them — what the    /// screen's Remove is decided against.    public var me: String?    /// The core evaluates the signed membership and database kind.    public var canAdmit: Bool    public var admitReason: String?    public init(members: [Member], me: String? = nil, canAdmit: Bool, admitReason: String? = nil) {        self.members = members        self.me = me        self.canAdmit = canAdmit        self.admitReason = admitReason    }    private enum CodingKeys: String, CodingKey { case members, me, canAdmit, admitReason }    public init(from decoder: Decoder) throws {        let fields = try decoder.container(keyedBy: CodingKeys.self)        members = try fields.decode([Member].self, forKey: .members)        me = try fields.decodeIfPresent(String.self, forKey: .me)        canAdmit = try fields.decode(Bool.self, forKey: .canAdmit)        admitReason = try fields.decodeIfPresent(String.self, forKey: .admitReason)        guard canAdmit || admitReason?.isEmpty == false else {            throw DecodingError.dataCorruptedError(forKey: .admitReason, in: fields, debugDescription: "A denied admission requires its native reason.")        }    }}/// The rules of the People list. Pure, so a test can hold them.public enum Members {    /// The owner first, then everyone else by name; a tie by fingerprint, so    /// two people called the same thing keep one order on every device.    public static func ordered(_ members: [Member]) -> [Member] {        members.sorted { a, b in            if a.isOwner != b.isOwner { return a.isOwner }            let byName = a.name.localizedCaseInsensitiveCompare(b.name)            if byName != .orderedSame { return byName == .orderedAscending }            return a.personKey < b.personKey        }    }    /// Who may remove whom: the owner or an admin removes a member, and nobody    /// removes the owner. Nobody at all when this device's person is unknown.    public static func mayRemove(_ target: Member, by actor: Member?) -> Bool {        guard let actor, !target.isOwner else { return false }        return actor.isOwner || actor.rights == .admin    }    /// The refusal KS4 gives when the owner is named — kept here so the screen    /// never has to ask the server a question whose answer it knows.    public static let ownerCannotBeRemoved = "the owner of a database cannot be removed from it"}/// The membership calls a screen makes.public protocol MembersCalling: Sendable {    func members(of databaseId: String) async throws -> MembersRead    /// KS4's removal act — `databases.remove(person)`.    /// Answers the act's receipt ("Removed Rhyn from this database").    @discardableResult    func remove(_ personKey: String, from databaseId: String) async throws -> ActAnswer}/// Live facts from the window's database. The caller's identity is the core's/// answer; Swift never substitutes the database's owner for this device.public struct CoreMembers: MembersCalling {    private let core: any CottonCalling    public init(core: any CottonCalling) { self.core = core }    public func members(of databaseId: String) async throws -> MembersRead {        try await core.call(CottonMethod.readMembers, Scope(database: databaseId), as: MembersRead.self)    }    @discardableResult    public func remove(_ personKey: String, from databaseId: String) async throws -> ActAnswer {        try await core.pageAct("databases.remove", Removal(database: databaseId, personKey: personKey))    }    private struct Scope: Encodable { let database: String }    private struct Removal: Encodable {        let database: String        let personKey: String    }}