Cotton code
153 lines · 5.9 KB · RustRaw
// `ingest` only: the four source names this guard walks exist in the Mac's// build alone. An integration test has no `mod` line to hang a `#[cfg]` on, so// an inner attribute is the whole gate — the same shape// `ingest_end_to_end.rs` uses.#![cfg(feature = "ingest")]//! Where each import source got to is ONE MACHINE's bookkeeping.//!//! Every row an import writes carries the source's own stable id, so re-reading//! a position this machine has already passed writes nothing twice. The//! position itself is therefore an optimisation, and it belongs to the disk that//! read it: two machines reading the same Messages database are at different//! places in it, and a position that travelled would make one of them skip rows//! it has never seen.//!//! The half already held elsewhere is that the positions live INSIDE the replica//! (`replica_tests.rs`, `the_cursors_live_in_the_replica_so_deleting_the_file…`),//! so deleting the file forgets them with it. What is held here is the other//! half: writing one queues nothing for anybody else.//!//! Every fixture is synthetic.use cotton_client::ingest::SourceId;use cotton_client::seams::{FixedClock, SeededRandom};use cotton_client::{open_replica, read_ingest_cursor, write_ingest_cursor, Layout};use cotton_store::meta::Meta;const WORKSPACE: &str = "55555555-5555-4555-8555-555555555555";const OWNER: &str = "owner-99";/// The name of the device-local table the positions live in.const CURSOR_TABLE: &str = "_ingest_cursors";/// RULE: Where an import source got to is a note on the machine that read it, and it is never handed to another device.////// WHY: the import engine matches every row against the people and threads the/// file already holds, and it skips a row it has seen before by that row's own/// id. A position that travelled would put a second machine past rows it never/// read — which is an import that silently loses months of somebody's messages/// and reports success.#[test]fn a_sources_read_position_is_never_handed_to_another_device() {    let dir = tempfile::tempdir().expect("a temp dir");    let layout = Layout::new(dir.path().join("CottonDB"));    let template = dir.path().join("snapshot.db");    synthetic_workspace(&template);    let replica = open_replica(        &layout,        WORKSPACE,        &FixedClock::default_start(),        &SeededRandom::default(),        &mut |path: &std::path::Path| {            std::fs::copy(&template, path)                .map(|_| ())                .map_err(|error| error.to_string())        },    )    .expect("an open replica");    // Every one of the four readers, so a fifth source added without thinking    // about this cannot be the one that travels.    for source in SourceId::ALL {        write_ingest_cursor(            &replica.driver,            &source.cursor_key(&replica.device_id),            "42",            "2026-09-26T10:00:00.000Z",        )        .expect("a position is written");        assert_eq!(            read_ingest_cursor(&replica.driver, &source.cursor_key(&replica.device_id))                .expect("a position is read back")                .as_deref(),            Some("42"),            "{} keeps its own position",            source.as_str()        );    }    assert_eq!(        cotton_store::outbox::pending_count(&replica.driver).expect("the queue is countable"),        0,        "writing four read positions queued something for another device"    );    assert_eq!(        queued_rows_for(&replica, CURSOR_TABLE),        0,        "a read position was queued to be handed over"    );}/// RULE: The table an import source keeps its read position in is not one of the tables devices hand to each other.////// WHY: the handover walks a declared list of tables. A device-local table that/// turned up on that list would start travelling the moment anything wrote to/// it, with no code change anywhere near the import sources — so the absence is/// asserted against the list itself rather than inferred from today's writers.#[test]fn the_read_position_table_is_not_a_synced_table_at_all() {    let declared: Vec<&str> = cotton_store::schema::table_specs::TABLE_SPECS        .iter()        .map(|spec| spec.name)        .collect();    assert!(        !declared.is_empty(),        "the declared table list is empty — this guard is reading the wrong thing"    );    assert!(        !declared.contains(&CURSOR_TABLE),        "{CURSOR_TABLE} is declared as a synced table, so read positions would travel"    );}/// A whole workspace file at the canonical shape — a copy of the store's own/// test template, with a synthetic workspace row so the first real write does/// not fail a foreign key.fn synthetic_workspace(path: &std::path::Path) {    let db = cotton_store::test_template::create_workspace_for_test(        path,        &Meta {            workspace_id: WORKSPACE.to_string(),            owner_id: OWNER.to_string(),            device_id: "device:snapshot".to_string(),            last_server_seq: 0,            last_hlc: None,        },    )    .expect("a synthetic workspace file");    db.run(        "INSERT OR IGNORE INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)",        &[            rusqlite::types::Value::Text(WORKSPACE.to_string()),            rusqlite::types::Value::Text("A synthetic workspace".to_string()),            rusqlite::types::Value::Text(OWNER.to_string()),            rusqlite::types::Value::Text("2026-09-26T09:00:00.000Z".to_string()),        ],    )    .expect("the workspace row");}/// How many queued handovers name this table.fn queued_rows_for(replica: &cotton_client::Replica, table: &str) -> i64 {    replica        .driver        .get(            "SELECT COUNT(*) AS n FROM _outbox WHERE tbl = ?",            &[rusqlite::types::Value::Text(table.to_string())],        )        .expect("the queue is readable")        .and_then(|row| row.int("n"))        .unwrap_or(0)}