Cotton code
596 lines · 23.6 KB · RustRaw
//! The fixtures every suite in this crate shares.//!//! **Every fixture is synthetic.** A real number, name or message text anywhere//! in this tree is a hard failure//! ([nothing-real-ever-goes-in-cotton-s-public-tree]), so the numbers below are//! reserved-for-fiction ranges, the names are made up, and the sources are//! built row by row with `rusqlite` rather than copied off a Mac. The//! TypeScript suites did exactly this and probed the real files by COUNTING//! rows, never by reading them.use std::path::Path;use std::collections::BTreeMap;use cotton_store::driver::Driver;use cotton_store::meta::Meta;use cotton_store::protocol::types::{ExchangeRequest, ExchangeResponse, PushRejection};use rusqlite::types::Value as SqlValue;pub const WORKSPACE: &str = "55555555-5555-4555-8555-555555555555";pub const OWNER: &str = "owner-99";/// [`WORKSPACE`] as the file a replica of it reads off itself.pub fn file_id() -> &'static cotton_store::file_identity::FileId {    static ID: std::sync::OnceLock<cotton_store::file_identity::FileId> = std::sync::OnceLock::new();    ID.get_or_init(|| cotton_store::file_identity::FileId::for_tests(WORKSPACE))}/// [`WORKSPACE`]'s namespace — its own id, as for every database not made at/// the stop.pub fn namespace() -> &'static cotton_store::file_identity::Namespace {    static NS: std::sync::OnceLock<cotton_store::file_identity::Namespace> =        std::sync::OnceLock::new();    NS.get_or_init(|| cotton_store::file_identity::Namespace::for_tests(WORKSPACE))}/// A whole workspace file at the canonical shape, with the workspace row every/// domain row's foreign key points at — what a server's snapshot looks like.////// **A COPY of a template, not a ladder run from zero.** Why, what it costs and/// why the cache is a FILE and not a `OnceLock` are all in/// `cotton_store::test_template` — the short version is that `cargo nextest`/// runs every test in its own process, so a process-local cache is a cache of/// one. A first attempt used a `static OnceLock` here and was a measured/// REGRESSION for exactly that reason; it shipped in #537 and this replaces it.pub fn write_snapshot(path: &Path) {    write_snapshot_for(path, WORKSPACE);}/// [`write_snapshot`] for another database — a place this device syncs/// beside Mine.pub fn write_snapshot_for(path: &Path, workspace_id: &str) {    let db = cotton_store::test_template::create_workspace_for_test(        path,        &Meta {            workspace_id: workspace_id.to_string(),            owner_id: OWNER.to_string(),            device_id: "device:snapshot".to_string(),            last_server_seq: 0,            last_hlc: None,        },    )    .expect("a workspace file");    seed_workspace_row_for(&db, workspace_id);}/// The `cotton_workspaces` row. A file with `_meta` but no workspace row fails/// a foreign key on the first real write, which is exactly what a snapshot from/// a live server never has.pub fn seed_workspace_row(db: &Driver) {    seed_workspace_row_for(db, WORKSPACE);}fn seed_workspace_row_for(db: &Driver, workspace_id: &str) {    db.run(        "INSERT OR IGNORE INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)",        &[            SqlValue::Text(workspace_id.to_string()),            SqlValue::Text("A synthetic workspace".to_string()),            SqlValue::Text(OWNER.to_string()),            SqlValue::Text("2026-09-08T09:00:00.000Z".to_string()),        ],    )    .expect("the workspace row");}/// A replica of `workspace` at its own address in `layout`, with `todos`/// records in it and checkpointed, so its bytes are the whole file.pub fn replica_with_rows(layout: &crate::Layout, workspace: &str, todos: usize) -> std::path::PathBuf {    const AT: &str = "2026-09-16T09:00:00.000Z";    let path = layout.replica(workspace);    std::fs::create_dir_all(path.parent().expect("a parent")).expect("the folder");    let db = Driver::open(&path).expect("a file");    cotton_store::create::create_workspace(        &db,        &Meta {            workspace_id: workspace.to_string(),            owner_id: "owner-1".to_string(),            device_id: "device:this-phone".to_string(),            last_server_seq: 0,            last_hlc: None,        },    )    .expect("the ladder runs");    db.run(        "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?, 'A synthetic workspace', 'owner-1', ?)",        &[            SqlValue::Text(workspace.to_string()),            SqlValue::Text(AT.to_string()),        ],    )    .expect("the workspace row");    cotton_tools::test_fixtures::reconcile(&db, "cotton_workspaces");    for n in 0..todos {        db.run(            "INSERT INTO cotton_todos (id, title, status, created_at, updated_at, workspace_id, _hlc)\n             VALUES (?, 'Call the bank', 'open', ?, ?, ?, ?)",            &[                SqlValue::Text(format!("todo-{n}")),                SqlValue::Text(AT.to_string()),                SqlValue::Text(AT.to_string()),                SqlValue::Text(workspace.to_string()),                SqlValue::Text(format!("000178739460000{n}:0001:device:this-phone")),            ],        )        .expect("a todo");        cotton_tools::test_fixtures::reconcile(&db, "cotton_todos");    }    db.checkpoint_truncate().expect("a checkpoint");    drop(db);    path}/// Write a whole connection record: Mine (`mine`, in `mode`) and the places,/// each listed and available.pub fn write_record(    layout: &crate::Layout,    mine: &str,    mode: crate::connection::ConnectionMode,    places: &[&str],) {    crate::connection::write_record(        &layout.connection_json(),        &crate::connection::ConnectionRecord {            left_databases: Vec::new(),            pending_leaves: Vec::new(),            mine: crate::connection::StoredConnection {            device_scope: None,            takes_placements: false,                mode,                base_url: cotton_core::device::pairing::relay_origin_for_name("studio")                    .expect("the synthetic relay name"),                workspace_id: Some(mine.to_string()),                owner_id: Some(OWNER.to_string()),                connected_at: Some("2026-09-08T10:00:00.000Z".to_string()),            },            places: places                .iter()                .map(|id| crate::connection::PlaceEntry {                    id: (*id).to_string(),                    name: Some("A synthetic place".to_string()),                    available: true,                    unavailable_since: None,                    origin: None,                    server_device_id: None,                    removed_at: None,                    removed_by: None,                    pending: false,                    toolkit: None,                })                .collect(),        },    )    .expect("the record");}/// A database an earlier invite joined at another person's Mac, added to the/// record on disk: its place, with the origin it is reached at and the Mac it/// is pinned to.pub fn hold_joined(layout: &crate::Layout, id: &str, origin: &str, mac: &str) {    let path = layout.connection_json();    let mut record = crate::connection::read_record(&path).expect("a read").expect("a record");    record.places.push(crate::connection::PlaceEntry {        id: id.to_string(),        name: Some("A synthetic joined database".to_string()),        available: true,        unavailable_since: None,        origin: Some(origin.to_string()),        server_device_id: Some(mac.to_string()),        removed_at: None,        removed_by: None,        pending: false,        toolkit: None,    });    crate::connection::write_record(&path, &record).expect("the record");}/// A `Layout` over a fresh temp folder, and the folder that must outlive it.pub fn temp_layout() -> (tempfile::TempDir, crate::Layout) {    let dir = tempfile::tempdir().expect("a temp dir");    let layout = crate::Layout::new(dir.path().join("CottonDB"));    (dir, layout)}/// A bootstrap that copies a snapshot this test built.pub fn bootstrap_from(source: std::path::PathBuf) -> impl FnMut(&Path) -> Result<(), String> {    move |destination: &Path| {        // not a copy: a test's invented file copied into a test's own folder.        std::fs::copy(&source, destination)            .map(|_| ())            .map_err(|error| error.to_string())    }}/// The replica every client suite opens: a fresh data directory, a synthetic/// snapshot, and the file open on top of it.pub fn open_test_replica() -> (tempfile::TempDir, crate::Layout, crate::Replica) {    let (dir, layout) = temp_layout();    let snapshot = dir.path().join("snapshot.db");    write_snapshot(&snapshot);    let replica = crate::open_replica(        &layout,        WORKSPACE,        &crate::seams::FixedClock::default_start(),        &crate::seams::SeededRandom::default(),        &mut bootstrap_from(snapshot),    )    .expect("an open replica");    (dir, layout, replica)}/// A replica of `workspace_id` in an existing data directory — a device that/// syncs several databases holds one per database, side by side.pub fn open_replica_for(    layout: &crate::Layout,    scratch: &Path,    workspace_id: &str,) -> crate::Replica {    let snapshot = scratch.join(format!("snapshot-{workspace_id}.db"));    write_snapshot_for(&snapshot, workspace_id);    crate::open_replica(        layout,        workspace_id,        &crate::seams::FixedClock::default_start(),        &crate::seams::SeededRandom::default(),        &mut bootstrap_from(snapshot),    )    .expect("an open replica")}/// What a fake transport was asked, in order.////// ONE VERB, so the interesting thing about a call is what it CARRIED: the old/// `Pull { since } / Push { ops }` pair proved an ORDER that no longer exists —/// a device cannot send without receiving.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Call {    Exchange { ops: usize },}/// A transport that answers whatever the test told it to, and remembers.#[derive(Debug, Default)]pub struct FakeTransport {    pub calls: std::sync::Mutex<Vec<Call>>,    /// Set to refuse the next exchange with this refusal.    pub refusal: std::sync::Mutex<Option<crate::transport::ServerRefusal>>,    /// Scripted answers, popped in order. An empty script answers the default:    /// everything accepted, nothing of the peer's own, no more.    pub answers: std::sync::Mutex<std::collections::VecDeque<ExchangeResponse>>,    /// What the DEFAULT answer says for `hasMore` — once.    pub has_more: std::sync::Mutex<bool>,    /// Set to HOLD every op the request carries under this reason word — a    /// peer whose build is behind the writer's — instead of accepting it.    pub hold: std::sync::Mutex<Option<&'static str>>,    /// The schema every answer SAYS the peer's file is at — a Mac on another    /// build than this one. None answers without the field, as an older Mac    /// does.    pub schema: std::sync::Mutex<Option<u32>>,    /// The Mac every answer says it came from; None answers without it.    pub answered_by: std::sync::Mutex<Option<cotton_store::protocol::types::AnsweredBy>>,    /// Whether this transport says it would take a copy of the whole file —    /// a phone (`RefusalAware::takes_copy`).    pub takes_copies: std::sync::Mutex<bool>,    /// What each exchange request said of `takesCopy`, in order.    pub said_takes_copy: std::sync::Mutex<Vec<bool>>,    last: std::sync::Mutex<Option<crate::transport::ServerRefusal>>,}impl FakeTransport {    pub fn calls(&self) -> Vec<Call> {        self.calls.lock().expect("the log").clone()    }    pub fn refuse(&self, refusal: crate::transport::ServerRefusal) {        *self.refusal.lock().expect("the slot") = Some(refusal);    }    /// Hand back these answers, in order, before the default one.    pub fn script(&self, answers: impl IntoIterator<Item = ExchangeResponse>) {        *self.answers.lock().expect("the script") = answers.into_iter().collect();    }    /// Hold every op under this reason word from now on.    pub fn hold_as(&self, code: &'static str) {        *self.hold.lock().expect("the slot") = Some(code);    }    /// Back to accepting everything.    pub fn hold_as_nothing(&self) {        *self.hold.lock().expect("the slot") = None;    }    /// Every answer from now on says the peer's file is at this schema.    pub fn says_schema(&self, version: u32) {        *self.schema.lock().expect("the slot") = Some(version);    }    /// Every answer from now on names the Mac it came from.    pub fn says_answered_by(&self, name: &str, version: &str) {        *self.answered_by.lock().expect("the slot") = Some(cotton_store::protocol::types::AnsweredBy {            name: name.to_string(),            version: Some(version.to_string()),        });    }    /// Every answer from now on names no schema — an older Mac's answer.    pub fn says_no_schema(&self) {        *self.schema.lock().expect("the slot") = None;    }}/// An answer that HELD everything it was handed, retryably, under one word.pub fn held(request: &ExchangeRequest, code: &'static str) -> ExchangeResponse {    ExchangeResponse {        answered_by: None,        wanted: Vec::new(),        copy: None,        workspace_id: request.workspace_id.clone(),        schema_version: None,        ops: Vec::new(),        cursors: BTreeMap::new(),        has_more: false,        applied_rows: BTreeMap::new(),        rejected: request            .ops            .iter()            .map(|op| PushRejection::held(op.op_id.clone(), "the peer is behind", code))            .collect(),        seen: BTreeMap::new(),        serving_epoch: None,        server_time: None,        restored: None,        copy_night: None,        behind_by: None,        owed_at_start: None,        owed_by_table: None,        passed: None,        wake_refusal: None,    }}/// An answer that accepted everything it was handed and had nothing of its own.pub fn accepted(request: &ExchangeRequest, has_more: bool) -> ExchangeResponse {    let mut applied_rows: BTreeMap<String, usize> = BTreeMap::new();    let mut rows: Vec<(&str, &str)> = Vec::new();    for op in &request.ops {        let row = (op.table.as_str(), op.row_id.as_str());        if rows.contains(&row) {            continue;        }        rows.push(row);        *applied_rows.entry(op.table.clone()).or_default() += 1;    }    let mut seen = request.cursors.clone();    // The fake already owns the synthetic snapshot handed to every replica.    seen.insert(        "origin".to_string(),        format!("origin:cotton_workspaces:{WORKSPACE}"),    );    for op in &request.ops {        let at = seen.entry(op.device_id.clone()).or_default();        if op.hlc > *at {            *at = op.hlc.clone();        }    }    ExchangeResponse {        answered_by: None,        wanted: Vec::new(),        copy: None,        workspace_id: request.workspace_id.clone(),        schema_version: None,        ops: Vec::new(),        cursors: BTreeMap::new(),        has_more,        applied_rows,        rejected: Vec::new(),        seen,        serving_epoch: None,        server_time: None,        restored: None,        copy_night: None,        behind_by: None,        owed_at_start: None,        owed_by_table: None,        passed: None,        wake_refusal: None,    }}impl crate::transport::RefusalAware for &FakeTransport {    fn last_refusal(&self) -> Option<crate::transport::ServerRefusal> {        self.last.lock().expect("the slot").clone()    }    fn takes_copy(&self, _database: &str) -> bool {        *self.takes_copies.lock().expect("the flag")    }}impl cotton_store::exchange::SyncTransport for &FakeTransport {    fn exchange(&mut self, request: &ExchangeRequest) -> Result<ExchangeResponse, String> {        self.calls.lock().expect("the log").push(Call::Exchange {            ops: request.ops.len(),        });        self.said_takes_copy            .lock()            .expect("the log")            .push(request.takes_copy);        if let Some(refusal) = self.refusal.lock().expect("the slot").clone() {            *self.last.lock().expect("the slot") = Some(refusal.clone());            return Err(refusal.message);        }        *self.last.lock().expect("the slot") = None;        let says = (            *self.schema.lock().expect("the slot"),            self.answered_by.lock().expect("the slot").clone(),        );        if let Some(code) = *self.hold.lock().expect("the slot") {            return Ok(saying(held(request, code), says));        }        if let Some(scripted) = self.answers.lock().expect("the script").pop_front() {            return Ok(saying(scripted, says));        }        let has_more = *self.has_more.lock().expect("the flag");        // Answered once: a `hasMore` that never went false would make the cycle        // walk its whole ten-page cap on every test.        *self.has_more.lock().expect("the flag") = false;        Ok(saying(accepted(request, has_more), says))    }}/// The answer, with the schema the test said the peer says (a scripted answer/// that already names one keeps its own).fn saying(    mut answer: ExchangeResponse,    (says, by): (Option<u32>, Option<cotton_store::protocol::types::AnsweredBy>),) -> ExchangeResponse {    if answer.schema_version.is_none() {        answer.schema_version = says;    }    if answer.answered_by.is_none() {        answer.answered_by = by;    }    answer}/// Queue one local change, so there is something in the outbox to push.pub fn queue_one_change(replica: &crate::Replica, title: &str) {    queue_one_change_for(replica, WORKSPACE, title);}/// [`queue_one_change`] in another database's replica.pub fn queue_one_change_for(replica: &crate::Replica, workspace_id: &str, title: &str) {    one_change(replica, workspace_id, title, None);}/// One change minted with no server time this launch: applied here and HELD,/// in no outbox, until judge time releases it.pub fn hold_one_change(replica: &crate::Replica, title: &str) {    let clock = cotton_store::mint::Clock::judged(None, 1_760_000_000_000, 5_000, "synthetic-boot".to_string());    one_change(replica, WORKSPACE, title, Some(clock));}fn one_change(replica: &crate::Replica, workspace_id: &str, title: &str, held: Option<cotton_store::mint::Clock>) {    // Seeded off the row, so two changes in one test mint two op ids: the    // outbox holds `op_id` UNIQUE, and a fixture that minted one twice would    // fail on the constraint rather than on the thing being tested.    let seed = title.bytes().fold(1u64, |acc, byte| {        acc.wrapping_mul(31).wrapping_add(u64::from(byte))    });    let mut ids = crate::seams::op_ids(std::sync::Arc::new(crate::seams::SeededRandom::new(seed)));    let clock = || 1_760_000_000_000i64;    let mut patch = serde_json::Map::new();    patch.insert("workspace_id".to_string(), workspace_id.into());    patch.insert("title".to_string(), title.into());    patch.insert("status".to_string(), "open".into());    patch.insert("created_at".to_string(), "2026-09-08T10:00:00.000Z".into());    patch.insert("updated_at".to_string(), "2026-09-08T10:00:00.000Z".into());    cotton_store::mint::mint(        &replica.driver,        &cotton_store::mint::Act {            actor: cotton_store::actor::Actor::DeviceJob(                cotton_store::actor::JobName::named("test").expect("a job name"),            ),            verb: "queue_todo".to_string(),            // ONE queued change: a kept act would queue its history row too.            history: cotton_store::mint::History::None,            // A row this file has never held: its first write is a create.            changes: vec![cotton_store::mint::Change::create(                "cotton_todos",                &format!("todo-{title}"),                patch,            )],        },        &match held {            Some(held) => held,            None => cotton_store::mint::clock::writer_clock(&replica.driver, clock(), &mut ids).expect("the replica's clock"),        },        &mut ids,        cotton_store::mint::Held::Replica,    )    .expect("a queued change");}/// Open a fixture database — one a test writes, reads back, and throws away.////// SQLite's default is `synchronous = FULL` over a rollback journal with one/// autocommit per statement, so every `INSERT` costs an `fsync`. Measured on/// this repo's CI box (2026-09-12, run 2877's disk under a full nextest pool):/// **1,038 ms per autocommitted insert**, against 1.5 ms with `synchronous`/// off. That single fact is almost the whole of this crate's test time — the/// 103-asset photo library spent 428 s writing itself and a fifteen-row/// WhatsApp backup spent 45 s, none of it inside anything under test.////// A fixture in a `tempfile::tempdir()` has nothing to survive a crash for: it/// is deleted when the test that wrote it ends, and no other process ever opens/// it. The durability it was paying for does not exist, so it stops paying./// Every row, every statement and every read is unchanged.pub fn open_fixture_db(path: &Path) -> rusqlite::Connection {    let db = rusqlite::Connection::open(path).expect("a fixture database");    db.pragma_update(None, "synchronous", "OFF")        .expect("a fixture does not fsync");    db}/// Op ids that never repeat across calls in one test process: each call/// draws from its own seed, so two writes in one millisecond never mint one/// op id twice (the outbox holds `op_id` UNIQUE).pub fn fresh_ids() -> impl cotton_store::outbox::IdSource {    static NEXT_SEED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);    // Odd seeds only: `SeededRandom` sets the low bit, so seeds 2 and 3 would    // be one generator.    let seed = NEXT_SEED.fetch_add(2, std::sync::atomic::Ordering::Relaxed);    crate::seams::op_ids(std::sync::Arc::new(crate::seams::SeededRandom::new(seed)))}/// A peer's create of `row_id` at `hlc` (which ends in `author`), with its/// receipt as `mint` makes one — the receipt is the write, so a case builds/// it against the table's own columns and codecs (`test_fixtures::peer_op`).pub fn peer_create(    op_id: &str,    table: &str,    row_id: &str,    patch: serde_json::Map<String, serde_json::Value>,    hlc: &str,    author: &str,) -> PeerOp {    let change = cotton_store::mint::Change::create(table, row_id, patch);    cotton_tools::test_fixtures::peer_op(&change, hlc, author, "test", op_id)}/// The op a peer hands over.pub type PeerOp = cotton_store::protocol::types::CottonOp;/// RULE: nothing in this crate declares a flavor — a declared flavor/// is the whole process's, so one test declaring it changes every test that runs after it in a/// plain `cargo test -p cotton-client` (11 Oct 2026: ~178 failed by order; nextest hid it).#[test]fn only_a_test_in_its_own_process_declares_a_flavor() {    fn walk(dir: &Path, found: &mut Vec<String>) {        for entry in std::fs::read_dir(dir).expect("the source folder reads") {            let path = entry.expect("an entry").path();            if path.is_dir() {                walk(&path, found);            } else if path.extension().is_some_and(|ext| ext == "rs") && !path.ends_with("test_support.rs") {                let text = std::fs::read_to_string(&path).expect("a source file reads");                if text.contains("flavor::declare(") {                    found.push(path.display().to_string());                }            }        }    }    let mut found = Vec::new();    let manifest = std::env::var("CARGO_MANIFEST_DIR").expect("cargo test names the manifest directory");    walk(&Path::new(&manifest).join("src"), &mut found);    assert!(found.is_empty(), "a test declared a flavor: {found:?}");}