Cotton code
393 lines · 18.8 KB · RustRaw
//! Receipts, slice 3a part 4: what `mint` refuses before a receipt exists,//! what never goes out as one, a peer's actor checked on arrival, and a held//! receipt kept out of a snapshot fill.use cotton_store::actor::{Actor, DeviceId, JobName};use cotton_store::changes::changes_since;use cotton_store::fixtures::{file_at_version, seed_workspace_row, NOW, OWNER, WORKSPACE};use cotton_store::fold::{arrive, Arrival, FoldResult};use cotton_store::meta::{seed_meta, Meta};use cotton_store::mint::{first_author, mint, Act, AuthorReason, Change, Clock, Held, History, IdSource};use cotton_store::protocol::hlc::next_hlc;use cotton_store::protocol::types::CottonOp;use cotton_store::schema::ddl::SCHEMA_VERSION;use cotton_store::snapshot::strip_for_phone;use cotton_store::wire::{from_bytes, op_of_change};use cotton_store::Driver;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};const T0: i64 = 1_759_480_000_000;struct Ids(u32, &'static str);impl IdSource for Ids {    fn next_op_id(&mut self, _now_ms: i64) -> cotton_store::Result<String> {        self.0 += 1;        Ok(format!("{}-{:04}", self.1, self.0))    }}/// One device's file, with its author minted for the device credential/// `credential`.struct Dev {    db: Driver,    ids: Ids,    author: String,    fact: CottonOp,}fn device(tag: &'static str, credential: &str) -> Dev {    let db = file_at_version(SCHEMA_VERSION);    seed_meta(        &db,        &Meta {            workspace_id: WORKSPACE.to_string(),            owner_id: OWNER.to_string(),            device_id: format!("device:{tag}"),            last_server_seq: 0,            last_hlc: None,        },        SCHEMA_VERSION,    )    .expect("seeds");    seed_workspace_row(&db);    let mut ids = Ids(0, tag);    let author = first_author(&db, credential, Some(tag), AuthorReason::First, &Clock::wall(T0 - 10), &mut ids, Held::Served)        .expect("the author");    Dev {        db,        ids,        author: author.id,        fact: author.fact,    }}fn obj(value: Value) -> Map<String, Value> {    value.as_object().expect("an object").clone()}fn todo(row_id: &str, title: &str) -> Map<String, Value> {    obj(json!({"id": row_id, "workspace_id": WORKSPACE, "title": title, "created_at": NOW, "updated_at": NOW}))}fn job() -> Actor {    Actor::device_job(JobName::named("test").expect("a job name"))}impl Dev {    fn mint(&mut self, at_ms: i64, change: Change) -> cotton_store::Result<Vec<CottonOp>> {        let act = Act {            actor: job(),            verb: "test".to_string(),            history: History::None,            changes: vec![change],        };        mint(&self.db, &act, &Clock::wall(at_ms), &mut self.ids, Held::Served).map(|minted| minted.ops)    }    fn create(&mut self, at_ms: i64, table: &str, row_id: &str, patch: Map<String, Value>) -> Vec<CottonOp> {        self.mint(at_ms, Change::create(table, row_id, patch)).expect("mints")    }    fn change(&mut self, at_ms: i64, table: &str, row_id: &str, patch: Value) -> Vec<CottonOp> {        self.mint(at_ms, Change::update(table, row_id, obj(patch))).expect("mints")    }    fn take(&self, ops: &[CottonOp]) -> FoldResult {        arrive(&self.db, ops, Arrival::Handed).expect("folds")    }    fn count(&self, sql: &str) -> i64 {        self.db.get(sql, &[]).expect("reads").and_then(|row| row.int("n")).unwrap_or(-1)    }    fn receipts(&self) -> i64 {        self.count("SELECT COUNT(*) AS n FROM _writes")    }    fn value(&self, table: &str, row_id: &str, column: &str) -> Option<SqlValue> {        self.db            .get(&format!("SELECT {column} AS v FROM {table} WHERE id = ?"), &[SqlValue::Text(row_id.to_string())])            .expect("reads")            .and_then(|row| row.get("v").cloned())    }    /// A write by this file's author under `actor`, built the way `mint`    /// builds one but without `mint`'s own checks — what a peer could send.    fn forged(&mut self, at_ms: i64, change: &Change, actor: &Actor) -> CottonOp {        let last = self            .db            .get("SELECT last_hlc FROM _meta", &[])            .expect("reads")            .and_then(|row| row.text("last_hlc").map(str::to_string));        let hlc = next_hlc(&self.author, last.as_deref(), at_ms).expect("a stamp");        self.db            .run("UPDATE _meta SET last_hlc = ?", &[SqlValue::Text(hlc.clone())])            .expect("moves the clock");        let id = self.ids.next_op_id(at_ms).expect("an id");        op_of_change(&self.db, change, &hlc, &self.author, actor, id).expect("a receipt")    }}fn fields_of(op: &CottonOp) -> Vec<String> {    cotton_store::canonical::decode(op.receipt.as_bytes())        .expect("a canonical receipt")        .fields        .keys()        .cloned()        .collect()}/// A `cotton_devices` row: `row_id`, holding the device credential `key`.fn device_row(row_id: &str, key: &str) -> Map<String, Value> {    obj(json!({        "id": row_id,        "workspace_id": WORKSPACE,        "device_id": key,        "name": row_id,        "approved_at": NOW,        "approved_by_device": "key-a",        "created_at": NOW,        "updated_at": NOW,    }))}/// RULE: A peer receipt's actor must be valid, and an owner actor's device credential must match the author fact on arrival./// A peer's receipt is checked against its author on arrival: an actor that does not read as one is refused, and an owner actor is refused unless its device row holds the same device credential as the author fact — an author names only its own device's owner. Mint asks its side of this before it stamps; the fold asks it of what arrives.#[test]fn arriving_receipt_whose_actor_its_author_may_not_name_is_refused() {    let mut a = device("a", "key-a");    let b = device("b", "key-b");    b.take(std::slice::from_ref(&a.fact));    let rows = [        a.create(T0, "cotton_devices", "dev-a", device_row("dev-a", "key-a")),        a.create(T0 + 1, "cotton_devices", "dev-b", device_row("dev-b", "key-b")),    ]    .concat();    let landed = b.take(&rows);    assert!(landed.rejected.is_empty(), "the device rows land: {landed:?}");    // a's author is device key-a: the owner at dev-b is not one it may name.    let at_b = Actor::owner(DeviceId::in_file(&a.db, "dev-b").expect("the row"));    let forged = a.forged(T0 + 10, &Change::create("cotton_todos", "t1", todo("t1", "as b's owner")), &at_b);    let result = b.take(std::slice::from_ref(&forged));    assert_eq!(result.rejected.len(), 1, "refused: {result:?}");    assert!(result.rejected[0].reason.contains("owner"), "{}", result.rejected[0].reason);    assert!(b.value("cotton_todos", "t1", "title").is_none(), "nothing applied");    assert_eq!(b.count(&format!("SELECT COUNT(*) AS n FROM _writes WHERE op_id = '{}'", forged.op_id)), 0, "nothing stored");    // The owner at a's own device is.    let at_a = Actor::owner(DeviceId::in_file(&a.db, "dev-a").expect("the row"));    let honest = a.forged(T0 + 20, &Change::create("cotton_todos", "t2", todo("t2", "as a's owner")), &at_a);    let result = b.take(std::slice::from_ref(&honest));    assert_eq!(result.applied, vec![honest.op_id.clone()], "{result:?}");    // An actor that does not read as one, in an otherwise canonical receipt.    let named = a.forged(T0 + 30, &Change::create("cotton_todos", "t3", todo("t3", "nobody")), &job());    let bytes = named.receipt.replace("\"actor\":\"device-job:test\"", "\"actor\":\"nobody\"");    assert_ne!(bytes, named.receipt, "the actor was in the receipt");    let unread = from_bytes(named.op_id.clone(), bytes.as_bytes()).expect("still canonical");    let result = b.take(std::slice::from_ref(&unread));    assert_eq!(result.rejected.len(), 1, "refused: {result:?}");    assert!(result.rejected[0].reason.contains("actor"), "{}", result.rejected[0].reason);    assert!(b.value("cotton_todos", "t3", "title").is_none());}/// RULE: A receipt from a member's device that claims the owner actor is refused on arrival, and an owner's device claiming a member actor is refused too; a member writes as member:<its own device row> and nothing else.#[test]fn a_member_receipt_claiming_owner_actor_is_refused() {    let mut a = device("a", "key-a");    let mut b = device("b", "key-b");    b.take(std::slice::from_ref(&a.fact));    a.take(std::slice::from_ref(&b.fact));    let mut member_row = device_row("dev-a", "key-a");    member_row.insert("person_key".to_string(), json!("PersonKeyOfBob"));    let rows = [        a.create(T0, "cotton_devices", "dev-a", member_row),        a.create(T0 + 1, "cotton_devices", "dev-b", device_row("dev-b", "key-b")),    ]    .concat();    let landed = b.take(&rows);    assert!(landed.rejected.is_empty(), "the device rows land: {landed:?}");    // a's device is a member's: an owner actor from it is refused.    let as_owner = Actor::owner(DeviceId::in_file(&a.db, "dev-a").expect("the row"));    let forged = a.forged(T0 + 10, &Change::create("cotton_todos", "t1", todo("t1", "as the owner")), &as_owner);    let result = b.take(std::slice::from_ref(&forged));    assert_eq!(result.rejected.len(), 1, "refused: {result:?}");    assert!(result.rejected[0].reason.contains("never writes as the owner"), "{}", result.rejected[0].reason);    assert!(b.value("cotton_todos", "t1", "title").is_none(), "nothing applied");    // The member actor at its own device is admitted.    let as_member = Actor::member(&a.db, DeviceId::in_file(&a.db, "dev-a").expect("the row")).expect("a member row");    let honest = a.forged(T0 + 20, &Change::create("cotton_todos", "t2", todo("t2", "as a member")), &as_member);    let result = b.take(std::slice::from_ref(&honest));    assert_eq!(result.applied, vec![honest.op_id.clone()], "{result:?}");    // The OWNER's own device (dev-b names no person) claiming a member actor —    // which `Actor::member` refuses to build, so b forges it as a peer could.    let b_as_member = Actor::Member(DeviceId::in_file(&b.db, "dev-b").expect("the row"));    let forged = b.forged(T0 + 30, &Change::create("cotton_todos", "t3", todo("t3", "b as member")), &b_as_member);    let result = a.take(std::slice::from_ref(&forged));    assert_eq!(result.rejected.len(), 1, "refused: {result:?}");    assert!(result.rejected[0].reason.contains("only a member's device writes as a member"), "{}", result.rejected[0].reason);    assert!(a.value("cotton_todos", "t3", "title").is_none(), "nothing applied");}/// RULE: A default never travels as a write: a column a create leaves to its DEFAULT is not a field of the receipt — not as minted, not as stored, not in a page — and every file fills it from its own schema.#[test]fn default_never_travels_as_a_write() {    let mut a = device("a", "key-a");    let b = device("b", "key-b");    b.take(std::slice::from_ref(&a.fact));    let created = a.create(T0, "cotton_todos", "t1", todo("t1", "one"));    assert_eq!(a.value("cotton_todos", "t1", "status"), Some(SqlValue::Text("open".to_string())));    assert_eq!(a.value("cotton_todos", "t1", "priority"), Some(SqlValue::Integer(0)));    let defaulted = ["status", "priority"];    let page = changes_since(&a.db, &a.author, "", 100).expect("a page");    let travelled = page.ops.iter().find(|op| op.op_id == created[0].op_id).expect("the create travels");    let stored = a        .db        .get("SELECT bytes, fields FROM _writes WHERE op_id = ?", &[SqlValue::Text(created[0].op_id.clone())])        .expect("reads")        .expect("stored");    let stored_bytes = match stored.get("bytes") {        Some(SqlValue::Blob(bytes)) => String::from_utf8(bytes.clone()).expect("UTF-8"),        other => panic!("no bytes: {other:?}"),    };    let stored_fields = stored.text("fields").unwrap_or_default().to_string();    for column in defaulted {        for op in [&created[0], travelled] {            let patch = op.patch.clone().unwrap_or_default();            assert!(!patch.contains_key(column), "{column} travels as a field: {patch:?}");            assert!(!fields_of(op).iter().any(|f| f == column), "{column} is in the receipt: {}", op.receipt);        }        assert!(!stored_bytes.contains(&format!("\"{column}\"")), "{column} is in the stored receipt: {stored_bytes}");        assert!(!stored_fields.contains(&format!("\"{column}\"")), "{column} is a stored field: {stored_fields}");    }    assert_eq!(stored_bytes, created[0].receipt, "stored as minted");    let result = b.take(&page.ops);    assert!(result.rejected.is_empty(), "{result:?}");    assert_eq!(b.value("cotton_todos", "t1", "status"), Some(SqlValue::Text("open".to_string())), "filled by b's own default");    assert_eq!(b.value("cotton_todos", "t1", "priority"), Some(SqlValue::Integer(0)));}/// RULE: A create without a column its table requires (NOT NULL, no default) is refused at mint, naming the column, and leaves nothing behind — no receipt, no row, no stamp.#[test]fn create_without_a_required_column_is_refused_at_mint() {    let mut a = device("a", "key-a");    let before = a.receipts();    let clock_before = a.count("SELECT COUNT(*) AS n FROM _meta WHERE last_hlc IS NOT NULL");    let last_before = a.db.get("SELECT last_hlc FROM _meta", &[]).expect("reads").and_then(|r| r.text("last_hlc").map(str::to_string));    for required in ["title", "created_at", "workspace_id"] {        let mut patch = todo("t1", "one");        patch.remove(required);        let refused = a.mint(T0, Change::create("cotton_todos", "t1", patch));        let Err(reason) = refused else {            panic!("a create without {required} was minted: {refused:?}");        };        assert!(reason.to_string().contains(required), "{reason}");    }    // A required column named as NULL is not named.    let mut patch = todo("t1", "one");    patch.insert("title".to_string(), Value::Null);    assert!(a.mint(T0, Change::create("cotton_todos", "t1", patch)).is_err());    assert_eq!(a.receipts(), before, "no receipt stored");    assert!(a.value("cotton_todos", "t1", "title").is_none(), "no row");    assert_eq!(a.count("SELECT COUNT(*) AS n FROM _meta WHERE last_hlc IS NOT NULL"), clock_before);    let last_after = a.db.get("SELECT last_hlc FROM _meta", &[]).expect("reads").and_then(|r| r.text("last_hlc").map(str::to_string));    assert_eq!(last_after, last_before, "the clock did not move");    // The whole create is minted.    assert!(a.mint(T0, Change::create("cotton_todos", "t1", todo("t1", "one"))).is_ok());}/// RULE: An integer an f64 cannot hold exactly is refused at mint — in a column or in a per-key field — rather than rounded, and nothing of the write is stored.#[test]fn integer_beyond_f64_is_refused_at_mint() {    let mut a = device("a", "key-a");    a.create(T0, "cotton_todos", "t1", todo("t1", "one"));    let before = a.receipts();    let beyond = (1_i64 << 53) + 1;    let mut patch = todo("t2", "two");    patch.insert("priority".to_string(), json!(beyond));    let refused = a.mint(T0 + 10, Change::create("cotton_todos", "t2", patch));    assert!(matches!(refused, Err(cotton_store::StoreError::Refused(_))), "{refused:?}");    assert!(a.value("cotton_todos", "t2", "id").is_none(), "no row");    let refused = a.mint(T0 + 20, Change::update("cotton_todos", "t1", obj(json!({"priority": beyond}))));    assert!(matches!(refused, Err(cotton_store::StoreError::Refused(_))), "{refused:?}");    assert_eq!(a.value("cotton_todos", "t1", "priority"), Some(SqlValue::Integer(0)), "not rounded into the row");    // A per-key field, which has no codec of its own, is refused the same way.    let record = obj(json!({        "id": "r1",        "workspace_id": WORKSPACE,        "table_id": "tbl-1",        "data": {"n": beyond},        "created_at": NOW,        "updated_at": NOW,    }));    let refused = a.mint(T0 + 30, Change::create("cotton_records", "r1", record));    assert!(matches!(refused, Err(cotton_store::StoreError::Refused(_))), "{refused:?}");    assert_eq!(a.receipts(), before, "nothing stored");    // The limit itself is exact, and is minted.    assert!(a.mint(T0 + 40, Change::update("cotton_todos", "t1", obj(json!({"priority": 1_i64 << 53})))).is_ok());}/// RULE: A snapshot fill never carries a held receipt: the copy keeps neither the held receipt nor the value it put in its row — each such row is assembled again from the receipts that travel, and a row whose only create is held is not in the copy.#[test]fn snapshot_fill_excludes_held_receipts() {    let mut a = device("a", "key-a");    let mut b = device("b", "key-b");    a.take(std::slice::from_ref(&b.fact));    b.take(std::slice::from_ref(&a.fact));    let created = a.create(T0, "cotton_todos", "t1", todo("t1", "one"));    b.take(&created);    // a's write is held from the moment it is made; b's, below it, arrives    // after and loses only to the held one, so a keeps it.    let held = a.change(T0 + 20, "cotton_todos", "t1", json!({"title": "held"}));    a.db.run("UPDATE _writes SET held = 1 WHERE op_id = ?", &[SqlValue::Text(held[0].op_id.clone())]).expect("holds");    let travels = b.change(T0 + 10, "cotton_todos", "t1", json!({"title": "travels"}));    assert!(a.take(&travels).rejected.is_empty());    let held_create = a.create(T0 + 30, "cotton_todos", "t2", todo("t2", "held create"));    a.db.run("UPDATE _writes SET held = 1 WHERE op_id = ?", &[SqlValue::Text(held_create[0].op_id.clone())]).expect("holds");    assert_eq!(a.value("cotton_todos", "t1", "title"), Some(SqlValue::Text("held".to_string())), "applies on its writer");    let mut travelling: Vec<String> = [&a.author, &b.author]        .iter()        .flat_map(|author| changes_since(&a.db, author, "", 100).expect("a page").ops)        .filter(|op| op.table == "cotton_todos")        .map(|op| op.op_id)        .collect();    travelling.sort();    // `a`'s file stands in for the copy the snapshot route makes of it: the    // strip runs over the copy, never the live file.    strip_for_phone(&a.db).expect("stripped");    assert_eq!(a.count("SELECT COUNT(*) AS n FROM _writes WHERE held = 1"), 0, "no held receipt in the copy");    for op in [&held[0], &held_create[0]] {        assert_eq!(a.count(&format!("SELECT COUNT(*) AS n FROM _writes WHERE op_id = '{}'", op.op_id)), 0);    }    assert_eq!(        a.value("cotton_todos", "t1", "title"),        Some(SqlValue::Text("travels".to_string())),        "the row is what its travelling receipts say"    );    assert!(a.value("cotton_todos", "t2", "id").is_none(), "a row only a held create made is not in the copy");    let copied: Vec<String> = a        .db        .all("SELECT op_id FROM _writes WHERE tbl = 'cotton_todos' ORDER BY op_id", &[])        .expect("reads")        .iter()        .filter_map(|row| row.text("op_id").map(str::to_string))        .collect();    assert_eq!(copied, travelling, "the copy holds exactly what a page carries");    // And the copy's rows are the rows of a file that saw only what travels.    assert_eq!(a.value("cotton_todos", "t1", "title"), b.value("cotton_todos", "t1", "title"));}