156 lines · 5.9 KB · RustRaw
//! Encode simulator fixture changes with the store's canonical receipt writer, reading its database without writing it.//!//! The running server holds its database folder, so this never opens that//! folder through the store: it takes one consistent snapshot of the file//! (`VACUUM INTO`, over a read-only connection) into a fresh folder the caller//! names under its own lane, and reads the copy.use cotton_store::{driver::Driver, protocol::types::CottonOp};use serde_json::Value;fn encode(db: &Driver, raw: Vec<Value>) -> Result<Vec<CottonOp>, Box<dyn std::error::Error>> { use cotton_store::{ actor::{Actor, JobName}, mint, outbox::LocalChange, wire, }; let local: Vec<LocalChange> = raw .iter() .cloned() .map(serde_json::from_value) .collect::<Result<_, _>>()?; let changes = mint::changes_of(db, &local); let actor = Actor::device_job(JobName::named("sim-pair")?); raw.iter() .zip(changes) .map(|(op, change)| { // The author fact is saved between seeds. Its op id must always name // the original bytes, even after its row already exists in the file. if op.get("receipt").is_some() { return wire::op(op).map_err(Into::into); } let text = |key: &str| { op.get(key) .and_then(Value::as_str) .filter(|value| !value.is_empty()) .ok_or_else(|| format!("seed op has no {key}")) }; Ok(wire::op_of_change( db, &change, text("hlc")?, text("deviceId")?, &actor, text("opId")?.to_string(), )?) }) .collect()}/// A consistent copy of `source` at `<fresh>/life.db`. `fresh` must be a new,/// empty folder: the copy is this process's own, never a file somebody holds.fn snapshot(source: &str, fresh: &std::path::Path) -> Result<std::path::PathBuf, Box<dyn std::error::Error>> { std::fs::create_dir_all(fresh)?; if std::fs::read_dir(fresh)?.next().is_some() { return Err(format!("{} is not an empty folder", fresh.display()).into()); } let copy = fresh.join("life.db"); let held = rusqlite::Connection::open_with_flags(source, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?; held.execute("VACUUM INTO ?1", [copy.to_string_lossy()])?; // VACUUM INTO writes a rollback-journal file; the store reads only WAL. rusqlite::Connection::open(©)?.query_row("PRAGMA journal_mode=WAL", [], |_| Ok(()))?; Ok(copy)}fn main() -> Result<(), Box<dyn std::error::Error>> { let mut args = std::env::args().skip(1); let usage = "usage: seed-receipts <life.db> <fresh folder> < changes.json"; let source = args.next().ok_or(usage)?; let fresh = args.next().ok_or(usage)?; let db = Driver::open_reader(snapshot(&source, std::path::Path::new(&fresh))?)?; let raw = serde_json::from_reader(std::io::stdin().lock())?; serde_json::to_writer(std::io::stdout().lock(), &encode(&db, raw)?)?; Ok(())}#[cfg(test)]mod tests { use super::*; use cotton_store::{ canonical::{self, Kind}, create::create_workspace, meta::Meta, }; use serde_json::json; fn database() -> Driver { let db = Driver::open_in_memory().unwrap(); create_workspace( &db, &Meta { workspace_id: "synthetic-workspace".into(), owner_id: "synthetic-owner".into(), device_id: "device:synthetic".into(), last_server_seq: 0, last_hlc: None, }, ) .unwrap(); db } fn change(id: &str, patch: Value) -> Value { json!({"opId":id,"deviceId":"device:sim-pair","kind":"upsert", "table":"cotton_workspaces","rowId":"synthetic-workspace","patch":patch, "hlc":format!("1791043200000:{:04}:device:sim-pair", if id == "seed-change" { 1 } else { 0 })}) } // RULE: Simulator seeds carry canonical receipts with the store's column codecs, so a successful seed cannot be 401 rejected legacy ops. #[test] fn creates_and_changes_are_receipts_and_encoding_never_writes_the_database() { let db = database(); let raw = vec![ change( "seed-create", json!({"id":"synthetic-workspace", "name":"A synthetic life","owner_user_id":"synthetic-owner", "created_at":"2026-10-03T00:00:00.000Z"}), ), change("seed-change", json!({"name":"A changed synthetic life"})), ]; let ops = encode(&db, raw).unwrap(); let receipts: Vec<_> = ops .iter() .map(|op| canonical::decode(op.receipt.as_bytes()).unwrap()) .collect(); assert_eq!(receipts[0].kind, Kind::Create); assert_eq!(receipts[1].kind, Kind::Change); assert_eq!(receipts[0].actor, "device-job:sim-pair"); assert!(!receipts[0].fields.contains_key("id")); assert!(db .get("SELECT id FROM cotton_workspaces", &[]) .unwrap() .is_none()); for op in &ops { assert_eq!( cotton_store::wire::op(&serde_json::to_value(op).unwrap()).unwrap(), *op ); } let folded = cotton_store::fold::fold_ops(&db, &ops).unwrap(); assert!(folded.rejected.is_empty(), "{:?}", folded.rejected); assert_eq!( db.get("SELECT name FROM cotton_workspaces", &[]) .unwrap() .unwrap() .text("name"), Some("A changed synthetic life") ); // A persisted author fact must keep its exact bytes and op id on every seed. assert_eq!( encode(&db, vec![serde_json::to_value(&ops[0]).unwrap()]).unwrap(), vec![ops[0].clone()] ); }}