//! Slice 3b: an undo is a FACT in `cotton_undos`, its id derived from the //! change undone, and its inverse rides as the act's own signed receipts, //! each naming the fact. Of two devices undoing one change, the earlier fact //! stands on every device and the other act parks whole; who wins a key is //! LWW by stamp, as for every other write. use std::sync::Arc; use cotton_store::actor::{Actor, JobName}; use cotton_store::fact_hooks::{undo_fact_id, UNDOS_TABLE}; 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_undo, 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 rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; const T0: i64 = 1_759_480_000_000; const PROJECTS: &str = "cotton_memory_projects"; const P: &str = "p-1"; /// The change being undone: the rename of P from "A" to "B". const RENAME: &str = "change-rename"; struct Ids(u32, &'static str); impl IdSource for Ids { fn next_op_id(&mut self, _now_ms: i64) -> cotton_store::Result { self.0 += 1; Ok(format!("{}-{:05}", self.1, self.0)) } } struct Dev { db: Driver, ids: Ids, fact: CottonOp, actor: Actor, tag: &'static str, } /// One device's file, signing with its own key, its author minted. 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")), tag } } fn obj(value: Value) -> Map { value.as_object().expect("an object").clone() } fn rename(name: &str) -> Change { Change::update(PROJECTS, P, obj(json!({"name": name}))) } /// The undo of [`RENAME`] as `dev` writes it: the fact first, then the inverse. fn undo_fact(dev: &Dev) -> Change { let fact = undo_fact_id(RENAME); Change::create( UNDOS_TABLE, &fact, obj(json!({ "id": fact, "workspace_id": WORKSPACE, "change_id": RENAME, "undo_change_id": format!("undo-change-{}", dev.tag), "at": NOW, "actor": dev.tag, })), ) } impl Dev { fn act(&mut self, at_ms: i64, changes: Vec) -> Vec { self.mint(at_ms, changes, None) } fn undo(&mut self, at_ms: i64) -> Vec { let fact = undo_fact_id(RENAME); let changes = vec![undo_fact(self), rename("A")]; self.mint(at_ms, changes, Some(&fact)) } fn mint(&mut self, at_ms: i64, changes: Vec, undo: Option<&str>) -> Vec { let act = Act { actor: self.actor.clone(), verb: "test".to_string(), history: History::None, changes }; mint_undo(&self.db, &act, &Clock::wall(at_ms), &mut self.ids, Held::Served, undo) .expect("mints") .ops } fn take(&self, ops: &[CottonOp]) -> FoldResult { arrive(&self.db, ops, Arrival::Handed).expect("folds") } fn name(&self) -> String { self.db .get(&format!("SELECT name FROM {PROJECTS} WHERE id = ?"), &[SqlValue::Text(P.to_string())]) .expect("reads") .and_then(|row| row.text("name").map(str::to_string)) .expect("P is here") } fn undo_author(&self) -> Option { self.db .get(&format!("SELECT _hlc FROM {UNDOS_TABLE} WHERE id = ?"), &[SqlValue::Text(undo_fact_id(RENAME))]) .expect("reads") .and_then(|row| row.text("_hlc").map(|hlc| hlc.get(19..).unwrap_or_default().to_string())) } /// Every receipt and tombstone this file holds, in order. fn receipts(&self) -> Vec { let mut out = Vec::new(); for place in ["_writes", "_tombstones"] { for row in self .db .all(&format!("SELECT tbl, row_id, hlc, op_id FROM {place} ORDER BY tbl, row_id, hlc, op_id"), &[]) .expect("reads") { out.push(format!( "{place} {} {} {} {}", row.text("tbl").unwrap_or_default(), row.text("row_id").unwrap_or_default(), row.text("hlc").unwrap_or_default(), row.text("op_id").unwrap_or_default() )); } } out } } /// Mac and phone, each holding P named "B" by the rename both have seen. fn start() -> (Dev, Dev) { let mut 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)); let born = mac.act( T0, vec![Change::create( PROJECTS, P, obj(json!({"id": P, "workspace_id": WORKSPACE, "slug": "p", "name": "A", "created_at": NOW, "updated_at": NOW})), )], ); phone.take(&born); let renamed = mac.act(T0 + 10, vec![rename("B")]); phone.take(&renamed); (mac, phone) } /// RULE: Two devices undoing one change keep one undo everywhere — the earlier fact stands, the later act parks whole on both, and an edit stamped between the two undos stands. #[test] fn two_devices_undoing_one_change_apply_one_inverse() { let (mut mac, mut phone) = start(); let mac_undo = mac.undo(T0 + 20); // An edit after the Mac's undo, which the phone has not seen when it undoes. let mac_edit = mac.act(T0 + 25, vec![rename("C")]); let phone_undo = phone.undo(T0 + 30); assert_eq!(phone.name(), "A", "the phone's own undo applies at first"); let at_mac = mac.take(&phone_undo); assert_eq!(at_mac.parked.len(), phone_undo.len(), "the phone's whole undo parks at the Mac: {:?}", at_mac.parked); let mut to_phone = mac_undo.clone(); to_phone.extend(mac_edit.iter().cloned()); let at_phone = phone.take(&to_phone); assert_eq!(at_phone.parked.len(), phone_undo.len(), "the phone's own undo is dropped and parked when the earlier one arrives: {:?}", at_phone.parked); for dev in [&mac, &phone] { assert_eq!(dev.name(), "C", "{}: the edit after the standing undo stands; the parked undo writes nothing", dev.tag); assert_eq!(dev.undo_author().as_deref(), Some(mac.fact.row_id.as_str()), "{}: the Mac's fact stands", dev.tag); } assert_eq!(mac.receipts(), phone.receipts(), "both devices hold the same receipts"); } /// RULE: An undo's inverse never overwrites an edit stamped after it, whichever arrives first. #[test] fn a_late_inverse_never_overwrites_a_later_edit() { let (mut mac, mut phone) = start(); let undo = mac.undo(T0 + 20); let edit = phone.act(T0 + 40, vec![rename("D")]); mac.take(&edit); phone.take(&undo); for dev in [&mac, &phone] { assert_eq!(dev.name(), "D", "{}: the later edit stands over the undo", dev.tag); } assert_eq!(mac.receipts(), phone.receipts(), "both devices hold the same receipts"); } /// RULE: No receipt a device holds lacks a signature — an undo's inverse is the act's own signed write, never one the fold writes for itself. #[test] fn every_receipt_of_an_undo_is_signed() { let (mut mac, phone) = start(); let undo = mac.undo(T0 + 20); assert!(undo.iter().all(|op| op.sig.is_some()), "every op of the undo is signed"); phone.take(&undo); for dev in [&mac, &phone] { let unsigned = dev .db .get("SELECT COUNT(*) AS n FROM _writes WHERE sig IS NULL OR length(sig) = 0", &[]) .expect("reads") .and_then(|row| row.int("n")) .unwrap_or(-1); assert_eq!(unsigned, 0, "{}: no _writes row lacks a signature", dev.tag); } }