Cotton code
546 lines · 22.3 KB · RustRaw
//! A synthetic life on disk, for the browse tests.//!//! EVERY FIXTURE IS SYNTHETIC — no real name, number or sentence anywhere in//! this tree. The rows here are the ones the reads have opinions about: a table//! two kinds share, a binned row, a row with an empty sort column, a record//! with links and versions, a photo whose bytes are here and a video whose//! bytes are not.//!//! The successor to `apps/cotton/__tests__/browse/fixture.ts` and, in//! miniature, of `scripts/seed-walk.ts`.use cotton_store::driver::Driver;use cotton_store::meta::Meta;use rusqlite::types::Value as SqlValue;pub const WORKSPACE: &str = "11111111-1111-4111-8111-111111111111";/// [`WORKSPACE`] as the file a replica of it reads off itself — its own id,/// and its own id as its namespace.pub fn identity() -> &'static cotton_store::file_identity::FileIdentity {    static IDENTITY: std::sync::OnceLock<cotton_store::file_identity::FileIdentity> =        std::sync::OnceLock::new();    IDENTITY.get_or_init(|| cotton_store::file_identity::FileIdentity::for_tests(WORKSPACE))}/// [`WORKSPACE`]'s file id.pub fn file_id() -> &'static cotton_store::file_identity::FileId {    identity().id()}pub const OWNER: &str = "owner-synthetic";pub const DEVICE: &str = "device:00000000000000000000000000";/// THE ID A SERVER ADMITS THIS DEVICE BY — the shape of an Ed25519 device id,/// 43 base64url characters, and NOT [`DEVICE`], which is the AUTHOR id this/// file's ops carry. Two ids, two questions; the vault's key rows are filed/// under this one (`shell/client.rs`, `self_device_id`). Synthetic.pub const SELF_DEVICE_ID: &str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}/// A file with the whole schema and a synthetic life in it.////// No version is named: `create_workspace` always creates at the build's own/// `SCHEMA_VERSION`, so a number written here is a number that rots at the next/// migration — it said v45 through v46's three new tables, two of which 4k/// reads.////// `path` is the CALLER's to make unique, and every caller in this crate takes/// it from a `tempfile::tempdir` — two tests seeding one path would be two/// ladders over one file. The other half of that rule is `cotton-store`'s/// `test_template::building_path`, which is where this fixture's own flake/// lived: the template every copy comes from was built under a pid-and-clock/// name that two THREADS of one `cargo test` could share, and the loser's/// `table _meta already exists` surfaced right here, at whichever test was/// second.pub fn seeded(path: &std::path::Path) -> Driver {    // BUILT ONCE A BUILD AND COPIED for every test after: the synthetic life,    // its receipts, the shell and the kit are the same file for every case    // (a case's own rows go in after, through its `seed`), and writing the    // kit was most of every test in this crate — a minute each on the    // loaded Linux box (rust-main 7647, 6 Nov 2026). Keyed on this test    // binary's build, which is all the code that writes it, and on whether    // the thread asked for a [`bare`] file.    let bare = BARE.with(std::cell::Cell::get);    cotton_store::test_template::cached_for_test(        path,        if bare { "ffi-seeded-bare" } else { "ffi-seeded" },        &fixture_version(),        &Meta {            workspace_id: WORKSPACE.to_string(),            owner_id: OWNER.to_string(),            device_id: DEVICE.to_string(),            last_server_seq: 0,            last_hlc: None,        },        |db| {            db.run(                "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,?,?,?)",                &[                    text(WORKSPACE),                    text("Synthetic"),                    text(OWNER),                    text("2026-09-01T00:00:00.000Z"),                ],            )            .expect("the workspace row");            seed(db);            // A replicated row IS its receipts: a row seeded by plain SQL has            // none, so a later write to it would find nothing live and stay            // dormant. Each is given the create receipt the fold reads it from.            cotton_tools::test_fixtures::reconcile_all(db);            created_and_filled(db);            Ok(())        },    )    .expect("a file opens")}/// The build of the code that writes [`seeded`]'s file: this test binary's/// (its size and modification time) — the fixture is this crate's own code/// and every library it links — and the kit's bytes.fn fixture_version() -> String {    use std::hash::{Hash, Hasher};    let exe = std::env::current_exe().expect("the test binary");    let stat = std::fs::metadata(&exe).expect("the test binary's metadata");    let built = stat.modified().ok().and_then(|at| at.duration_since(std::time::UNIX_EPOCH).ok()).map(|at| at.as_nanos());    let mut hasher = std::collections::hash_map::DefaultHasher::new();    (exe, stat.len(), built, cotton_core::kit::fingerprint()).hash(&mut hasher);    format!("{:016x}", hasher.finish())}thread_local! {    static BARE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };}/// While the guard lives, [`seeded`] files on this thread hold no shell and/// no tool: for a case whose claim is about a database nobody filled.pub fn bare() -> Bare {    BARE.with(|bare| bare.set(true));    Bare}/// [`bare`]'s guard.pub struct Bare;impl Drop for Bare {    fn drop(&mut self) {        BARE.with(|bare| bare.set(false));    }}/// What this build writes at creation (the shell: the Bin, Home's board, the/// themes, the cap) and the kit a person imported — no tool is built in (72nd/// amendment, 21 Oct 2026), so a database with tools is one that took them by/// import. Written as the serving Mac wrote them, before this copy pulled.pub fn created_and_filled(db: &Driver) {    if BARE.with(std::cell::Cell::get) {        return;    }    let now = chrono::DateTime::parse_from_rfc3339("2026-09-01T00:00:00Z").expect("an instant").with_timezone(&chrono::Utc);    let random: std::sync::Arc<dyn cotton_tools::random::Random> = std::sync::Arc::new(cotton_tools::random::SystemRandom);    cotton_tools::presentation::write_shell(db, now, random.clone(), cotton_store::mint::Held::Served).expect("the shell writes");    cotton_tools::kit::import_kit_into(db, now, random).expect("the kit imports");    // Those rows arrived from the serving Mac under ITS author (its fact    // stays); this copy has not written yet, so it mints its own at its first    // write, as a pulled copy does.    db.run("UPDATE _meta SET author_id = NULL", &[]).expect("this copy has no author of its own yet");}/// After a case's raw `INSERT`/`UPDATE`, the receipt that says what the row it/// wrote now holds — without one, the next fold drops the row or the edit.pub fn receipted(db: &Driver, sql: &str) {    if let Some(table) = cotton_tools::test_fixtures::written_table(sql) {        cotton_tools::test_fixtures::reconcile(db, &table);    }}/// THIS DEVICE'S ROW in `cotton_devices`, approved and live, under/// [`SELF_DEVICE_ID`] — what a PAIRED device's copy holds once its first pull/// after approval lands. A write at the screen is asked by the owner at this/// row (`authoring::owner_actor`), so a harness claiming a paired device has/// to hold it. Synthetic.pub fn this_devices_row(db: &Driver) {    device_row(db, SELF_DEVICE_ID);}/// A synthetic Keychain seed, for a harness that opens a core through/// `CottonHandle::open` as a PAIRED phone: [`paired_secret`] is what the open/// config carries and [`paired_key`] the key its row is held under.pub const PAIRED_SEED: [u8; 32] = [7; 32];/// [`PAIRED_SEED`] as `OpenConfig.device_secret` carries it.pub fn paired_secret() -> String {    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};    URL_SAFE_NO_PAD.encode(PAIRED_SEED)}/// One of Cotton's own apps' manifests, written as/// `apps/cotton/App/Flavours/<flavour>/flavour.json` writes it: a personal/// object of one database, the fan opening on the app's kit, `name` its name./// A test of how the core behaves under an app opens this one; whether each/// SHIPPED manifest opens is shell.deck's tests' work, which read the files.pub fn own_app_manifest(flavour: &str, name: &str) -> serde_json::Value {    serde_json::json!({        "genesis": "personal",        "flavour": flavour,        "name": name,        "databases": "single",        "database": "personal",        "business": { "server": { "real": "https://cottondb.com", "dev": "https://cotton-business-dev.example" } },        "fan": { "home": false, "tools": false, "opens": flavour },        "kit": flavour,    })}/// The device key [`PAIRED_SEED`] opens as.pub fn paired_key() -> String {    cotton_client::DeviceIdentity::from_secret(&PAIRED_SEED)        .expect("a synthetic identity")        .device_id()}/// The serving Mac behind this phone: a live Mac's row beside this device's./// A phone's keep defaults narrow it only where a Mac answers for what it/// lets go (`cotton_store::keep::has_a_mac`); without one it keeps/// everything, as Rigby's only home does. Synthetic.pub fn a_mac_behind(db: &Driver) {    device_row(db, MAC_DEVICE_ID);    db.run("UPDATE cotton_devices SET platform = 'mac' WHERE device_id = ?", &[text(MAC_DEVICE_ID)]).expect("the Mac's platform");    cotton_tools::test_fixtures::reconcile(db, "cotton_devices");}/// The invented serving Mac's device key ([`a_mac_behind`]).pub const MAC_DEVICE_ID: &str = "device:invented-serving-mac";/// A live, approved `cotton_devices` row for `key` in [`WORKSPACE`] — the/// row a device holding that key writes as. Synthetic.pub fn device_row(db: &Driver, key: &str) {    db.run(        "INSERT INTO cotton_devices (id, workspace_id, device_id, name, approved_at, \         approved_by_device, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",        &[            text(&cotton_tools::devices::approval_row_id(WORKSPACE, key, "2026-09-08T09:00:00.000Z")),            text(WORKSPACE),            text(key),            text("An invented phone"),            text("2026-09-08T09:00:00.000Z"),            text("self"),            text("2026-09-08T09:00:00.000Z"),            text("2026-09-08T09:00:00.000Z"),        ],    )    .expect("this device's row");    cotton_tools::test_fixtures::reconcile(db, "cotton_devices");}fn seed(db: &Driver) {    // Three notes and two journal pages — the ONE table two kinds share.    for (at, id, title) in [        (1, "note-a", "First"),        (2, "note-b", "Second"),        (3, "note-c", "Third"),    ] {        db.run(            "INSERT INTO cotton_notes (id, workspace_id, kind, title, body, created_at, updated_at) \             VALUES (?,?,'note',?,?,?,?)",            &[                text(id),                text(WORKSPACE),                text(title),                text("A synthetic body with the word alpaca in it."),                text(&format!("2026-09-0{at}T00:00:00.000Z")),                text(&format!("2026-09-0{at}T00:00:00.000Z")),            ],        )        .expect("a note");    }    for (at, id) in [(4, "journal-a"), (5, "journal-b")] {        db.run(            "INSERT INTO cotton_notes (id, workspace_id, kind, title, body, journal_date, \             created_at, updated_at) VALUES (?,?,'journal',?,?,?,?,?)",            &[                text(id),                text(WORKSPACE),                text("A day"),                text("A synthetic journal page mentioning alpaca."),                text(&format!("2026-09-0{at}")),                text(&format!("2026-09-0{at}T00:00:00.000Z")),                text(&format!("2026-09-0{at}T00:00:00.000Z")),            ],        )        .expect("a journal page");    }    // A person and a project, for the name resolver — plus one archived person    // and one archived project, which it must not offer.    db.run(        "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) \         VALUES (?,?,?,?,?)",        &[            text("person-a"),            text(WORKSPACE),            text("Alpaca Tester"),            text("2026-09-01T00:00:00.000Z"),            text("2026-09-01T00:00:00.000Z"),        ],    )    .expect("a person");    db.run(        "INSERT INTO cotton_people (id, workspace_id, full_name, archived_at, created_at, \         updated_at) VALUES (?,?,?,?,?,?)",        &[            text("person-archived"),            text(WORKSPACE),            text("Alpaca Retired"),            text("2026-09-02T00:00:00.000Z"),            text("2026-09-01T00:00:00.000Z"),            text("2026-09-01T00:00:00.000Z"),        ],    )    .expect("an archived person");    for (id, slug, name, status) in [        ("project-a", "alpaca-work", "Alpaca Work", "active"),        ("project-old", "alpaca-old", "Alpaca Old", "archived"),    ] {        db.run(            "INSERT INTO cotton_memory_projects (id, workspace_id, slug, name, status, \             created_at, updated_at) VALUES (?,?,?,?,?,?,?)",            &[                text(id),                text(WORKSPACE),                text(slug),                text(name),                text(status),                text("2026-09-01T00:00:00.000Z"),                text("2026-09-01T00:00:00.000Z"),            ],        )        .expect("a project");    }    // What the inspector reads about `note-a`: a project link, a comment and a    // version.    db.run(        "INSERT INTO cotton_project_links (id, workspace_id, project_id, record_kind, record_id, \         applied_by, created_at, updated_at, pinned, position) VALUES (?,?,?,?,?,'user',?,?,0,1.0)",        &[            text("link-a"),            text(WORKSPACE),            text("project-a"),            text("note"),            text("note-a"),            text("2026-09-01T00:00:00.000Z"),            text("2026-09-01T00:00:00.000Z"),        ],    )    .expect("a project link");    db.run(        "INSERT INTO cotton_comments (id, workspace_id, record_kind, record_id, body, \         author_kind, author_user_id, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?)",        &[            text("comment-a"),            text(WORKSPACE),            text("note"),            text("note-a"),            text("A synthetic remark."),            text("user"),            text(OWNER),            text("2026-09-01T01:00:00.000Z"),            text("2026-09-01T01:00:00.000Z"),        ],    )    .expect("a comment");    db.run(        "INSERT INTO cotton_changes (id, workspace_id, table_id, record_id, verb, byline, before, \         after, actor, created_at) VALUES (?,?,?,?,?,?,?,?,?,?)",        &[            text("version-a"),            text(WORKSPACE),            text("cotton_notes"),            text("note-a"),            text("update_note"),            text("owner:d"),            text("{\"title\":\"Draft\"}"),            text("{\"title\":\"First\"}"),            text("owner:d"),            text("2026-09-01T02:00:00.000Z"),        ],    )    .expect("a version");    // Email: one live, one binned. The bin is the view that asks.    db.run(        "INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, created_at, \         updated_at) VALUES (?,?,?,?,?,?)",        &[            text("thread-a"),            text(WORKSPACE),            text("synthetic-thread-key"),            text("An alpaca thread"),            text("2026-09-01T00:00:00.000Z"),            text("2026-09-01T00:00:00.000Z"),        ],    )    .expect("an email thread");    for (id, trashed) in [        ("email-live", None),        ("email-binned", Some("2026-09-06T00:00:00.000Z")),    ] {        db.run(            "INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, from_email, \             sent_at, subject, body, created_at, trashed_at) \             VALUES (?,?,?,?,?,?,?,?,?,?)",            &[                text(id),                text(WORKSPACE),                text("thread-a"),                text(id),                text("nobody@example.invalid"),                text("2026-09-01T00:00:00.000Z"),                text("An alpaca message"),                text("A synthetic email body about an alpaca."),                text("2026-09-01T00:00:00.000Z"),                trashed.map_or(SqlValue::Null, text),            ],        )        .expect("an email");    }    // A todo with no due date, so a sort on an empty column has something to    // page through.    for (id, due) in [        ("todo-a", Some("2026-09-10T00:00:00.000Z")),        ("todo-b", None),        ("todo-c", None),    ] {        db.run(            "INSERT INTO cotton_todos (id, workspace_id, title, due_at, created_at, updated_at) \             VALUES (?,?,?,?,?,?)",            &[                text(id),                text(WORKSPACE),                text("A synthetic todo"),                due.map_or(SqlValue::Null, text),                text("2026-09-01T00:00:00.000Z"),                text("2026-09-01T00:00:00.000Z"),            ],        )        .expect("a todo");    }}/// The key of the one photo the fixture pretends to hold bytes for.pub fn photo_key(sha: &str) -> String {    cotton_core::media::keys::photo_key(file_id(), sha, "jpg")}/// The environment variable that tells a child test process which one test it/// was started to run as its own app ([`in_own_process`]).const OWN_PROCESS_ENV: &str = "COTTON_TEST_OWN_PROCESS";/// Run the calling test as its own app — `cotton_client::test_support`'s/// helper, which is private to that crate's tests, for this crate's.////// A declared flavor is the whole process's (`cotton_core::flavor::declare` —/// one process is one app), so a test that declares one must not share its/// process with this crate's other tests. 11 Oct 2026: one invite test/// declared Dev in a plain `cargo test -p cotton-ffi`, and every test that ran/// after it and named a household without `-dev` — 22 of them, the tunnel's/// eight first — was refused as the other app's (nextest, one process per/// test, hid it).////// Call it first, with the test's `module_path!()` and name: in the test run/// it starts this test binary again for that one test, with `flavor` to/// declare, waits for it to pass and answers false (the caller returns); in/// that child it declares `flavor` and answers true (the caller runs its body).pub fn in_own_process(module: &str, test: &str, flavor: cotton_core::flavor::Flavor) -> bool {    let path = match module.split_once("::") {        Some((_crate, rest)) => format!("{rest}::{test}"),        None => test.to_string(),    };    if std::env::var(OWN_PROCESS_ENV).ok().as_deref() == Some(path.as_str()) {        cotton_core::flavor::declare(flavor).expect("the child declares one flavor");        return true;    }    let output = std::process::Command::new(std::env::current_exe().expect("this test binary"))        .args(["--exact", &path, "--test-threads=1", "--nocapture"])        .env(OWN_PROCESS_ENV, &path)        .output()        .expect("the test binary starts again");    let said = String::from_utf8_lossy(&output.stdout);    assert!(        output.status.success() && said.contains("1 passed"),        "{path} in its own process:\n{said}\n{}",        String::from_utf8_lossy(&output.stderr)    );    false}/// RULE: no test in this crate declares a flavor except through [`in_own_process`] — 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-ffi` (11 Oct 2026: 22 failed by order; nextest hid it)./// The binaries under `src/bin` are each their own process and declare their own.#[test]fn only_a_test_in_its_own_process_declares_a_flavor() {    fn walk(dir: &std::path::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() {                if !path.ends_with("bin") {                    walk(&path, found);                }            } else if path.extension().is_some_and(|ext| ext == "rs") && !path.ends_with("fixture.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(&std::path::Path::new(&manifest).join("src"), &mut found);    assert!(found.is_empty(), "declare a flavor only through fixture::in_own_process: {found:?}");}/// A paired phone over the synthetic fixture, shared by preference guards.#[cfg(test)]pub(crate) fn synthetic_phone() -> (tempfile::TempDir, crate::handle::CottonHandle) {    let dir = tempfile::tempdir().expect("a temp container");    let layout = cotton_client::layout::Layout::new(dir.path());    std::fs::create_dir_all(layout.client_dir()).expect("the client folder");    // not a copy: a fixture's file, made for a test database.    std::fs::write(        layout.connection_json(),        serde_json::to_vec(&serde_json::json!({            "mode": "remote",            "baseUrl": "https://server.invalid",            "workspaceId": crate::fixture::WORKSPACE,            "ownerId": crate::fixture::OWNER,            "connectedAt": "2026-09-11T10:00:00.000Z",        }))        .expect("connection json"),    )    .expect("the connection record");    let replica = layout.replica(crate::fixture::WORKSPACE);    std::fs::create_dir_all(replica.parent().expect("a parent")).expect("the replica folder");    let seeded = crate::fixture::seeded(&replica);    crate::fixture::device_row(&seeded, &crate::fixture::paired_key());    drop(seeded);    let handle = crate::handle::CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone {            container_path: dir.path().to_string_lossy().to_string(),            previous_container_path: None,        },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: Some(crate::fixture::paired_secret()),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: None,    })    .expect("an open core");    (dir, handle)}