Cotton code
322 lines · 14.4 KB · RustRaw
//! `cotton_store::cottonpkg`: a database's records out as one `.cottonpkg`//! file, and into another database through the mint.use std::collections::BTreeMap;use cotton_store::actor::{Actor, JobName};use cotton_store::cottonpkg::{    export_package, import_package, Filter, Match, MediaSink, MediaSource, Package, Selection,};use cotton_store::fixtures::{file_at_version, NOW, OWNER};use cotton_store::meta::{seed_meta, Meta};use cotton_store::mint::{first_author, mint, Act, AuthorReason, Change, Clock, Held, History, IdSource};use cotton_store::schema::ddl::SCHEMA_VERSION;use cotton_store::Driver;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use sha2::{Digest, Sha256};const SOURCE: &str = "11111111-1111-4111-8111-111111111111";const TARGET: &str = "22222222-2222-4222-8222-222222222222";const T0: i64 = 1_759_480_000_000;struct Ids(u32);impl IdSource for Ids {    fn next_op_id(&mut self, _now_ms: i64) -> cotton_store::Result<String> {        self.0 += 1;        Ok(format!("op-{:05}", self.0))    }}/// A database whose own id is `id`, with its workspace row and its author.fn database(id: &str, device: &str) -> Driver {    let db = file_at_version(SCHEMA_VERSION);    seed_meta(        &db,        &Meta {            workspace_id: id.to_string(),            owner_id: OWNER.to_string(),            device_id: device.to_string(),            last_server_seq: 0,            last_hlc: None,        },        SCHEMA_VERSION,    )    .expect("seeds the identity");    db.run(        "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)",        &[text(id), text("A database"), text(OWNER), text(NOW)],    )    .expect("the workspace row");    first_author(&db, "key", Some("Test"), AuthorReason::First, &Clock::wall(T0 - 1), &mut Ids(90_000), Held::Served)        .expect("the file's author");    db}fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}fn job() -> Actor {    Actor::job(JobName::named("test").expect("a job name"))}fn object(value: Value) -> Map<String, Value> {    value.as_object().expect("an object").clone()}fn write(db: &Driver, changes: Vec<Change>) {    mint(        db,        &Act { actor: job(), verb: "test_write".to_string(), history: History::None, changes },        &Clock::wall(T0),        &mut Ids(1),        Held::Served,    )    .expect("the source write");}fn todo(id: &str, title: &str, label: Option<&str>) -> Change {    Change::create(        "cotton_todos",        id,        object(json!({"id": id, "workspace_id": SOURCE, "title": title, "label": label, "created_at": NOW, "updated_at": NOW})),    )}const PHOTO_BYTES: &[u8] = b"not really a jpeg";fn photo_hash() -> String {    hex::encode(Sha256::digest(PHOTO_BYTES))}fn photo(key: &str) -> Change {    let hash = photo_hash();    let id = format!("photo:{hash}");    Change::create(        "cotton_photos",        &id,        object(json!({            "id": id, "workspace_id": SOURCE, "key": key, "sha256": hash, "content_type": "image/jpeg",            "size_bytes": PHOTO_BYTES.len(), "taken_at": NOW, "created_at": NOW, "updated_at": NOW,        })),    )}/// Bytes by key, both ways.#[derive(Default)]struct Shelf(BTreeMap<String, Vec<u8>>);impl MediaSource for Shelf {    fn read(&mut self, key: &str) -> cotton_store::Result<Option<Vec<u8>>> {        Ok(self.0.get(key).cloned())    }}impl MediaSink for Shelf {    fn write(&mut self, key: &str, bytes: &[u8]) -> cotton_store::Result<()> {        self.0.insert(key.to_string(), bytes.to_vec());        Ok(())    }}fn all(table: &str) -> Selection {    Selection { table: table.to_string(), filter: Filter::default() }}fn count(db: &Driver, sql: &str) -> i64 {    db.get(sql, &[]).expect("reads").and_then(|row| row.int("n")).unwrap_or(0)}fn one(db: &Driver, sql: &str) -> Option<String> {    db.get(sql, &[]).expect("reads").and_then(|row| row.columns().first().and_then(|(_, value)| match value {        SqlValue::Text(text) => Some(text.clone()),        _ => None,    }))}fn import(db: &Driver, bytes: &[u8], sink: &mut Shelf) -> cotton_store::cottonpkg::Imported {    import_package(db, bytes, &job(), &Clock::wall(T0 + 1_000), &mut Ids(50_000), Held::Served, sink).expect("imports")}/// RULE: A package moves records between databases with their own ids, and every imported record is minted — it has its receipt in the importing file, under that file's author — with the source database's id rewritten to the importer's, in `workspace_id` and in the `{file}/` prefix of every media key, and the bytes land at the rewritten key (Cotton package brief, 22 Oct 2026).#[test]fn a_package_moves_records_and_their_bytes_into_another_database() {    let source = database(SOURCE, "device:01JSOURCE00000000000000000");    let key = format!("{SOURCE}/photos/{}.jpg", photo_hash());    write(&source, vec![todo("t1", "Buy milk", Some("home")), todo("t2", "Call the bank", None), photo(&key)]);    let mut shelf = Shelf::default();    shelf.0.insert(key.clone(), PHOTO_BYTES.to_vec());    let exported = export_package(&source, &[all("cotton_todos"), all("cotton_photos")], &mut shelf, NOW).expect("exports");    assert!(exported.missing_media.is_empty());    assert_eq!(exported.manifest.source_database, SOURCE);    assert_eq!(exported.manifest.tables.iter().map(|t| (t.table.as_str(), t.rows)).collect::<Vec<_>>(), [("cotton_todos", 2), ("cotton_photos", 1)]);    let target = database(TARGET, "device:01JTARGET00000000000000000");    let mut landed = Shelf::default();    let report = import(&target, &exported.bytes, &mut landed);    assert!(report.refused.is_empty(), "{:?}", report.refused);    assert_eq!(report.created.get("cotton_todos"), Some(&2));    assert_eq!(report.created.get("cotton_photos"), Some(&1));    assert_eq!(one(&target, "SELECT title FROM cotton_todos WHERE id = 't1'").as_deref(), Some("Buy milk"));    assert_eq!(one(&target, "SELECT workspace_id FROM cotton_todos WHERE id = 't2'").as_deref(), Some(TARGET));    let moved = format!("{TARGET}/photos/{}.jpg", photo_hash());    assert_eq!(one(&target, "SELECT key FROM cotton_photos").as_deref(), Some(moved.as_str()));    assert_eq!(landed.0.get(&moved).map(Vec::as_slice), Some(PHOTO_BYTES));    assert_eq!(report.media_written, 1);    let author = one(&target, "SELECT author_id FROM _meta").expect("an author");    assert_eq!(        count(&target, &format!("SELECT count(*) AS n FROM _writes WHERE row_id IN ('t1', 't2') AND author = '{author}'")),        2,        "each imported record carries a receipt minted here"    );}/// RULE: Importing the same package twice changes nothing the second time — every record is reported unchanged and no receipt is minted — and a record the importer changed since is brought back to the package's values in only the columns that differ.#[test]fn importing_the_same_package_twice_is_idempotent() {    let source = database(SOURCE, "device:01JSOURCE00000000000000000");    write(&source, vec![todo("t1", "Buy milk", Some("home")), todo("t2", "Call the bank", None)]);    let exported = export_package(&source, &[all("cotton_todos")], &mut Shelf::default(), NOW).expect("exports");    let target = database(TARGET, "device:01JTARGET00000000000000000");    import(&target, &exported.bytes, &mut Shelf::default());    let receipts = count(&target, "SELECT count(*) AS n FROM _writes");    let again = import(&target, &exported.bytes, &mut Shelf::default());    assert_eq!(again.unchanged.get("cotton_todos"), Some(&2));    assert!(again.created.is_empty() && again.changed.is_empty() && again.refused.is_empty());    assert_eq!(count(&target, "SELECT count(*) AS n FROM _writes"), receipts, "no receipt for a record that did not change");    mint(        &target,        &Act {            actor: job(),            verb: "test_write".to_string(),            history: History::None,            changes: vec![Change::update("cotton_todos", "t1", object(json!({"label": "work"})))],        },        &Clock::wall(T0 + 2_000),        &mut Ids(60_000),        Held::Served,    )    .expect("a local edit");    let third = import_package(&target, &exported.bytes, &job(), &Clock::wall(T0 + 3_000), &mut Ids(70_000), Held::Served, &mut Shelf::default())        .expect("imports");    assert_eq!(third.changed.get("cotton_todos"), Some(&1));    assert_eq!(third.unchanged.get("cotton_todos"), Some(&1));    assert_eq!(one(&target, "SELECT label FROM cotton_todos WHERE id = 't1'").as_deref(), Some("home"));}/// RULE: An export takes the records its filter names — by id, by a column's values, by whether a column is set — and never a record in the bin.#[test]fn an_export_takes_what_its_filter_names() {    let source = database(SOURCE, "device:01JSOURCE00000000000000000");    write(&source, vec![todo("t1", "One", Some("home")), todo("t2", "Two", Some("work")), todo("t3", "Three", None)]);    source.run("UPDATE cotton_todos SET trashed_at = ? WHERE id = 't2'", &[text(NOW)]).expect("binned");    let ids = |filter: Filter| -> Vec<String> {        let exported = export_package(&source, &[Selection { table: "cotton_todos".into(), filter }], &mut Shelf::default(), NOW)            .expect("exports");        let package = Package::from_bytes(&exported.bytes).expect("reads back");        package.records[0].1.iter().map(|row| row["id"].as_str().unwrap_or_default().to_string()).collect()    };    assert_eq!(ids(Filter::default()), ["t1", "t3"]);    assert_eq!(ids(Filter { ids: Some(vec!["t3".into()]), columns: vec![] }), ["t3"]);    assert_eq!(ids(Filter { ids: None, columns: vec![("label".into(), Match::Values(vec![json!("home")]))] }), ["t1"]);    assert_eq!(ids(Filter { ids: None, columns: vec![("label".into(), Match::Present(false))] }), ["t3"]);    let unknown = export_package(        &source,        &[Selection { table: "cotton_todos".into(), filter: Filter { ids: None, columns: vec![("nope".into(), Match::Present(true))] } }],        &mut Shelf::default(),        NOW,    );    assert!(unknown.is_err());}/// RULE: A package never carries a database's identity, credentials or system tables: an export naming one is refused with why, and so is an import of a package that names one.#[test]fn a_package_refuses_identity_and_credential_tables() {    let source = database(SOURCE, "device:01JSOURCE00000000000000000");    for table in ["cotton_workspaces", "cotton_mcp_tokens", "cotton_secrets", "_meta", "cotton_mcp_audit"] {        let refused = export_package(&source, &[all(table)], &mut Shelf::default(), NOW);        assert!(refused.is_err(), "{table} is refused");    }    let forged = Package {        manifest: cotton_store::cottonpkg::Manifest {            format: 1,            schema_version: SCHEMA_VERSION,            source_database: SOURCE.into(),            exported_at: NOW.into(),            tables: vec![cotton_store::cottonpkg::PackagedTable { table: "cotton_workspaces".into(), rows: 1 }],            media: vec![],        },        records: vec![("cotton_workspaces".into(), vec![object(json!({"id": SOURCE, "name": "x"}))])],        media: BTreeMap::new(),    };    let target = database(TARGET, "device:01JTARGET00000000000000000");    let bytes = forged.to_bytes().expect("writes");    let refused = import_package(&target, &bytes, &job(), &Clock::wall(T0), &mut Ids(1), Held::Served, &mut Shelf::default());    assert!(refused.is_err());}/// RULE: A package from a newer schema is refused whole, and a package whose media does not hold the bytes its hash names is not read at all.#[test]fn a_newer_or_damaged_package_is_refused() {    let source = database(SOURCE, "device:01JSOURCE00000000000000000");    let key = format!("{SOURCE}/photos/{}.jpg", photo_hash());    write(&source, vec![photo(&key)]);    let mut shelf = Shelf::default();    shelf.0.insert(key, PHOTO_BYTES.to_vec());    let exported = export_package(&source, &[all("cotton_photos")], &mut shelf, NOW).expect("exports");    let target = database(TARGET, "device:01JTARGET00000000000000000");    let mut newer = Package::from_bytes(&exported.bytes).expect("reads");    newer.manifest.schema_version = SCHEMA_VERSION + 1;    let refused = import_package(&target, &newer.to_bytes().expect("writes"), &job(), &Clock::wall(T0), &mut Ids(1), Held::Served, &mut Shelf::default());    assert!(refused.unwrap_err().to_string().contains("newer"));    let mut damaged = Package::from_bytes(&exported.bytes).expect("reads");    damaged.media.insert(photo_hash(), b"other bytes".to_vec());    assert!(Package::from_bytes(&damaged.to_bytes().expect("writes")).is_err());}/// RULE: A record whose bytes the source does not hold still travels, and its key is reported as missing rather than dropped in silence.#[test]fn missing_bytes_are_reported() {    let source = database(SOURCE, "device:01JSOURCE00000000000000000");    let key = format!("{SOURCE}/photos/{}.jpg", photo_hash());    write(&source, vec![photo(&key)]);    let exported = export_package(&source, &[all("cotton_photos")], &mut Shelf::default(), NOW).expect("exports");    assert_eq!(exported.missing_media, [key]);    assert_eq!(exported.manifest.tables[0].rows, 1);}/// RULE: An import writes owning parents before their children, whatever order the package lists the tables in, so a package holding an album and its items lands both.#[test]fn owning_parents_land_before_their_children() {    let source = database(SOURCE, "device:01JSOURCE00000000000000000");    write(        &source,        vec![            Change::create("cotton_media_albums", "a1", object(json!({                "id": "a1", "workspace_id": SOURCE, "kind": "trip", "title": "Goa", "starts_at": NOW, "ends_at": NOW,                "created_at": NOW, "updated_at": NOW,            }))),            Change::create("cotton_media_album_items", "i1", object(json!({                "id": "i1", "workspace_id": SOURCE, "album_id": "a1", "record_kind": "photo", "record_id": "photo:x",                "added_by": "user", "sort_at": NOW, "created_at": NOW, "updated_at": NOW,            }))),        ],    );    let exported =        export_package(&source, &[all("cotton_media_album_items"), all("cotton_media_albums")], &mut Shelf::default(), NOW)            .expect("exports");    let target = database(TARGET, "device:01JTARGET00000000000000000");    let report = import(&target, &exported.bytes, &mut Shelf::default());    assert!(report.refused.is_empty(), "{:?}", report.refused);    assert_eq!(count(&target, "SELECT count(*) AS n FROM cotton_media_album_items"), 1);}