Cotton code
127 lines · 6.6 KB · RustRaw
use super::*;use cotton_core::rules::sync_state::SyncState;use cotton_client::seams::Clock as _;use cotton_client::layout::Layout;use serde_json::json;/// The household's second database, served by the same Mac.const KITCHEN: &str = "55555555-5555-4555-8555-555555555555";/// A Mac that serves nothing: its sample reaches the household's own file only.const MINI: &str = "synthetic-mini";const SERVING: &str = "synthetic-serving";fn stamp(at: chrono::DateTime<chrono::Utc>) -> String {    cotton_client::seams::iso(at)}/// One Mac row in a database; `sample` is (sampled_at, disk free, exchanged at).fn a_mac(db: &cotton_store::driver::Driver, workspace: &str, id: &str, sample: Option<(&str, f64, &str)>) {    let text = |value: &str| Sql::Text(value.to_string());    db.run(        "INSERT INTO cotton_devices (id,workspace_id,device_id,name,platform,approved_at,approved_by_device,created_at,updated_at,sampled_at,disk_free_gb,disk_total_gb,reported_state) \         VALUES (?,?,?,?,'mac','2026-09-01T00:00:00Z','self','2026-09-01T00:00:00Z','2026-09-01T00:00:00Z',?,?,228.0,?)",        &[            text(id), text(workspace), text(id), text(&format!("Synthetic {id}")),            sample.map_or(Sql::Null, |(at, _, _)| text(at)),            sample.map_or(Sql::Null, |(_, free, _)| Sql::Real(free)),            sample.map_or(Sql::Null, |(_, _, exchanged)| text(&json!({"last_exchange_at": exchanged}).to_string())),        ],    ).expect("a Mac row");}fn serving_fact(db: &cotton_store::driver::Driver, workspace: &str) {    db.run(        "INSERT INTO cotton_serving_machine (id,workspace_id,epoch,device_credential_id,author_id,since) \         VALUES (?,?,1,?,'synthetic-author','2026-09-01T00:00:00Z')",        &[Sql::Text(format!("serving-{workspace}")), Sql::Text(workspace.into()), Sql::Text(SERVING.into())],    ).expect("the serving fact");}/// A paired phone holding the household's own database and Kitchen, both/// served by one Mac, with the lines `lines` persisted from a previous run./// The Mac is fresh in the household's own file (sampled 2 min ago, 45 GB/// free, exchanged a minute ago) and as old as its last serve in Kitchen/// (sampled a day ago, 25.4 GB free).fn a_household(    lines: impl FnOnce(i64) -> Vec<(&'static str, cotton_client::sync::line::HomeLine)>,) -> (tempfile::TempDir, std::sync::Arc<ClientController>, chrono::DateTime<chrono::Utc>) {    let (dir, client, clock) = crate::shell::client::phone_tests::attached_on_a_clock();    let now = clock.now();    let layout = Layout::new(dir.path());    let record = layout.connection_json();    let mut connection: Value = serde_json::from_slice(&std::fs::read(&record).unwrap()).unwrap();    connection["places"] = json!([{ "id": KITCHEN, "name": "Kitchen", "available": true, "unavailableSince": null }]);    std::fs::write(&record, serde_json::to_vec_pretty(&connection).unwrap()).unwrap();    let path = layout.replica(KITCHEN);    std::fs::create_dir_all(path.parent().unwrap()).unwrap();    let kitchen = cotton_store::test_template::create_workspace_for_test(        &path,        &cotton_store::meta::Meta {            workspace_id: KITCHEN.to_string(),            owner_id: crate::fixture::OWNER.to_string(),            device_id: crate::fixture::DEVICE.to_string(),            last_server_seq: 0,            last_hlc: None,        },    ).unwrap();    kitchen.run(        "INSERT OR IGNORE INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?,'Kitchen',?,'2026-09-01T00:00:00Z')",        &[Sql::Text(KITCHEN.into()), Sql::Text(crate::fixture::OWNER.into())],    ).unwrap();    let ago = |minutes: i64| stamp(now - chrono::Duration::minutes(minutes));    a_mac(&kitchen, KITCHEN, MINI, Some((&ago(24 * 60), 25.4, &ago(24 * 60))));    a_mac(&kitchen, KITCHEN, SERVING, None);    serving_fact(&kitchen, KITCHEN);    drop(kitchen);    client.with_writer(|file| {        a_mac(file.driver, file.workspace_id, MINI, Some((&ago(2), 45.0, &ago(1))));        a_mac(file.driver, file.workspace_id, SERVING, None);        serving_fact(file.driver, file.workspace_id);        Ok(())    }).unwrap();    let kept = lines(now.timestamp_millis());    cotton_client::sync::line::store(        &layout.home_lines_json(),        &kept.into_iter().map(|(database, line)| (database.to_string(), line)).collect(),    );    drop(client);    let client = std::sync::Arc::new(        ClientController::new(layout, std::sync::Arc::new(crate::events::EventBus::new()), Some("UTC".into()), None)            .with_seams(clock.clone(), std::sync::Arc::new(cotton_client::seams::SeededRandom::default())),    );    client.set_self_device_id(Some(crate::fixture::SELF_DEVICE_ID.into()));    (dir, client, now)}/// RULE: the reachability fact is one per Mac (295 rule 16): a pass that/// went unanswered while database A was shown makes the serving Mac not/// heard in database B's sync state too, and B's copy of it — Me and Copies/// — never says "Up to date" or "heard just now" while A's says the Mac is/// away. Walker294: two other databases said "Up to date · synced/// 6 min ago" and Copies "heard just now", the relay unreachable.#[test]fn a_failure_seen_in_one_database_is_the_mac_not_heard_in_every_one() {    let (_dir, client, _now) = a_household(|now| {        use cotton_client::sync::line::{Answered, HomeLine};        let (mut personal, mut kitchen) = (HomeLine::default(), HomeLine::default());        personal.answered(Answered::default(), now - 6 * 60_000);        kitchen.answered(Answered::default(), now - 6 * 60_000 + 3);        // Only the shown database's line saw the pass that failed.        personal.unanswered(None, now - 60_000);        vec![(crate::fixture::WORKSPACE, personal), (KITCHEN, kitchen)]    });    for database in [crate::fixture::WORKSPACE, KITCHEN] {        let mut args = Map::new();        args.insert("database".into(), Value::from(database));        let answer: SyncState = serde_json::from_value(crate::phone::sync_state::read(&client, &args).unwrap()).unwrap();        let serving = answer.devices.iter().find(|copy| copy.device.serving).unwrap();        assert_eq!(serving.reachable, Some(false), "{database}: the Mac is not heard");        let copies = crate::phone::sync_state::copies(&client, &json!({"where": {"database": database}})).unwrap();        let own = copies.iter().find(|row| row["data"]["role"] == "this_device").unwrap();        assert_ne!(own["data"]["ambient"], "up_to_date", "{database}: {own}");        let mac = copies.iter().find(|row| row["data"]["role"] == "serving").unwrap();        assert_eq!(mac["data"]["reach"], "unreachable", "{database}: {mac}");    }}