Cotton code
437 lines · 19.1 KB · RustRaw
//! The three commands' names, their shapes, and what a screen can ask before//! anything is running.//!//! What is NOT here: the join and the bootstrap themselves. Those are proved in//! `cotton-client` (`join/join_tests.rs`, `bootstrap/{mod,download,claim}_tests.rs`)//! against a scripted exchange that sees the real signed headers — and proving//! them a second time through the FFI would be a second implementation of the//! same assertions over a slower fixture. What this file holds is the part the//! FFI actually owns: the method names, the event JSON a screen keys on, and//! the status a screen reads when it missed an event.use super::*;use cotton_client::replica::MigrationEvent;#[test]fn every_command_this_module_answers_is_in_the_phones_method_list() {    let names = crate::phone::method_names();    for method in commands::COMMAND_METHODS        .iter()        .chain(commands::MIGRATE_METHODS.iter())    {        assert!(            names.contains(&method.to_string()),            "{method} is answered and not declared"        );        assert!(            crate::methods::CLIENT_METHODS.contains(method),            "{method} is not in the client half's partition"        );    }}#[test]fn the_route_table_goes_through_the_boundary_as_paths_rather_than_a_count() {    // The Swift `Route` enum is held TOTAL against this list. It travels as    // PATHS so a mismatch names the route that moved — a count alone would say    // "109 != 110" and leave somebody diffing two files by eye.    assert!(routes::ROUTES.contains(&"/capture"));    assert!(routes::ROUTES.contains(&"/take"));    assert!(        routes::ROUTES.windows(2).all(|pair| pair[0] < pair[1]),        "the table is sorted, so a set comparison is a diff"    );}#[test]fn the_push_vocabulary_crosses_the_same_boundary_the_route_table_does() {    // The Swift notification table is held TOTAL against `PUSH_TYPES` the way    // the Swift `Route` enum is held total against `ROUTES` — one method, two    // lists, because a test can only compare two tables it can both see. The    // known hole rides with it, so the Swift assertion is "total, except these    // two, which are the ledger's" rather than a red test on arrival.    let dir = tempfile::tempdir().expect("a temp container");    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: None,        device_secret: None,        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: None,    })    .expect("an open core");    let answer = crate::methods::dispatch(&handle, "routes.list", &serde_json::json!({}))        .expect("the table");    let types: Vec<&str> = answer["pushTypes"]        .as_array()        .expect("a list")        .iter()        .filter_map(serde_json::Value::as_str)        .collect();    // The FFI must export the whole native registry as push types are added.    assert_eq!(types, cotton_core::rules::notifications::PUSH_TYPES);    // A representative name, and it is no longer `cotton_message`: the push    // that carried a message somebody else sent went with the sharing data    // plane in 5m. `cotton_session_question` is the shape that is left — a    // typed row the server created, with a screen to open.    assert!(types.contains(&"cotton_session_question"));    // **The hole is CLOSED, and the empty list is the assertion.** The two    // types nothing routed were `share_revoked` and `share_stale`, which went    // with the multi-person sharing data plane in 5m; every type the server    // can still emit has a screen. The field stays on the answer so the Swift    // guard keeps reading it rather than learning to skip it.    assert_eq!(        answer["pushTypesUnmapped"],        serde_json::json!([]),        "a type the app cannot route travels with the list, so the Swift guard can name it"    );    // And the routes are still there, unchanged: this method answers two    // questions and neither displaced the other.    assert_eq!(answer["count"], serde_json::json!(routes::ROUTES.len()));}#[test]fn a_migration_start_carries_the_step_count_the_screen_says_n_of_m_from() {    let painted = commands::migration_json_for_test(&MigrationEvent::Start {        from: 1,        to: 3,        total: 2,    });    assert_eq!(painted["phase"], "migrate");    assert_eq!(painted["stage"], "start");    assert_eq!(painted["total"], 2);    assert_eq!(painted["from"], 1);    assert_eq!(painted["to"], 3);}#[test]fn a_migration_step_is_one_based_so_step_n_of_m_reads_the_way_a_person_counts() {    let painted = commands::migration_json_for_test(&MigrationEvent::Step {        version: 2,        index: 1,        total: 2,    });    assert_eq!(painted["stage"], "step");    assert_eq!(painted["index"], 1);    assert_eq!(painted["total"], 2);}#[test]fn a_migration_that_rewound_the_cursor_says_so_rather_than_leaving_a_replay_unexplained() {    // `replayed` is the whole server log being folded again — minutes of work    // on a big file, and a screen that said nothing about it would look stuck.    let painted = commands::migration_json_for_test(&MigrationEvent::Done {        from: 1,        to: 2,        dropped_from_outbox: 3,        replayed: true,    });    assert_eq!(painted["stage"], "done");    assert_eq!(painted["droppedFromOutbox"], 3);    assert_eq!(painted["replayed"], true);}/// **Going to the back leaves nothing for the next launch to recover.**////// `cotton_close` runs from a Swift `deinit`, and a force-quit runs no/// `deinit` — so before this, every launch after one paid the write-ahead/// log's recovery inside the first `attach`, on a boundary that answers one/// call at a time, with the person looking at the splash. `sync.background`/// is the moment nobody is waiting, so the fold happens there./// RULE: The checkpoint guard owns its app process, temporary container and connections; sibling app tests must not share process-wide state that can reopen its WAL between checkpoint and the zero-length assertion.#[test]fn going_to_the_back_folds_the_write_ahead_log_back_into_the_file() {    if !crate::fixture::in_own_process(        module_path!(),        "going_to_the_back_folds_the_write_ahead_log_back_into_the_file",        cotton_core::flavor::Flavor::Real,    ) {        return;    }    use cotton_client::layout::Layout;    let dir = tempfile::tempdir().expect("a temp container");    let layout = Layout::new(dir.path());    std::fs::create_dir_all(layout.client_dir()).expect("the client folder");    std::fs::write(        layout.connection_json(),        serde_json::to_vec_pretty(&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("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");    // A PAIRED phone: the pull after its approval brought its own row, and    // it opens with the key that row is held under — a write is asked by the    // owner at that row.    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");    // A write, so there is something in the log to fold.    handle        .client()        .write(            "create_todo",            &[("title".to_string(), serde_json::json!("Something"))]                .into_iter()                .collect(),        )        .expect("the todo");    let wal = replica.with_file_name(format!(        "{}-wal",        replica.file_name().expect("a name").to_string_lossy()    ));    assert!(        std::fs::metadata(&wal).map(|meta| meta.len()).unwrap_or(0) > 0,        "the write is in the log to begin with"    );    let answer = crate::methods::dispatch(&handle, "sync.background", &serde_json::json!({}))        .expect("the scene phase");    assert_eq!(answer["checkpoint"], serde_json::json!(true));    // A retained sync timer may reopen an empty WAL after TRUNCATE. Its    // 32-byte header contains no frames to recover. Prove the write reached    // the main file itself, without copying or opening the original WAL.    let wal_bytes = std::fs::metadata(&wal).map(|meta| meta.len()).unwrap_or(0);    assert!(matches!(wal_bytes, 0 | 32), "checkpoint left WAL frames: {wal_bytes} bytes");    let main_only = dir.path().join("checkpointed.sqlite");    std::fs::copy(&replica, &main_only).expect("the checkpointed main file");    let persisted = cotton_store::Driver::open(&main_only).expect("the main file opens without its WAL");    assert!(persisted.get("SELECT title FROM cotton_todos WHERE title=?", &["Something".to_owned().into()])        .expect("the persisted todo").is_some(), "the todo must survive without WAL recovery");    // And going to the back still keeps the timer: this added a fold, it did    // not rewrite what going to the back means.    assert_eq!(answer["timer"], serde_json::json!("kept"));}// RULE: Phone attachment refuses an old schema without migrating or restamping the file.#[test]fn a_launch_with_an_old_schema_refuses_attachment_without_migrating() {    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");    std::fs::write(        layout.connection_json(),        serde_json::to_vec_pretty(&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("json"),    )    .expect("the connection record");    // The schema stamp is enough to refuse an old file, even if its tables    // would otherwise be readable. No historical runner enters normal builds.    let replica = layout.replica(crate::fixture::WORKSPACE);    std::fs::create_dir_all(replica.parent().expect("a parent")).expect("the replica folder");    {        let db = cotton_store::driver::Driver::open(&replica).expect("the file");        db.transaction(|db| {            cotton_store::migrate::migrate_store(db)?;            db.exec("PRAGMA user_version = 1")?;            cotton_store::meta::seed_meta(                db,                &cotton_store::meta::Meta {                    workspace_id: crate::fixture::WORKSPACE.to_string(),                    owner_id: crate::fixture::OWNER.to_string(),                    device_id: "device-server".to_string(),                    last_server_seq: 0,                    last_hlc: None,                },                1,            )        })        .expect("a version-1 file");    }    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: None,        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: None,    })    .expect("an open core");    let answer = crate::methods::dispatch(&handle, "read.syncStatus", &serde_json::json!({}))        .expect("the attachment status");    assert_eq!(answer["connected"], serde_json::json!(false));    // The refusal names no schema (passivemove rule 4): the numbers are the    // log's.    let reason = answer["reason"].as_str().expect("the refusal");    assert!(!reason.contains("schema"), "{reason}");    let db = cotton_store::driver::Driver::open(&replica).expect("the unchanged file");    assert_eq!(cotton_store::migrate::current_version(&db).expect("the stamp"), 1);}/// RULE: The wait screen names the step the core reports for an open — `recovering` when the last run left saved changes in the write-ahead log, `reading` otherwise — and never guesses a reason of its own.#[test]fn an_open_in_flight_says_which_step_it_is_on_through_migrate_status() {    // THE BUG THIS ANSWERS: the first open of a new build sat on "This takes a    // moment when the app was closed suddenly" — the screen's own guess — when    // the app had been updated, not closed. The step is now the core's: the    // controller marks the open for as long as it runs, decided by the file on    // disk, and `migrate.status` carries it when no ladder is running.    use crate::shell::client::OpenStep;    // Decided by the FILE. A connection that is dropped closes cleanly and    // SQLite folds its log away; one that is never closed (an app killed    // mid-run) leaves saved changes in the `-wal` beside the file.    let dir = tempfile::tempdir().expect("a folder");    let clean = dir.path().join("clean.sqlite");    {        let db = cotton_store::driver::Driver::open(&clean).expect("the file");        db.exec("CREATE TABLE t (x)").expect("a write");    }    assert_eq!(OpenStep::of(&clean), OpenStep::Reading, "a clean close leaves no log");    let killed = dir.path().join("killed.sqlite");    let db = cotton_store::driver::Driver::open(&killed).expect("the file");    db.exec("CREATE TABLE t (x)").expect("a write");    // Never closed, as a process that is killed never closes it.    std::mem::forget(db);    assert_eq!(OpenStep::of(&killed), OpenStep::Recovering, "a killed run leaves its log");    assert_eq!(OpenStep::of(&dir.path().join("absent.sqlite")), OpenStep::Reading);    // And carried to the screen while an open runs, absent when none does.    let container = tempfile::tempdir().expect("a container");    let handle = crate::handle::CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone {            container_path: container.path().to_string_lossy().to_string(),            previous_container_path: None,        },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: None,        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: None,    })    .expect("an open core");    let status = || {        crate::methods::dispatch(&handle, "migrate.status", &serde_json::json!({}))            .expect("the status")    };    assert_eq!(status(), serde_json::json!({ "running": false }));    handle.client().set_opening_for_test(Some(OpenStep::Recovering));    assert_eq!(        status(),        serde_json::json!({ "running": false, "opening": "recovering" })    );    handle.client().set_opening_for_test(Some(OpenStep::Reading));    assert_eq!(status(), serde_json::json!({ "running": false, "opening": "reading" }));    handle.client().set_opening_for_test(None);    assert_eq!(status(), serde_json::json!({ "running": false }));}#[test]fn a_ladder_step_names_the_versions_its_start_named() {    // The upgrade screen says "from version A to B", and a gate that came up    // after the `start` only ever reads a `step` — so the step carries both.    let container = tempfile::tempdir().expect("a container");    let handle = crate::handle::CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone {            container_path: container.path().to_string_lossy().to_string(),            previous_container_path: None,        },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: None,        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: None,    })    .expect("an open core");    use cotton_client::replica::MigrationEvent;    handle.commands().note_migration(MigrationEvent::Start { from: 39, to: 44, total: 5 });    handle.commands().note_migration(MigrationEvent::Step { version: 41, index: 2, total: 5 });    let status = crate::methods::dispatch(&handle, "migrate.status", &serde_json::json!({}))        .expect("the status");    assert_eq!(status["running"], serde_json::json!(true));    assert_eq!(status["stage"], serde_json::json!("step"));    assert_eq!(status["index"], serde_json::json!(2));    assert_eq!(status["from"], serde_json::json!(39));    assert_eq!(status["to"], serde_json::json!(44));    assert!(status.get("opening").is_none(), "a running ladder is the step");}// ── what this build says it is ──────────────────────────────────────────────// The bug the Code screen's Macs strip ran into: a Mac that pressed Start filed// its own device row as an iPhone, because `workspace.startLocal` carries no// platform and the fallback was a flat `ios`.#[test]fn a_caller_that_names_no_platform_is_filed_as_this_builds_own() {    use cotton_core::device::pairing::DevicePlatform;    // An explicit word still wins — a caller that names a platform is    // answering for itself, and the join form does.    assert_eq!(commands::asked_platform(Some("mac")), DevicePlatform::Mac);    assert_eq!(commands::asked_platform(Some("ios")), DevicePlatform::Ios);    assert_eq!(        commands::asked_platform(Some("android")),        DevicePlatform::Android    );    // Nothing, an empty string and a word no build knows all fall back.    assert_eq!(        commands::asked_platform(None),        commands::THIS_BUILDS_PLATFORM    );    assert_eq!(        commands::asked_platform(Some("")),        commands::THIS_BUILDS_PLATFORM    );    assert_eq!(        commands::asked_platform(Some("teleporter")),        commands::THIS_BUILDS_PLATFORM    );    // And on the slice the Mac app links, that fallback is a Mac. This is the    // assertion the bug would have failed: the tests run on macOS, exactly    // where the macOS slice is built.    #[cfg(target_os = "macos")]    assert_eq!(commands::THIS_BUILDS_PLATFORM, DevicePlatform::Mac);    #[cfg(target_os = "android")]    assert_eq!(commands::THIS_BUILDS_PLATFORM, DevicePlatform::Android);    #[cfg(target_os = "linux")]    assert_eq!(commands::THIS_BUILDS_PLATFORM, DevicePlatform::Linux);    #[cfg(not(any(target_os = "macos", target_os = "android", target_os = "linux")))]    assert_eq!(commands::THIS_BUILDS_PLATFORM, DevicePlatform::Ios);}