Cotton code
685 lines · 27.3 KB · RustRaw
//! A file at this build's schema version, and a synthetic OWNER file, for//! the tests of every crate that needs something shaped like the owner's own//! database.//!//! **ONE VERSION.** The fresh line has no ladder: a file is the flat DDL//! stamped at `SCHEMA_VERSION`, and [`build_at_version`] builds exactly that.//! A file at an older version is never built here; one from 141 up is carried//! in place by `shape_move`. The builder lives behind the `fixtures` feature the dev-dependencies//! turn on, so no shipping build compiles this module.//!//! Every row is synthetic and every value invented//! ([nothing-real-ever-goes-in-cotton-s-public-tree]).use std::collections::{BTreeMap, BTreeSet};use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value as JsonValue};use crate::driver::{Driver, Row};use crate::fold::fold_ops;use crate::meta::{seed_meta, Meta};use crate::migrate::{current_version, SCHEMA_VERSION};use crate::protocol::hlc::next_hlc;use crate::schema::decl::Codec;use crate::schema::fts::FTS_SOURCES;use crate::schema::table_specs::TABLE_SPECS;pub mod open_bundle;/// The workspace every fixture row belongs to.pub const WORKSPACE: &str = "11111111-1111-4111-8111-111111111111";/// Its owner.pub const OWNER: &str = "owner-1";/// An explicit instant, never the wall clock.pub const NOW: &str = "2026-10-01T09:00:00.000Z";/// The Mac that wrote the synthetic owner file, as an op AUTHOR.pub const OWNER_MAC: &str = "device:01JOWNERMAC0000000000000000";/// The word every synthetic text carries, so a search can be asked for it.pub const SEARCH_WORD: &str = "synthetic";/// An in-memory file at `version` — see [`build_at_version`].pub fn file_at_version(version: u32) -> Driver {    let db = Driver::open_in_memory().expect("an in-memory file opens");    build_at_version(&db, version);    db}/// Build this build's schema into an empty `db`: the flat DDL, stamped at/// `SCHEMA_VERSION`.////// Panics on any other `version`: the fresh line has one version, and a file/// at an older one is carried in place by `shape_move`, never built or climbed.pub fn build_at_version(db: &Driver, version: u32) {    assert!(        version == SCHEMA_VERSION,        "the fresh line has one version ({SCHEMA_VERSION}); a file at {version} is carried in place by shape_move, never built or climbed"    );    crate::create::apply_schema(db).expect("applies the flat DDL");    db.exec(&format!("PRAGMA user_version = {SCHEMA_VERSION}"))        .expect("stamps the version");    assert_eq!(current_version(db).expect("reads"), version);}/// The workspace row every domain row's foreign key points at.pub fn seed_workspace_row(db: &Driver) {    db.run(        "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)",        &[text(WORKSPACE), text("A workspace"), text(OWNER), text(NOW)],    )    .expect("the workspace row");}fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}// ── the synthetic owner file ────────────────────────────────────────────────/// An in-memory synthetic owner file at `version` — see [`fill_owner_file`].pub fn owner_file_at(version: u32) -> Driver {    let db = file_at_version(version);    fill_owner_file(&db, version);    db}/// The same file ON DISK at `path`, opened the way the server opens one (WAL)/// and closed again, so what is left is the one file a stopped Mac holds.pub fn write_owner_file(path: &std::path::Path, version: u32) {    let db = Driver::open(path).expect("opens the file");    build_at_version(&db, version);    fill_owner_file(&db, version);    db.checkpoint_truncate().expect("checkpoints");}/// Fill a file at `version` the way the owner's file is filled: the identity,/// the workspace, and at least one row in EVERY synced table the file has,/// each written through the fold by the owner's Mac — so every row carries/// its clocks exactly as a real write leaves them, and every search index/// holds the text.////// The tables are read off the FILE, not a list: every [`TABLE_SPECS`] entry/// the file holds is filled, so a table cannot be skipped silently, and/// [`synced_tables`] answers the same set for a test to assert on./// The actor the synthetic owner file's rows are written under.pub fn fixture_actor() -> crate::actor::Actor {    crate::actor::Actor::device_job(crate::actor::JobName::named("fixture").expect("a job name"))}pub fn fill_owner_file(db: &Driver, version: u32) {    seed_meta(        db,        &Meta {            workspace_id: WORKSPACE.to_string(),            owner_id: OWNER.to_string(),            device_id: OWNER_MAC.to_string(),            last_server_seq: 0,            last_hlc: None,        },        version,    )    .expect("seeds the identity");    let tables = synced_tables(db);    let order = parents_first(db, &tables);    let mut written: BTreeMap<String, Map<String, JsonValue>> = BTreeMap::new();    let mut clock: i64 = 1_790_000_000_000;    let mut last_hlc: Option<String> = None;    let mut refused: Vec<String> = Vec::new();    for table in &order {        let shape = TableShape::read(db, table);        let mut attempts = Vec::new();        let mut landed = None;        for minimal in [false, true] {            let patch = shape.patch(&written, minimal);            // A key that is a parent's key is missing when that parent was            // refused: say so here, so the report names the parent's refusal.            let Some(row_id) = shape.row_id(&patch) else {                attempts.push(format!("no {} — its parent's row was not written", shape.pk));                continue;            };            clock += 1_000;            let hlc = next_hlc(OWNER_MAC, last_hlc.as_deref(), clock).expect("a stamp");            last_hlc = Some(hlc.clone());            let op = crate::wire::op_of_change(                db,                &crate::mint::Change::create(table, &row_id, patch.clone()),                &hlc,                OWNER_MAC,                &fixture_actor(),                format!("op-owner-{table}-{clock}"),            );            let op = match op {                Ok(op) => op,                Err(error) => {                    attempts.push(error.to_string());                    continue;                }            };            match fold_ops(db, &[op]) {                Ok(result) if result.rejected.is_empty() => {                    landed = Some(patch);                    break;                }                Ok(result) => attempts.push(                    result                        .rejected                        .iter()                        .map(|rejection| rejection.reason.clone())                        .collect::<Vec<_>>()                        .join("; "),                ),                // A CHECK that calls a JSON function on text that is not JSON                // fails the statement rather than the constraint.                Err(error) => attempts.push(error.to_string()),            }        }        match landed {            Some(patch) => {                written.insert(table.clone(), patch);            }            None => refused.push(format!("{table}: {}", attempts.join(" | then minimal: "))),        }    }    assert!(        refused.is_empty(),        "the synthetic owner file could not write a row into {} table(s) — give each an \         entry in `fixtures::OVERRIDES`:\n{}",        refused.len(),        refused.join("\n")    );    // An EDIT of a written row, folded as the owner's Mac's, so the fill    // holds an update receipt beside the creates.    let todo = written        .get("cotton_todos")        .and_then(|patch| patch.get("id"))        .and_then(JsonValue::as_str)        .expect("the todo the fill wrote")        .to_string();    clock += 1_000;    let hlc = next_hlc(OWNER_MAC, last_hlc.as_deref(), clock).expect("a stamp");    let mut edit = Map::new();    edit.insert(        "title".to_string(),        JsonValue::String("A synthetic todo, edited on the Mac".to_string()),    );    let edit_op = crate::wire::op_of_change(        db,        &crate::mint::Change::update("cotton_todos", &todo, edit),        &hlc,        OWNER_MAC,        &fixture_actor(),        format!("op-owner-edit-{clock}"),    )    .expect("the edit's receipt");    let edited = fold_ops(db, &[edit_op]).expect("the edit folds");    assert_eq!(edited.applied.len(), 1, "the edit: {edited:?}");}/// Every [`TABLE_SPECS`] table this file holds — the synced tables of the/// version it is at.pub fn synced_tables(db: &Driver) -> Vec<String> {    let held: BTreeSet<String> = db        .all("SELECT name FROM sqlite_master WHERE type = 'table'", &[])        .expect("reads the tables")        .iter()        .filter_map(|row| row.text("name").map(str::to_string))        .collect();    TABLE_SPECS        .iter()        .map(|spec| spec.name)        .filter(|name| held.contains(*name))        .map(str::to_string)        .collect()}/// The tables in an order where every parent a foreign key names comes/// before its child. A cycle is broken where it is met: the child goes in/// and the column pointing back is left out of its row (see/// [`TableShape::patch`], which only fills a reference whose parent row is/// already written).fn parents_first(db: &Driver, tables: &[String]) -> Vec<String> {    let all: BTreeSet<&str> = tables.iter().map(String::as_str).collect();    let parents: BTreeMap<&str, BTreeSet<String>> = tables        .iter()        .map(|table| {            let named: BTreeSet<String> = foreign_keys(db, table)                .into_iter()                .map(|fk| fk.parent)                .filter(|parent| parent != table && all.contains(parent.as_str()))                .collect();            (table.as_str(), named)        })        .collect();    let mut order: Vec<String> = Vec::new();    let mut placed: BTreeSet<String> = BTreeSet::new();    while order.len() < tables.len() {        let ready = tables            .iter()            .filter(|table| !placed.contains(*table))            .find(|table| parents[table.as_str()].iter().all(|p| placed.contains(p)))            .or_else(|| tables.iter().find(|table| !placed.contains(*table)))            .expect("a table is left")            .clone();        placed.insert(ready.clone());        order.push(ready);    }    order}struct ForeignKey {    column: String,    parent: String,    /// The parent column, or `None` for its primary key.    to: Option<String>,}fn foreign_keys(db: &Driver, table: &str) -> Vec<ForeignKey> {    db.all(        "SELECT \"from\" AS col, \"table\" AS parent, \"to\" AS target FROM pragma_foreign_key_list(?)",        &[text(table)],    )    .expect("reads the foreign keys")    .iter()    .filter_map(|row| {        Some(ForeignKey {            column: row.text("col")?.to_string(),            parent: row.text("parent")?.to_string(),            to: row.text("target").map(str::to_string),        })    })    .collect()}struct Column {    name: String,    codec: Codec,    not_null: bool,    has_default: bool,}struct TableShape {    table: String,    pk: &'static str,    columns: Vec<Column>,    foreign_keys: Vec<ForeignKey>,    sql: String,}impl TableShape {    fn read(db: &Driver, table: &str) -> TableShape {        let spec = TABLE_SPECS            .iter()            .find(|spec| spec.name == table)            .expect("a synced table");        let columns = db            .all(                "SELECT name, \"notnull\" AS nn, dflt_value AS d FROM pragma_table_info(?) ORDER BY cid",                &[text(table)],            )            .expect("reads the columns")            .iter()            .filter_map(|row| {                let name = row.text("name")?.to_string();                let codec = spec                    .columns                    .iter()                    .find(|(column, _)| *column == name)                    .map(|(_, codec)| *codec)?;                Some(Column {                    name,                    codec,                    not_null: row.int("nn") == Some(1),                    has_default: row.get("d").is_some_and(|value| *value != SqlValue::Null),                })            })            .collect();        let sql = db            .get(                "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",                &[text(table)],            )            .expect("reads")            .and_then(|row| row.text("sql").map(str::to_string))            .unwrap_or_default();        TableShape {            table: table.to_string(),            pk: spec.pk,            columns,            foreign_keys: foreign_keys(db, table),            sql,        }    }    fn row_id(&self, patch: &Map<String, JsonValue>) -> Option<String> {        match patch.get(self.pk) {            Some(JsonValue::String(id)) => Some(id.clone()),            _ => None,        }    }    /// One row: every column (`minimal` = only what the table cannot do    /// without), each value the override, the parent's key, the first word a    /// `CHECK (… IN (…))` allows, or a value of the column's codec.    fn patch(        &self,        written: &BTreeMap<String, Map<String, JsonValue>>,        minimal: bool,    ) -> Map<String, JsonValue> {        let mut patch = Map::new();        for column in &self.columns {            let name = column.name.as_str();            let is_pk = name == self.pk;            if let Some((_, _, value)) = OVERRIDES                .iter()                .find(|(table, col, _)| *table == self.table && *col == name)            {                let value = value();                if !value.is_null() {                    patch.insert(name.to_string(), value);                }                continue;            }            if let Some(fk) = self.foreign_keys.iter().find(|fk| fk.column == name) {                let parent_row = written.get(&fk.parent);                let parent_value = parent_row.and_then(|row| {                    let key = fk.to.clone().unwrap_or_else(|| {                        TABLE_SPECS                            .iter()                            .find(|spec| spec.name == fk.parent)                            .map_or("id", |spec| spec.pk)                            .to_string()                    });                    row.get(&key).cloned()                });                if let Some(value) = parent_value {                    patch.insert(name.to_string(), value);                }                // A parent this file does not have, or one not written yet (a                // cycle): the reference stays out, and NOT NULL says so.                continue;            }            if self.table == "cotton_money_accounts" && name == "kind" {                patch.insert(                    name.to_string(),                    first_allowed(&self.sql, name).unwrap_or_else(|| json!("bank")),                );                continue;            }            let required = column.not_null && !column.has_default;            // A searched column is filled even in the smallest row, so every            // search index holds text.            let searched = FTS_SOURCES                .iter()                .any(|source| source.source == self.table && source.columns.contains(&name));            if minimal && !required && !is_pk && !searched {                continue;            }            let value = if is_pk {                json!(format!("{}-{SEARCH_WORD}-1", short(&self.table)))            } else if let Some(allowed) = first_allowed(&self.sql, name) {                // `CHECK (flag IN (0, 1))` on a boolean: the codec takes a bool.                match (column.codec, allowed.as_i64()) {                    (Codec::Bool, Some(number)) => json!(number != 0),                    _ => allowed,                }            } else {                self.value_of(column)            };            patch.insert(name.to_string(), value);        }        patch    }    fn value_of(&self, column: &Column) -> JsonValue {        let name = column.name.as_str();        // Synthetic media uses the file's own prefix, just like a real row;        // the fixture must pass the same holding-key guard as ordinary writes.        if crate::media_keys::MEDIA_KEY_HOLDERS.iter().any(|(table, key, shape)| {            *table == self.table && *key == name && *shape == crate::media_keys::KeyShape::Text        }) {            return json!(format!("{WORKSPACE}/synthetic/{}/{name}", short(&self.table)));        }        // A column the DDL reads as JSON holds JSON whatever its codec says.        if column.codec == Codec::Text {            let is_array = [                format!("json_type({name}) = 'array'"),                format!("json_array_length({name})"),            ]            .iter()            .any(|probe| self.sql.contains(probe.as_str()));            let is_json = is_array                || [format!("json_type({name})"), format!("json_valid({name})")]                    .iter()                    .any(|probe| self.sql.contains(probe.as_str()));            if is_json {                return json!(if is_array { "[]" } else { "{}" });            }        }        match column.codec {            Codec::Timestamp => json!(NOW),            Codec::Int => json!(1),            Codec::MoneyMinor => json!(100),            Codec::Real => json!(0.5),            Codec::Bool => json!(true),            Codec::DecimalText => json!("0.5"),            Codec::Json => {                let array = [                    format!("json_type({name}) = 'array'"),                    format!("json_array_length({name})"),                ];                if array.iter().any(|probe| self.sql.contains(probe.as_str())) {                    json!([])                } else {                    json!({})                }            }            Codec::Text => {                if name.ends_with("_at") || name.ends_with("_until") || name.ends_with("_on") {                    json!(NOW)                } else if name.contains("sha256") || name.ends_with("_hash") || name.ends_with("digest") {                    json!(HEX64)                } else if name.contains("email") {                    json!("someone@example.com")                } else if name == "slug" || name == "handle" {                    // Lowercase letters, digits and hyphens.                    json!(format!("{SEARCH_WORD}-{}", short(&self.table).replace('_', "-")))                } else if name == "phone" {                    json!(PHONE)                } else if name.contains("currency") {                    // ISO 4217's code for testing.                    json!("XTS")                } else {                    json!(format!("Synthetic {} {name}", short(&self.table)))                }            }        }    }}const HEX64: &str = "0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0";const OTHER_HEX64: &str = "a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1";/// Digits only, in the length a phone CHECK allows; no real number.const PHONE: &str = "15550100000";fn short(table: &str) -> &str {    table.strip_prefix("cotton_").unwrap_or(table)}/// The first literal of `<column> IN (…)` in the table's DDL, where there is/// one — the value a CHECK listing the allowed words accepts.fn first_allowed(sql: &str, column: &str) -> Option<JsonValue> {    let needle = format!("{column} IN (");    let mut from = 0;    while let Some(found) = sql[from..].find(&needle) {        let at = from + found;        from = at + needle.len();        let before = sql[..at].chars().next_back();        if before.is_some_and(|c| c.is_ascii_alphanumeric() || c == '_') {            continue;        }        let list = &sql[from..];        let first = list.split([',', ')']).next()?.trim();        if let Some(word) = first.strip_prefix('\'').and_then(|w| w.strip_suffix('\'')) {            return Some(json!(word));        }        if let Ok(number) = first.parse::<i64>() {            return Some(json!(number));        }    }    None}/// A value, made when the row is.type Make = fn() -> JsonValue;/// The values a table needs that no rule above can derive — a CHECK across/// columns, a shape inside a JSON column, a format an id must have. `null`/// leaves the column out of the row./// The record the synthetic audience row names: an id, not a row — an audience/// may name a record this file does not hold yet.const AUDIENCE_RECORD: &str = "cccccccc-0000-4000-8000-000000000001";const OVERRIDES: &[(&str, &str, Make)] = &[    // An audience's id is derived from the record it names, and a released    // one (`everyone`) holds nothing back from the peers this file exchanges with.    ("cotton_audiences", "id", || json!(crate::protocol::derived_id::audience_id("cotton_todos", AUDIENCE_RECORD))),    ("cotton_audiences", "record_table", || json!("cotton_todos")),    ("cotton_audiences", "record_id", || json!(AUDIENCE_RECORD)),    ("cotton_audiences", "audience", || json!(crate::audience::EVERYONE)),    ("cotton_workspaces", "id", || json!(WORKSPACE)),    ("cotton_workspaces", "owner_user_id", || json!(OWNER)),    ("cotton_blocked_senders", "address", || json!("someone@example.com")),    ("cotton_email_senders", "address", || json!("someone@example.com")),    ("cotton_usage", "kind", || json!("view_opened")),    // A filing proposal names its candidates and arrivals as JSON arrays and    // its revisions and payload as JSON objects (rise 138).    ("cotton_filing_proposals", "kind", || json!("move")),    ("cotton_filing_proposals", "candidates", || json!([])),    ("cotton_filing_proposals", "arrivals", || json!([])),    ("cotton_filing_proposals", "revisions", || json!({})),    ("cotton_filing_proposals", "payload", || json!({})),    // A document's state is stamped with its time even where the column takes    // null (rise 142: the object files documents no engine there reads), so    // the synthetic owner file seeds the historical shapes that required it.    ("cotton_documents", "status_changed_at", || json!(NOW)),    ("cotton_email_senders", "kind", || json!("service")),    ("cotton_email_senders", "written_to", || json!(false)),    ("cotton_email_threads", "sender_address", || JsonValue::Null),    ("cotton_email_threads", "sender_kind", || JsonValue::Null),    ("cotton_email_threads", "record_kind", || JsonValue::Null),    ("cotton_email_threads", "amount_minor", || JsonValue::Null),    ("cotton_email_threads", "currency", || JsonValue::Null),    ("cotton_email_threads", "record_on", || JsonValue::Null),    ("cotton_collections", "kind", || json!("calendar")),    // `author_kind` is 'user', so the user id is set and the agent's label is not.    ("cotton_comments", "author_label", || JsonValue::Null),    ("cotton_comments", "author_user_id", || json!(OWNER)),    ("cotton_media_duplicates", "keep_id", || json!(format!("photo:{HEX64}"))),    ("cotton_media_duplicates", "copy_id", || json!(format!("photo:{OTHER_HEX64}"))),    ("cotton_media_album_items", "record_id", || json!(format!("photo:{HEX64}"))),    ("cotton_media_faces", "record_id", || json!(format!("photo:{HEX64}"))),    ("cotton_media_sightings", "record_id", || json!(format!("photo:{HEX64}"))),    // `status` is 'active' and `origin_kind` 'user': nothing archived,    // superseded or labelled as an agent's.    ("cotton_memories", "archived_at", || JsonValue::Null),    ("cotton_memories", "superseded_by", || JsonValue::Null),    ("cotton_memories", "origin_label", || JsonValue::Null),    ("cotton_moods", "local_day", || json!("2026-10-01")),    ("cotton_msg_contact_handles", "value", || json!(PHONE)),    ("cotton_msg_reactions", "emoji", || json!("ok")),    ("cotton_photos", "id", || json!(format!("photo:{HEX64}"))),    ("cotton_photos", "phash", || json!("0123456789abcdef")),    ("cotton_videos", "id", || json!(format!("video:{HEX64}"))),    ("cotton_videos", "phash", || json!("0123456789abcdef")),    // `format` is 'raw', which names no environment variable.    ("cotton_secret_placements", "env_name", || JsonValue::Null),    ("cotton_secret_placements", "path", || json!("~/synthetic/placed.txt")),    ("cotton_screenplay_documents", "kind", || json!("draft")),    ("cotton_repo_vars", "name", || json!("SYNTHETIC_VAR")),    ("cotton_secrets", "service", || json!("synthetic.service")),];// ── what a test compares ────────────────────────────────────────────────────/// Every row of every ordinary table, in the columns `columns` names per/// table, as text, sorted — so two dumps are equal exactly when every value/// of every row in those columns is.pub fn dump(    db: &Driver,    columns: &BTreeMap<String, Vec<String>>,) -> BTreeMap<String, Vec<Vec<String>>> {    columns        .iter()        .map(|(table, names)| {            let list = names                .iter()                .map(|name| format!("\"{name}\""))                .collect::<Vec<_>>()                .join(", ");            let mut rows: Vec<Vec<String>> = db                .all(&format!("SELECT {list} FROM \"{table}\""), &[])                .unwrap_or_else(|error| panic!("dumps {table}: {error}"))                .iter()                .map(|row: &Row| {                    row.columns()                        .iter()                        .map(|(_, value)| format!("{value:?}"))                        .collect()                })                .collect();            rows.sort();            (table.clone(), rows)        })        .collect()}/// How many ops the file has parked as refused.pub fn parked(db: &Driver) -> i64 {    db.get("SELECT count(*) AS c FROM _parked", &[])        .expect("reads")        .and_then(|row| row.int("c"))        .unwrap_or(-1)}/// The device key a fixture AUTHOR signs with (keys slice KS1): derived from/// the author's name, so a fixture's author fact names it and every op the/// fixture hands over under that author is signed by it, with no key passed/// around. Two authors, two keys; the same author, the same key in every crate.pub fn author_key(author: &str) -> crate::signed::KeySigner {    use sha2::{Digest, Sha256};    let seed: [u8; 32] = Sha256::digest(format!("cotton-fixture-author/{author}").as_bytes()).into();    crate::signed::KeySigner(ed25519_dalek::SigningKey::from_bytes(&seed))}/// [`author_key`]'s device id: what a fixture author's fact names.pub fn author_device(author: &str) -> String {    use crate::signed::ReceiptSigner as _;    author_key(author).device_key()}/// An op a fixture signs.pub type SignedOp = crate::protocol::types::CottonOp;/// `op`, signed in `database_id` by its author's fixture key ([`author_key`]).pub fn signed_by_author(database_id: &str, op: SignedOp) -> SignedOp {    author_key(&op.device_id.clone()).sign_op(database_id, op)}#[cfg(test)]mod tests {    use super::*;    #[test]    fn latest_owner_fixture_uses_the_personal_kit_bank_kind() {        let db = owner_file_at(SCHEMA_VERSION);        let kind = db            .get("SELECT kind FROM cotton_money_accounts LIMIT 1", &[])            .expect("reads the synthetic account")            .and_then(|row| row.text("kind").map(str::to_owned))            .expect("the synthetic account kind");        assert_eq!(kind, "bank");    }}