Cotton code
321 lines · 13.0 KB · RustRaw
//! Fixtures a test of any crate builds a file with, now that a replicated//! row IS its receipts (slice 3a): a peer's op with its receipt, an author's//! fact, and [`reconcile`] — the receipt for a row a case wrote with raw SQL.//!//! Compiled only with the `test-fixtures` feature, which only a crate's//! `[dev-dependencies]` turn on.use cotton_store::driver::Driver;use cotton_store::fold::fold_ops;use cotton_store::protocol::types::CottonOp;use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};thread_local! {    /// A file at this build's schema: what a peer's receipt is made against.    static SCHEMA: Driver = {        let db = Driver::open_in_memory().expect("opens");        cotton_store::migrate::migrate_store(&db).expect("migrates");        db    };}/// A peer's op for `change`, with its receipt as `mint` would make it — the/// one door a test builds an op through besides `mint` (`wire::op_of_change`).pub fn peer_op(change: &cotton_store::mint::Change, hlc: &str, author: &str, job: &'static str, op_id: &str) -> CottonOp {    let actor = cotton_store::actor::Actor::device_job(        cotton_store::actor::JobName::named(job).expect("a job name"),    );    SCHEMA        .with(|db| cotton_store::wire::op_of_change(db, change, hlc, author, &actor, op_id.to_string()))        .unwrap_or_else(|error| panic!("{} {} has no receipt ({error})", change.table, change.row_id))}/// A `cotton_authors` fact for a peer author, as `mint::first_author` makes/// one, naming and signed by the author's fixture key. The same shape as/// `cotton-server`'s `test_files::author_fact`.pub fn author_fact(workspace_id: &str, author: &str, first_stamp: &str) -> CottonOp {    let ms: i64 = first_stamp        .get(..13)        .and_then(|digits| digits.parse().ok())        .expect("a stamp starts with its 13-digit millisecond");    let patch = serde_json::json!({        "id": author,        "workspace_id": workspace_id,        // The device key the author signs with (keys slice KS1), derived from        // its name (`cotton_store::fixtures::author_key`).        "device_id": cotton_store::fixtures::author_device(author),        "device_name": Value::Null,        "minted_at": cotton_store::protocol::js::to_iso_string(ms).expect("an instant"),        "reason": "first",        "first_stamp": first_stamp,    });    let fact = peer_op(        &cotton_store::mint::Change::create(            "cotton_authors",            author,            patch.as_object().expect("an object").clone(),        ),        first_stamp,        author,        "mint-author",        &format!("fact-{author}"),    );    cotton_store::fixtures::signed_by_author(workspace_id, fact)}/// The table an `INSERT [OR …] INTO <table>` or `UPDATE <table>` statement/// writes, if it is one.pub fn written_table(sql: &str) -> Option<String> {    // Anywhere in the statement, so a `WITH … INSERT INTO <table>` counts.    let words: Vec<&str> = sql.split_whitespace().collect();    let at = words.iter().position(|word| {        word.eq_ignore_ascii_case("into") || word.eq_ignore_ascii_case("update")    })?;    let table = words.get(at + 1)?;    Some(table.split('(').next().unwrap_or(table).trim_matches('"').to_string())}fn replicated(db: &Driver, table: &str) -> bool {    db.all(&format!("PRAGMA table_info({table})"), &[])        .map(|columns| columns.iter().any(|row| row.text("name") == Some("_born")))        .unwrap_or(false)}/// Bring every replicated table's receipts level with its rows — see/// [`reconcile`].////// Only rows with NO receipt are looked for here — the cheap half, asked/// before every tool call; a raw `UPDATE` is reconciled by the caller that ran it (`reconcile`),/// which knows the table it touched.pub fn reconcile_all(db: &Driver) {    for spec in cotton_store::schema::table_specs::TABLE_SPECS {        reconcile_rows(db, spec.name, false, fold_ops);    }}/// [`reconcile_rows`] of every row of `table`, changes included.pub fn reconcile(db: &Driver, table: &str) {    reconcile_rows(db, table, true, fold_ops);}/// [`reconcile`], with each receipt folded as the serving Mac's answer/// (`fold_pulled`): a row a file held before a rule mint and a device's push/// are now held to — what a case planting such a row, to prove the wall/// downstream of that rule, writes it as.pub fn reconcile_pulled(db: &Driver, table: &str) {    reconcile_rows(db, table, true, cotton_store::fold::fold_pulled);}/// A replicated row IS its receipts: the fold writes the row from them, so a/// row a case wrote past them (a raw `INSERT` or `UPDATE` setting a fixture/// up) would vanish, or lose the edit, at the first write that folds. So each/// such row is given the receipt that says what it now holds — a create for/// a row with none (what the final move mints for a row it carries over), a/// change of the columns that differ for one whose receipts say otherwise —/// by `device:fixture`, folded like any peer's write.type Fold = fn(&Driver, &[CottonOp]) -> cotton_store::Result<cotton_store::fold::FoldResult>;fn reconcile_rows(db: &Driver, table: &str, changes: bool, fold: Fold) {    let Some(spec) = cotton_store::schema::specs::spec_for(table) else {        return;    };    if !replicated(db, table) {        return;    }    let unreceipted = if changes {        String::new()    } else {        format!(            " AS t WHERE NOT EXISTS (SELECT 1 FROM _writes AS w WHERE w.tbl = '{table}' AND w.row_id = t.\"{}\")",            spec.pk        )    };    let rows = db        .all(&format!("SELECT * FROM {table}{unreceipted}"), &[])        .expect("the table reads");    if rows.is_empty() {        return;    }    // What a column holds when no receipt names it: its DDL default.    let defaults: std::collections::BTreeMap<String, SqlValue> = db        .all(&format!("PRAGMA table_info({table})"), &[])        .expect("the table's columns")        .iter()        .filter_map(|column| {            let name = column.text("name")?.to_string();            let value = match column.text("dflt_value") {                Some(literal) => db                    .get(&format!("SELECT {literal} AS v"), &[])                    .ok()                    .flatten()                    .and_then(|row| row.get("v").cloned())                    .unwrap_or(SqlValue::Null),                None => SqlValue::Null,            };            Some((name, value))        })        .collect();    let actor = cotton_store::actor::Actor::device_job(        cotton_store::actor::JobName::named("fixture").expect("a job name"),    );    let mut announced = false;    // The receipts go in as a peer's push does, a batch to a fold — never    // one fold a row: every fold runs the derive pass once, and a fixture of    // fifty thousand raw rows folded one by one spent its forty minutes    // there (run 6347).    let mut batch: Vec<CottonOp> = Vec::new();    for row in rows {        let Some(id) = row.text(spec.pk).map(str::to_string) else {            continue;        };        let stored = cotton_store::receipts::of_row(db, table, &id).expect("the row's receipts");        let t = cotton_store::receipts::retract_stamp(db, table, &id).expect("the retract stamp");        let life = cotton_store::receipts::assemble(table, &stored, t.as_deref());        let written: std::collections::BTreeMap<String, SqlValue> = if life.live {            cotton_store::receipts::row_columns(table, &life)                .expect("the assembled row")                .into_iter()                .collect()        } else {            std::collections::BTreeMap::new()        };        let differ: Vec<&str> = spec            .columns            .iter()            .map(|(column, _)| *column)            .filter(|column| *column != spec.pk)            .filter(|column| {                let held = row.get(column).cloned().unwrap_or(SqlValue::Null);                let says = written                    .get(*column)                    .cloned()                    .or_else(|| defaults.get(*column).cloned())                    .unwrap_or(SqlValue::Null);                held != says            })            .collect();        if life.live && differ.is_empty() {            continue;        }        // A row a case corrupted on purpose (a JSON column that does not        // parse) has no receipt to give: it stays the raw row the case wrote.        let Ok(Some(decoded)) = cotton_store::fold::read_row(db, table, &id) else {            continue;        };        let (change, stamp) = if life.live {            let patch: Map<String, Value> = differ                .iter()                .map(|column| ((*column).to_string(), decoded.get(*column).cloned().unwrap_or(Value::Null)))                .collect();            let newest = life.newest.as_deref().unwrap_or("0");            let ms: u64 = newest.split(':').next().and_then(|ms| ms.parse().ok()).unwrap_or(0);            (                cotton_store::mint::Change::update(table, &id, patch),                format!("{:013}:0000:device:fixture", ms + 1),            )        } else {            let patch: Map<String, Value> = decoded.into_iter().filter(|(_, value)| !value.is_null()).collect();            (                cotton_store::mint::Change::create(table, &id, patch),                "0000000000002:0000:device:fixture".to_string(),            )        };        // `device:fixture` announces itself first: a file holding its own        // author's fact parks a receipt from an author it has not heard of.        if !announced {            announce_fixture_author(db);            announced = true;        }        let op = cotton_store::wire::op_of_change(            db,            &change,            &stamp,            "device:fixture",            &actor,            format!("fixture:{table}:{id}:{stamp}"),        )        ;        // A row no receipt can hold (a case wrote a value the column's codec        // refuses, on purpose) stays the raw row the case wrote.        let Ok(op) = op else {            continue;        };        batch.push(op);        if batch.len() == RECONCILE_BATCH {            fold_batch(db, table, &mut batch, fold);        }    }    fold_batch(db, table, &mut batch, fold);    // A definition the case wrote raw is already in the file when its    // receipt folds, so the fold's before-and-after sees no storage change    // (package_shape::after_definitions): step the whole file, as a launch does.    if table == "cotton_table_definitions" {        cotton_store::schema::package_shape::step_file(db).expect("the defined tables step");    }}/// How many fixture receipts one fold takes.const RECONCILE_BATCH: usize = 1000;/// Fold the receipts `batch` holds, and empty it.fn fold_batch(db: &Driver, table: &str, batch: &mut Vec<CottonOp>, fold: Fold) {    if batch.is_empty() {        return;    }    // A change that is current for nothing is skipped as stale: the    // receipts already said what the row holds.    let result = fold(db, batch).expect("the receipts fold");    assert!(        result.rejected.is_empty(),        "{table}: a fixture receipt was refused: {:?}",        result.rejected    );    batch.clear();}/// Fold `device:fixture`'s author fact into the file once.fn announce_fixture_author(db: &Driver) {    let known = db        .get(            "SELECT 1 AS known FROM cotton_authors WHERE id = 'device:fixture'",            &[],        )        .expect("the authors read")        .is_some();    if known {        return;    }    let workspace_id = db        .get("SELECT workspace_id FROM _meta", &[])        .expect("the meta row")        .and_then(|row| row.text("workspace_id").map(str::to_string))        .expect("the file names its workspace");    let fact = author_fact(&workspace_id, "device:fixture", "0000000000001:0000:device:fixture");    let result = fold_ops(db, std::slice::from_ref(&fact)).expect("the fact folds");    assert!(result.rejected.is_empty(), "the fixture author's fact was refused: {result:?}");}/// Fold `author`'s create of `row_id` at `hlc` (which ends in `author`) into/// `db`, the way a peer's write arrives — a fixture row that says who wrote/// it and when. Panics unless it applied: a seed that did not land makes/// every assertion after it a lie.pub fn fold_create(db: &Driver, table: &str, row_id: &str, patch: Value, hlc: &str, author: &str) {    let actor = cotton_store::actor::Actor::device_job(        cotton_store::actor::JobName::named("fixture").expect("a job name"),    );    let op = cotton_store::wire::op_of_change(        db,        &cotton_store::mint::Change::create(table, row_id, patch.as_object().cloned().unwrap_or_default()),        hlc,        author,        &actor,        format!("fixture:{table}:{row_id}:{hlc}"),    )    .unwrap_or_else(|error| panic!("{table} {row_id} has no receipt ({error})"));    let result = fold_ops(db, std::slice::from_ref(&op)).expect("the create folds");    assert!(        result.applied.contains(&op.op_id),        "{table} {row_id}: the create did not apply: {result:?}"    );}