Cotton code
220 lines · 10.3 KB · RustRaw
//! WHICH DATABASE THIS APP SHOWS — the manifest's `database` (owner, 19 Oct//! 2026: one app, one database). Cotton shows Personal alone; Cotton Project//! and every business app show the one database their manifest names by id,//! at the host it names; a build with no manifest (the Mac, a test) shows//! every database it holds.//!//! When genesis is `personal`, the app holds Personal for its person key,//! vault key, voice words and feedback. A `none` flavour joins its business//! without founding Personal; an existing synthetic Personal stays held.//! An app that shows another database never shows Personal: it is not in the list of//! databases, a call that names no database is the shown one's, the feeds//! cross only the shown one, and a call that names Personal is refused. A//! database the manifest does not name is never fetched at all//! (`ClientController::fill_listed`).use serde_json::Value;/// What the manifest's `database` says.#[derive(Debug, Clone, PartialEq, Eq, Default)]pub enum DatabaseScope {    /// No `database`: every database this device holds.    #[default]    Every,    /// `"personal"`: the device's own and nothing else.    Personal,    /// `{"id": "<database id>", "host": "<origin>", "named": "<name>"}`: that    /// one database, by its id, and Personal held but never shown. The host is    /// where the app signs in (the join screen reads it); the name is how a    /// sentence says the database.    One { id: String, name: Option<String> },}/// The words a refusal of a manifest's `database` says.const SHAPE: &str = "a manifest's database is \"personal\" or {\"id\": \"<database id>\", \"host\": \"<https origin>\", \"named\": \"<name>\"}";impl DatabaseScope {    /// The manifest's word, or a refusal naming what it says instead.    pub fn of(manifest: Option<&Value>) -> Result<Self, String> {        let Some(said) = manifest.and_then(|manifest| manifest.get("database")) else {            return Ok(Self::Every);        };        match said {            Value::String(word) if word == "personal" => Ok(Self::Personal),            Value::Object(one) => {                let text = |key: &str| match one.get(key) {                    None => Ok(None),                    Some(Value::String(text)) if !text.trim().is_empty() => Ok(Some(text.clone())),                    Some(_) => Err(format!("{SHAPE}, not {said}")),                };                if one.keys().any(|key| !matches!(key.as_str(), "id" | "host" | "named")) {                    return Err(format!("{SHAPE}, not {said}"));                }                let Some(id) = text("id")? else {                    return Err(format!("{SHAPE} — this one names no database id"));                };                match text("host")? {                    Some(host) if host.starts_with("https://") || host.starts_with("http://") => {}                    _ => return Err(format!("{SHAPE} — this one names no host to sign in at")),                }                Ok(Self::One { id, name: text("named")? })            }            other => Err(format!("{SHAPE}, not {other}")),        }    }    /// How a sentence says the one database: its name, or its id.    pub fn said(&self) -> Option<&str> {        match self {            Self::One { id, name } => Some(name.as_deref().unwrap_or(id)),            _ => None,        }    }    /// Whether a database the household lists, other than the device's own,    /// may be held by this app — by its id, never its name, which a rename    /// changes.    pub fn admits(&self, database: &str) -> bool {        match self {            Self::Every => true,            Self::Personal => false,            Self::One { id, .. } => id == database,        }    }    /// Whether the device's own Personal is shown.    pub fn shows_personal(&self) -> bool {        !matches!(self, Self::One { .. })    }    /// Whether a held database is shown: Personal when the scope shows it,    /// another when the scope admits its id.    pub fn shows(&self, personal: bool, database: &str) -> bool {        if personal {            self.shows_personal()        } else {            self.admits(database)        }    }}/// Where the scope is kept beside the connection record, for the sync and open/// paths that are handed only the layout: written when the scope is set,/// removed at an open whose manifest names none, so it is always this/// launch's word and never an earlier build's.fn file(layout: &cotton_client::layout::Layout) -> std::path::PathBuf {    layout.client_dir().join("scope.json")}/// Keep `scope` for this container ([`file`]); `Every` keeps nothing.pub fn keep(layout: &cotton_client::layout::Layout, scope: &DatabaseScope) -> Result<(), String> {    let path = file(layout);    let word = match scope {        DatabaseScope::Every => {            // not a copy: the scope file.            return match std::fs::remove_file(&path) {                Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.to_string()),                _ => Ok(()),            };        }        DatabaseScope::Personal => serde_json::json!({"database": "personal"}),        // The host is the manifest's to say at every open; what is kept here        // is only what the sync paths admit (`kept`).        DatabaseScope::One { id, name } => serde_json::json!({"kept": {"id": id, "named": name}}),    };    std::fs::create_dir_all(layout.client_dir()).map_err(|error| error.to_string())?;    // not a copy: the scope file.    std::fs::write(&path, word.to_string()).map_err(|error| error.to_string())}/// This container's scope as last kept; none kept is every database. One that/// does not read is Personal alone — the narrowest, never the widest.pub fn kept(layout: &cotton_client::layout::Layout) -> DatabaseScope {    let Ok(bytes) = std::fs::read(file(layout)) else { return DatabaseScope::Every };    let Ok(word) = serde_json::from_slice::<Value>(&bytes) else { return DatabaseScope::Personal };    match word.get("kept") {        Some(one) => match one.get("id").and_then(Value::as_str) {            Some(id) if !id.is_empty() => DatabaseScope::One {                id: id.to_string(),                name: one.get("named").and_then(Value::as_str).map(str::to_string),            },            _ => DatabaseScope::Personal,        },        None => DatabaseScope::of(Some(&word)).unwrap_or(DatabaseScope::Personal),    }}/// The connection record with only the places this scope admits — what the/// held, synced and opened sets are read from, so a database outside the/// app's scope is neither opened nor synced, though its file stays on disk.pub fn admitted(    mut record: cotton_client::connection::ConnectionRecord,    scope: &DatabaseScope,) -> cotton_client::connection::ConnectionRecord {    record.places.retain(|place| scope.admits(&place.id));    record}/// The sentence a call naming a database this app does not show is refused with.pub const NOT_SHOWN: &str = "This app does not show that database.";#[cfg(test)]mod tests {    use super::*;    use serde_json::json;    // RULE: a manifest's `database` is "personal" or one database named by its id and the host it signs in at (owner's 62nd–64th rulings: the app opens only the database its manifest names); absent is every database. A database with no id, no host, or a misspelt word is refused at open rather than read as "every", because "every" would show Personal in Cotton Project.    #[test]    fn a_manifest_names_personal_one_database_or_none() {        assert_eq!(DatabaseScope::of(None), Ok(DatabaseScope::Every));        assert_eq!(DatabaseScope::of(Some(&json!({"flavour": "sharmila"}))), Ok(DatabaseScope::Every));        assert_eq!(DatabaseScope::of(Some(&json!({"database": "personal"}))), Ok(DatabaseScope::Personal));        assert_eq!(            DatabaseScope::of(Some(&json!({"database": {"id": "db-1", "host": "https://unit.example", "named": "Cotton"}}))),            Ok(DatabaseScope::One { id: "db-1".into(), name: Some("Cotton".into()) })        );        assert_eq!(            DatabaseScope::of(Some(&json!({"database": {"id": "db-1", "host": "https://unit.example"}}))),            Ok(DatabaseScope::One { id: "db-1".into(), name: None })        );        for wrong in [            json!("Personal"),            json!({"named": "Cotton"}),            json!({"id": "", "host": "https://unit.example"}),            json!({"id": "db-1"}),            json!({"id": "db-1", "host": "unit.example"}),            json!({"id": "db-1", "host": "https://unit.example", "and": 1}),            json!(1),        ] {            assert!(DatabaseScope::of(Some(&json!({"database": wrong}))).is_err(), "{wrong}");        }    }    // RULE: an app that names one database holds Personal and never shows it, and holds no database but that one — matched by id, so a database renamed to the same name is still somebody else's; Cotton shows Personal and holds no other.    #[test]    fn a_named_scope_hides_personal_and_admits_its_one_database() {        let project = DatabaseScope::One { id: "db-cotton".into(), name: Some("Cotton".into()) };        assert!(!project.shows(true, "db-personal"));        assert!(project.shows(false, "db-cotton"));        assert!(!project.admits("Cotton"), "a name is not an id");        assert!(!project.admits("db-allotment"));        let cotton = DatabaseScope::Personal;        assert!(cotton.shows(true, "db-personal"));        assert!(!cotton.admits("db-cotton"));        assert!(DatabaseScope::Every.admits("db-allotment") && DatabaseScope::Every.shows_personal());    }    // RULE: the scope kept beside the connection record reads back as the same one database, so a sync path handed only the layout admits exactly what the open did.    #[test]    fn a_kept_scope_reads_back_whole() {        let dir = tempfile::tempdir().unwrap();        let layout = cotton_client::layout::Layout::new(dir.path());        let one = DatabaseScope::One { id: "db-cotton".into(), name: Some("Cotton".into()) };        keep(&layout, &one).unwrap();        assert_eq!(kept(&layout), one);        keep(&layout, &DatabaseScope::Personal).unwrap();        assert_eq!(kept(&layout), DatabaseScope::Personal);        keep(&layout, &DatabaseScope::Every).unwrap();        assert_eq!(kept(&layout), DatabaseScope::Every);    }}