Cotton code
270 lines · 11.6 KB · RustRaw
//! Slice 6b: history is written by `mint`, in the act that made the change —//! one `cotton_changes` row per act per record, holding the moved fields only —//! and travels with the act, so every device holds the same history. Folding a//! peer's write writes none.use std::sync::Arc;use cotton_store::actor::{Actor, JobName};use cotton_store::fact_hooks::HISTORY_TABLE;use cotton_store::fixtures::{file_at_version, seed_workspace_row, NOW, OWNER, WORKSPACE};use cotton_store::fold::{arrive, Arrival};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::types::CottonOp;use cotton_store::schema::ddl::SCHEMA_VERSION;use cotton_store::signed::{KeySigner, ReceiptSigner};use cotton_store::Driver;use serde_json::{json, Map, Value};const T0: i64 = 1_759_480_000_000;const TODOS: &str = "cotton_todos";const DOCUMENTS: &str = "cotton_documents";const TODO: &str = "00000000-0000-4000-8000-00000000b001";const DOC: &str = "00000000-0000-4000-8000-00000000d001";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!("{}-{:05}", self.1, self.0))    }}struct Dev {    db: Driver,    ids: Ids,    fact: CottonOp,    actor: Actor,}fn device(tag: &'static str, seed: u8) -> Dev {    let signer = Arc::new(KeySigner::of_seed(seed));    let key = signer.device_key();    let db = file_at_version(SCHEMA_VERSION).signed_by(signer);    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, &key, Some(tag), AuthorReason::First, &Clock::wall(T0 - 10), &mut ids, Held::Served)        .expect("the author");    Dev { db, ids, fact: author.fact, actor: Actor::device_job(JobName::named("test").expect("a job name")) }}fn pair() -> (Dev, Dev) {    let mac = device("mac", 1);    let phone = device("phone", 2);    mac.take(std::slice::from_ref(&phone.fact));    phone.take(std::slice::from_ref(&mac.fact));    (mac, phone)}fn obj(value: Value) -> Map<String, Value> {    value.as_object().expect("an object").clone()}fn new_todo(title: &str) -> Change {    Change::create(        TODOS,        TODO,        obj(json!({"id": TODO, "workspace_id": WORKSPACE, "title": title, "created_at": NOW, "updated_at": NOW})),    )}impl Dev {    fn act_as(&mut self, at_ms: i64, verb: &str, history: History, changes: Vec<Change>) -> Vec<CottonOp> {        let act = Act { actor: self.actor.clone(), verb: verb.to_string(), history, changes };        mint(&self.db, &act, &Clock::wall(at_ms), &mut self.ids, Held::Served).expect("mints").ops    }    fn act(&mut self, at_ms: i64, verb: &str, changes: Vec<Change>) -> Vec<CottonOp> {        self.act_as(at_ms, verb, History::Kept, changes)    }    fn take(&self, ops: &[CottonOp]) {        let result = arrive(&self.db, ops, Arrival::Handed).expect("folds");        assert!(result.rejected.is_empty(), "nothing is rejected: {:?}", result.rejected);    }    /// Every history row, every column that travels, oldest first.    fn history(&self) -> Vec<Value> {        self.db            .all(                &format!(                    "SELECT id, table_id, kind, record_id, verb, actor, write_hlc, byline, before, after, created_at \                     FROM {HISTORY_TABLE} ORDER BY write_hlc, id"                ),                &[],            )            .expect("reads")            .iter()            .map(|row| {                let text = |c: &str| row.text(c).map_or(Value::Null, |t| Value::String(t.to_string()));                let json = |c: &str| row.text(c).and_then(|t| serde_json::from_str(t).ok()).unwrap_or(Value::Null);                json!({                    "id": text("id"), "table_id": text("table_id"), "kind": text("kind"),                    "record_id": text("record_id"), "verb": text("verb"), "actor": text("actor"),                    "write_hlc": text("write_hlc"), "byline": text("byline"),                    "before": json("before"), "after": json("after"), "created_at": text("created_at"),                })            })            .collect()    }}/// The ops of an act without its history receipts — what a peer's write looks/// like to a fold that is asked to write history itself.fn without_history(ops: &[CottonOp]) -> Vec<CottonOp> {    ops.iter().filter(|op| op.table != HISTORY_TABLE).cloned().collect()}/// RULE: History is written by mint in the act and travels with it, so every device holds the same history rows after an exchange.#[test]fn history_is_identical_on_every_device_after_exchange() {    let (mut mac, mut phone) = pair();    let made = mac.act(T0, "create_todo", vec![new_todo("Buy bread")]);    phone.take(&made);    let edited = phone.act(T0 + 1_000, "update_todo", vec![Change::update(TODOS, TODO, obj(json!({"title": "Buy rye"})))]);    mac.take(&edited);    let mac_history = mac.history();    assert_eq!(mac_history.len(), 2, "one row per act per record: {mac_history:#?}");    assert_eq!(phone.history(), mac_history, "both devices hold the same history");    assert_eq!(mac_history[0]["verb"], "create_todo");    assert_eq!(mac_history[0]["kind"], "todo");    assert_eq!(mac_history[0]["table_id"], TODOS);    assert_eq!(mac_history[0]["record_id"], TODO);    assert_eq!(mac_history[1]["verb"], "update_todo");    let todo_receipt = edited.iter().find(|op| op.table == TODOS).expect("the todo's receipt");    assert_eq!(mac_history[1]["write_hlc"], Value::String(todo_receipt.hlc.clone()), "the row names the write's stamp");}/// RULE: A history row holds before and after of the moved fields only — a column named with its own value is not history.#[test]fn a_history_row_holds_the_moved_fields_only() {    let (mut mac, _) = pair();    mac.act(T0, "create_todo", vec![new_todo("Buy bread")]);    mac.act(        T0 + 1_000,        "update_todo",        vec![Change::update(TODOS, TODO, obj(json!({"title": "Buy rye", "priority": 0})))],    );    let history = mac.history();    assert_eq!(history[1]["before"], json!({"title": "Buy bread"}), "{history:#?}");    assert_eq!(history[1]["after"], json!({"title": "Buy rye"}), "{history:#?}");    assert_eq!(history[0]["before"], Value::Null, "a create has nothing before");    assert_eq!(history[0]["after"]["title"], "Buy bread");    // A write that moves nothing leaves no row.    mac.act(T0 + 2_000, "update_todo", vec![Change::update(TODOS, TODO, obj(json!({"title": "Buy rye"})))]);    assert_eq!(mac.history().len(), 2, "a write that moved nothing is not history");}/// RULE: Folding a peer's write writes no history — the history a device holds is only what arrived as history rows.#[test]fn folding_a_peer_write_writes_no_history() {    let (mut mac, phone) = pair();    let made = mac.act(T0, "create_todo", vec![new_todo("Buy bread")]);    phone.take(&without_history(&made));    assert!(phone.history().is_empty(), "the fold wrote history: {:#?}", phone.history());}/// RULE: An act that keeps no history (History::None) writes no history row.#[test]fn an_act_that_keeps_no_history_writes_none() {    let (mut mac, _) = pair();    mac.act_as(T0, "import", History::None, vec![new_todo("Buy bread")]);    assert!(mac.history().is_empty());}/// RULE: A retract keeps the record's history and adds its own row; an erase leaves no history row behind.#[test]fn a_retract_keeps_history_and_an_erase_leaves_none() {    let (mut mac, _) = pair();    mac.act(T0, "create_todo", vec![new_todo("Buy bread")]);    mac.act(T0 + 1_000, "delete_now", vec![Change::retract(TODOS, TODO)]);    let history = mac.history();    assert_eq!(history.len(), 2, "{history:#?}");    assert_eq!(history[1]["after"], Value::Null);    assert_eq!(history[1]["before"]["title"], "Buy bread");    mac.act(T0 + 2_000, "create_todo", vec![new_todo("Buy milk")]);    mac.act(T0 + 3_000, "empty_bin", vec![Change::erase(TODOS, TODO, "bin")]);    assert!(mac.history().is_empty(), "the erase took every history row: {:#?}", mac.history());}/// RULE: A secret column never reaches history in the clear — a document's password is written as has_password.#[test]fn a_password_never_reaches_history() {    let (mut mac, _) = pair();    let key = format!("{WORKSPACE}/doc.pdf");    mac.act(        T0,        "file_document",        vec![Change::create(            DOCUMENTS,            DOC,            obj(json!({"id": DOC, "workspace_id": WORKSPACE, "original_name": "doc.pdf", "mime": "application/pdf",                       "byte_size": 3, "sha256": "a".repeat(64), "storage_path": key, "status_changed_at": NOW,                       "password": "hunter2", "created_at": NOW, "updated_at": NOW})),        )],    );    let history = mac.history();    let text = serde_json::to_string(&history).expect("json");    assert!(!text.contains("hunter2"), "the password reached history: {text}");    assert_eq!(history[0]["after"]["has_password"], true, "{history:#?}");}/// RULE: A peer's history row for a record this file erased parks gone, as the record's own write does — history never outlives an erase.#[test]fn a_peers_history_row_for_an_erased_record_parks_gone() {    let (mut mac, mut phone) = pair();    let made = mac.act(T0, "create_todo", vec![new_todo("Buy bread")]);    phone.take(&made);    // The phone edits the todo before it hears of the erase.    let edited = phone.act(T0 + 5_000, "update_todo", vec![Change::update(TODOS, TODO, obj(json!({"title": "Buy rye"})))]);    assert!(edited.iter().any(|op| op.table == HISTORY_TABLE), "the edit carries its history row");    mac.act(T0 + 1_000, "empty_bin", vec![Change::erase(TODOS, TODO, "bin")]);    assert!(mac.history().is_empty());    let folded = arrive(&mac.db, &edited, Arrival::Handed).expect("folds");    assert!(folded.applied.is_empty(), "{folded:?}");    assert!(mac.history().is_empty(), "the peer's history row outlived the erase: {:#?}", mac.history());    for op in &edited {        let class = mac            .db            .get("SELECT class FROM _parked WHERE op_id = ?", &[rusqlite::types::Value::Text(op.op_id.clone())])            .expect("reads")            .and_then(|row| row.text("class").map(str::to_string));        assert_eq!(class.as_deref(), Some("gone"), "{} {} did not park gone", op.table, op.row_id);    }}/// RULE: The one history row an erased record keeps is the erase's own note — a generic verb's row in the erase's act, by its author, which every device takes.#[test]fn the_erases_own_note_stands_on_every_device() {    let (mut mac, phone) = pair();    phone.take(&mac.act(T0, "create_todo", vec![new_todo("Buy bread")]));    let note = Change::create(        HISTORY_TABLE,        "00000000-0000-4000-8000-00000000c001",        obj(json!({"id": "00000000-0000-4000-8000-00000000c001", "workspace_id": WORKSPACE, "table_id": "todo",                   "record_id": TODO, "verb": "delete", "byline": "owner", "before": "{\"state\":\"binned\"}",                   "created_at": NOW})),    );    let erase = mac.act(T0 + 1_000, "delete_record", vec![Change::erase(TODOS, TODO, "bin"), note]);    phone.take(&erase);    for dev in [&mac, &phone] {        let history = dev.history();        assert_eq!(history.len(), 1, "{history:#?}");        assert_eq!(history[0]["verb"], "delete");    }}