Cotton code
379 lines · 14.5 KB · RustRaw
//! `_meta` and the rest of the system tables — what makes a plain SQLite file//! a Cotton database.//!//! Named with a leading underscore so they sort away from the `cotton_*`//! domain and so an export's reader can tell at a glance which tables are//! theirs and which are ours. They are protocol machinery, never user data://! the domain tables hold the life, these hold what is needed to sync it.//!//! The DDL is NOT ported: `schema::ddl::SCHEMA_DDL` already carries every//! statement a fresh file is built from, system tables included, and a second//! copy here would be a second answer to "what shape is this table" — the one//! thing the generator exists to prevent. This module names WHICH tables are//! the protocol's and takes their text from there.use rusqlite::types::Value;use crate::driver::Driver;use crate::error::{Result, StoreError};use crate::schema::ddl::SCHEMA_DDL;/// The tables the protocol owns, by name.////// A NAMED LIST, never a catch-all on the underscore prefix: a table that/// appears in the file without appearing here is something nobody declared,/// and the guard below says so rather than quietly adopting it.////// - `_meta` — one row, ever. The `only_one` CHECK on a fixed primary key is///   what makes "one file, one life" a property of the file./// - `_outbox` — the client's un-handed-over tail, drained FIFO by op id./// - `_tombstones` — deletes have to outlive the row, or an older upsert///   arriving after a delete would resurrect what the user removed./// - `_media` — the media ledger (v7). DEVICE-LOCAL, never synced: which///   device holds which bytes is a fact about a phone, not about the life./// - `_cursors` — how far this file has seen each AUTHOR's writes (v8). One row///   per WRITER, not per peer./// - `_shadow_writes` — the authors a row's `_hlc` does not name (v8): every///   author on a row EXCEPT the one holding the maximum stamp, so a second///   author's write is findable in its own stream instead of being invisible.////// - `_writes`, `_gone`, `_media_key_names` — the sync rebuild's per-write///   log, erased rows and media-key index (slice 9a); DEVICE-LOCAL, never///   synced./// - `_computed` — what this device worked out for every computed column///   (`crate::derived`); never synced./// - `_media_unlinks` — this device's queue of dead media keys to unlink///   (slice 7, `crate::media_erasure`); DEVICE-LOCAL, never synced./// - `_on_demand` — the rows this device holds only because somebody opened///   them (`crate::keep`), each with when; DEVICE-LOCAL, never synced./// - `_fts_fill` — the search indexes this file is still filling in the///   background, each with its floor and progress (`crate::fts_fill`, v122);///   DEVICE-LOCAL, never synced./// - `_fts_purge` — the search indexes an erase left words in, due a merge///   in the background (`crate::fts_purge`, v154); DEVICE-LOCAL, never synced./// - `_keep_fetch` — what this device's copy of each narrowable table is///   complete for, and where a widening fetch got to (`crate::keep`);///   DEVICE-LOCAL, never synced./// - `_parked` — a write this file could not fold yet, in either direction,///   kept whole with its class (`crate::rejected`) and never dropped.////// `_ops` — the server's operation log — was the eighth until version 11 took/// it off the file. The tables have been the log since version 8: a row carries/// its own stamp and an author index answers for its writer/// ([`crate::changes`]), so nothing wrote the log and nothing read it.pub const SYSTEM_TABLE_NAMES: &[&str] = &[    "_ai_batches",    "_meta",    "_outbox",    "_tombstones",    "_media",    "_cursors",    "_writes",    "_writes_owners",    "_field_sets",    "_trim",    "_parked",    "_gone",    "_media_key_names",    "_media_unlinks",    "_computed",    "_on_demand",    "_keep_fetch",    "_fts_fill",    "_fts_purge",    "_mail_cuts",    "_mail_landed",    "_mail_own",];/// The statements that build the system tables and their indexes, taken from/// the generated schema in issue order.////// Used to stand up JUST the protocol tables — what `meta`, the fold, the/// outbox and the media ledger need in a test. A real file is created from the/// whole of `SCHEMA_DDL` (`create.rs`), never from this.pub fn system_tables_ddl() -> Vec<&'static str> {    SCHEMA_DDL        .iter()        .copied()        .filter(|statement| {            target_table(statement).is_some_and(|table| SYSTEM_TABLE_NAMES.contains(&table))        })        .collect()}/// The table a `CREATE TABLE`/`CREATE INDEX`/`CREATE TRIGGER` statement is/// about. `None` for anything else — a shape this module does not claim to/// parse is a shape it leaves alone.fn target_table(statement: &str) -> Option<&str> {    let mut words = statement.split_whitespace();    match (words.next()?, words.next()?) {        // `CREATE TABLE [IF NOT EXISTS] <name> (`. The `IF NOT EXISTS` is        // skipped rather than read as the name: a rung whose table is also in        // `SCHEMA_DDL` spells it that way (version 2's, version 8's two), and        // a parse that answered `"IF"` would drop those statements out of        // `system_tables_ddl` silently — a test standing up the protocol        // tables would get a file missing one, with nothing to say so.        ("CREATE", "TABLE") => {            let name = words.next()?;            if name.eq_ignore_ascii_case("IF") {                // `NOT`, `EXISTS`, then the name.                words.next()?;                words.next()?;                words.next().map(strip_open_paren)            } else {                Some(strip_open_paren(name))            }        }        // `CREATE [UNIQUE] INDEX <name> ON <table> (`  /  `CREATE TRIGGER <name> … ON <table>`        ("CREATE", "UNIQUE") | ("CREATE", "INDEX") | ("CREATE", "TRIGGER") => {            let mut rest = statement.split_whitespace();            rest.next();            loop {                let word = rest.next()?;                if word.eq_ignore_ascii_case("ON") {                    return rest.next().map(strip_open_paren);                }            }        }        _ => None,    }}fn strip_open_paren(word: &str) -> &str {    word.split('(').next().unwrap_or(word).trim_matches('"')}/// The workspace/owner/device identity of a file.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Meta {    pub workspace_id: String,    pub owner_id: String,    pub device_id: String,    pub last_server_seq: i64,    pub last_hlc: Option<String>,}/// Stand up just the protocol tables on an empty file.////// The statements are the generated schema's own, so a table created here is/// the table a real file has. Not how a file is CREATED — that is the whole of/// `SCHEMA_DDL` — but what a test of the fold, the outbox or the ledger needs/// without the other hundred tables.pub fn create_system_tables(db: &Driver) -> Result<()> {    for statement in system_tables_ddl() {        db.exec(statement)?;    }    Ok(())}/// Seed the identity of a brand-new file.////// Separate from creating one because a file being ADOPTED (spec R3) already/// HAS its identity — taking it into the Rust era must not overwrite who it/// belongs to. Refuses a file that is already seeded: one file is one life.////// `device_id` is the CALLER's — this crate mints no ids of its own (spec R7),/// so the `device:<ulid>` default TypeScript applies is the caller's job.pub fn seed_meta(db: &Driver, meta: &Meta, schema_version: u32) -> Result<()> {    if let Some(existing) = db.get("SELECT workspace_id FROM _meta", &[])? {        let workspace = existing            .text("workspace_id")            .unwrap_or_default()            .to_string();        return Err(StoreError::refused(format!(            "file already belongs to workspace {workspace} — one file is one life"        )));    }    db.run(        "INSERT INTO _meta (only_one, workspace_id, owner_id, schema_version, last_server_seq, device_id, last_hlc)\n     VALUES (1, ?, ?, ?, ?, ?, ?)",        &[            Value::Text(meta.workspace_id.clone()),            Value::Text(meta.owner_id.clone()),            Value::Integer(i64::from(schema_version)),            Value::Integer(meta.last_server_seq),            Value::Text(meta.device_id.clone()),            meta.last_hlc                .clone()                .map_or(Value::Null, Value::Text),        ],    )?;    Ok(())}/// The file's identity, or `None` when it has never been seeded.pub fn read_meta(db: &Driver) -> Result<Option<Meta>> {    let Some(row) = db.get(        "SELECT workspace_id, owner_id, device_id, last_server_seq, last_hlc FROM _meta",        &[],    )?    else {        return Ok(None);    };    Ok(Some(Meta {        workspace_id: row.text("workspace_id").unwrap_or_default().to_string(),        owner_id: row.text("owner_id").unwrap_or_default().to_string(),        device_id: row.text("device_id").unwrap_or_default().to_string(),        last_server_seq: row.int("last_server_seq").unwrap_or(0),        last_hlc: row.text("last_hlc").map(str::to_string),    }))}/// `PRAGMA user_version` — the version the FILE is stamped at. 0 on a file no/// migration has ever touched.pub fn file_schema_version(db: &Driver) -> Result<u32> {    let row = db.get("PRAGMA user_version", &[])?;    Ok(row        .and_then(|row| row.int("user_version"))        .unwrap_or(0)        .max(0) as u32)}#[cfg(test)]mod tests {    use super::*;    fn opened() -> Driver {        let db = Driver::open_in_memory().expect("in-memory file opens");        create_system_tables(&db).expect("system tables create");        db    }    fn meta() -> Meta {        Meta {            workspace_id: "11111111-1111-4111-8111-111111111111".to_string(),            owner_id: "owner-1".to_string(),            device_id: "device:01J0000000000000000000000A".to_string(),            last_server_seq: 0,            last_hlc: None,        }    }    #[test]    fn every_declared_system_table_is_in_the_generated_schema() {        // The list above is a DECLARATION, and a declaration that names a        // table the file no longer has would fail silently — the filter would        // simply return fewer statements and a test would stand up a database        // missing a table nobody noticed.        let built: Vec<&str> = system_tables_ddl();        for name in SYSTEM_TABLE_NAMES {            assert!(                built.iter().any(|statement| {                    statement.starts_with(&format!("CREATE TABLE {name} "))                        || statement.starts_with(&format!("CREATE TABLE IF NOT EXISTS {name} "))                }),                "{name} is declared a system table but the generated schema does not create it"            );        }    }    #[test]    fn no_underscore_table_in_the_file_is_left_undeclared() {        // The other direction: a new protocol table added in TypeScript has to        // be named here, or `create_system_tables` quietly stops creating it        // and every test built on this helper drifts from a real file.        for statement in SCHEMA_DDL {            let Some(table) = target_table(statement) else {                continue;            };            if !table.starts_with('_') {                continue;            }            // A table version 1 builds and a LATER rung drops is not in the            // file this list describes — `_ops` since version 11. The            // exemption is derived from the retirement declared on the step,            // never a second hand-kept list.            if crate::migrate::is_retired_table(table) {                continue;            }            assert!(                SYSTEM_TABLE_NAMES.contains(&table),                "{table} is in the file but not in SYSTEM_TABLE_NAMES"            );        }    }    #[test]    fn the_target_table_is_read_off_the_statement_shape() {        assert_eq!(            target_table("CREATE TABLE _meta (\n  x TEXT\n)"),            Some("_meta")        );        assert_eq!(            target_table("CREATE INDEX idx_outbox_order ON _outbox (op_id)"),            Some("_outbox")        );        assert_eq!(            target_table("CREATE UNIQUE INDEX uq_x ON cotton_todos (id)"),            Some("cotton_todos")        );        assert_eq!(            target_table("CREATE VIRTUAL TABLE fts_notes USING fts5(title)"),            None        );    }    #[test]    fn seeds_and_reads_back() {        let db = opened();        seed_meta(&db, &meta(), 45).expect("seeds");        let read = read_meta(&db).expect("reads").expect("is seeded");        assert_eq!(read, meta());    }    #[test]    fn an_unseeded_file_reads_none() {        let db = opened();        assert_eq!(read_meta(&db).expect("reads"), None);    }    #[test]    fn refuses_a_second_identity() {        let db = opened();        seed_meta(&db, &meta(), 45).expect("seeds");        let mut other = meta();        other.workspace_id = "22222222-2222-4222-8222-222222222222".to_string();        let error = seed_meta(&db, &other, 45).expect_err("a second identity is refused");        assert!(            error.to_string().contains("one file is one life"),            "got {error}"        );        // And the first identity survives the refusal.        assert_eq!(read_meta(&db).expect("reads").expect("seeded"), meta());    }    #[test]    fn only_one_row_ever() {        let db = opened();        seed_meta(&db, &meta(), 45).expect("seeds");        let error = db            .run(                "INSERT INTO _meta (only_one, workspace_id, owner_id, schema_version, last_server_seq, device_id) VALUES (2, 'w', 'o', 45, 0, 'd')",                &[],            )            .expect_err("the only_one CHECK refuses a second row");        assert!(            error.to_string().to_lowercase().contains("check"),            "got {error}"        );    }    #[test]    fn the_file_version_starts_at_zero_and_follows_the_pragma() {        let db = opened();        assert_eq!(file_schema_version(&db).expect("reads"), 0);        db.exec("PRAGMA user_version = 7").expect("stamps");        assert_eq!(file_schema_version(&db).expect("reads"), 7);    }    #[test]    fn last_hlc_round_trips_as_a_nullable() {        let db = opened();        let mut with_hlc = meta();        with_hlc.last_hlc = Some("1700000000000:0000:device:a".to_string());        with_hlc.last_server_seq = 17;        seed_meta(&db, &with_hlc, 45).expect("seeds");        assert_eq!(read_meta(&db).expect("reads").expect("seeded"), with_hlc);    }}