Cotton code
178 lines · 10.4 KB · RustRaw
//! OFFLINE START (coordinator for the Android builder, 26 Nov 2026): with wifi and data off, a cold start drew the//! skeleton for about 11 s: `personal.connect` 2.2 to 4.0 s, then `shell.lines`, asked after it, answered at 11.6 s.//! A phone whose copy is already the object's opens it without asking the object anything, so neither call may wait//! on the network. Here the network is an exchange that hangs, as a phone with no network does on its lookup, and//! then fails.use std::sync::Arc;use std::time::{Duration, Instant};use cotton_client::transport::scripted::{Reply, ScriptedExchange};use cotton_client::transport::{http1::Http1Request, Answer, Exchange, Origin};use serde_json::json;use base64::Engine as _;use super::*;const DATABASE: &str = "11111111-1111-4111-8111-111111111111";const HANG: Duration = Duration::from_secs(6);/// No network: every request hangs for [`HANG`], then fails as a lookup with no network does.#[derive(Debug, Default)]struct NoNetwork {    asked: std::sync::atomic::AtomicUsize,}impl Exchange for NoNetwork {    fn send(&self, _origin: &Origin, _request: &Http1Request<'_>, ceiling: Duration) -> Result<Box<dyn Answer>, String> {        self.asked.fetch_add(1, std::sync::atomic::Ordering::SeqCst);        std::thread::sleep(HANG.min(ceiling));        Err("failed to lookup address information: no network".into())    }    fn send_stream(&self, origin: &Origin, request: &Http1Request<'_>, _body: &mut dyn std::io::Read, _length: u64, ceiling: Duration) -> Result<Box<dyn Answer>, String> {        self.send(origin, request, ceiling)    }}fn open_phone(dir: &tempfile::TempDir) -> CottonHandle {    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: Some(serde_json::from_str(include_str!("../../../../apps/cotton/App/CottonManifest/flavour.json")).expect("Cotton's manifest")),    })    .expect("an open core")}fn ask() -> serde_json::Value {    json!({"server": "https://cotton.example.com", "databaseId": DATABASE, "credential": "synthetic-credential", "windows": {"message": 90}, "deviceName": "An invented phone"})}/// RULE: A cold start with no network over a copy that is already the object's answers `personal.connect` and then `shell.lines` from the copy at once: neither waits on a request the network cannot answer.#[test]fn a_cold_start_with_no_network_answers_connect_and_the_lines_from_the_copy() {    let dir = tempfile::tempdir().expect("a temp container");    {        let first = open_phone(&dir);        let object = ScriptedExchange::new([            Reply::ok(&json!({"business": {"kind": "personal", "database_id": DATABASE, "timezone": "Asia/Kolkata"}, "tools": [], "tables": [], "etag": "e1"}).to_string()),            Reply::ok(&json!({"person": {"id": "owner-person", "phone": "+919000000009", "role": "owner"}, "version": 3}).to_string()),        ]);        call_with(&first, "personal.connect", &ask(), object as Arc<dyn Exchange>).expect("connected");        first.client().detach();    }    let started = Instant::now();    let handle = open_phone(&dir);    let opened = started.elapsed();    let offline = Arc::new(NoNetwork::default());    let mut asked = ask();    asked["dataKey"] = json!(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([7u8; 32]));    let at = Instant::now();    call_with(&handle, "personal.connect", &asked, Arc::clone(&offline) as Arc<dyn Exchange>).expect("connected offline");    let connect = at.elapsed();    let at = Instant::now();    let lines = crate::methods::shell_lines::lines(&handle, &json!({})).expect("the lines");    let shell_lines = at.elapsed();    let at = Instant::now();    let set = lines["sets"].as_object().and_then(|sets| sets.keys().next().cloned()).expect("a set");    crate::methods::shell_lines::lines(&handle, &json!({ "set": set })).expect("one set");    let one_set = at.elapsed();    // And while the loop's first pass hangs on the network, as it does on a phone with no network.    let waited = Instant::now();    while offline.asked.load(std::sync::atomic::Ordering::SeqCst) == 0 && waited.elapsed() < Duration::from_secs(10) {        std::thread::sleep(Duration::from_millis(20));    }    let in_flight = offline.asked.load(std::sync::atomic::Ordering::SeqCst) > 0;    std::thread::sleep(Duration::from_millis(200));    let at = Instant::now();    crate::methods::shell_lines::lines(&handle, &json!({})).expect("the lines while the pass hangs");    let during_pass = at.elapsed();    // What the launch asks beside the lines, on the same few native threads (Android's four): the key's status and    // the ways back in. Each asked the object on the caller's thread and waited out the lookup a phone with no network    // makes, so the lines queued behind them.    let mut beside = Vec::new();    for method in ["seal.status", "seal.status", "recovery.status", "recovery.status"] {        let at = Instant::now();        let _ = crate::methods::dispatch(&handle, method, &json!({}));        beside.push(format!("{method} {:?}", at.elapsed()));        assert!(at.elapsed() < Duration::from_secs(2), "{method} waited on the network: {:?}", at.elapsed());    }    let said = format!("{}; ", beside.join(", ")) + &format!("pass in flight {in_flight} after {:?}, shell.lines during it {during_pass:?}; ", waited.elapsed()) + &format!("open {opened:?}, personal.connect {connect:?}, shell.lines {shell_lines:?}, one set {one_set:?}; {} request(s) to a network that does not answer", offline.asked.load(std::sync::atomic::Ordering::SeqCst));    eprintln!("OFFLINE START {said}");    assert!(lines["sets"].as_object().is_some_and(|sets| !sets.is_empty()), "{lines}");    assert!(connect < Duration::from_secs(2), "{said}");    assert!(shell_lines < Duration::from_secs(2) && one_set < Duration::from_secs(2), "{said}");    assert!(during_pass < Duration::from_secs(2), "{said}");}/// RULE (UNSENT SEEN, 26 Nov 2026): a write this phone held two days because it cannot seal it is in the phone's report as names and counts (waiting by table and by code, the things with the raw writes beside them, the oldest waits), and Account's line says it cannot sync and what to do.#[test]fn a_write_held_for_its_seal_is_counted_in_the_report_and_said_on_account() {    let dir = tempfile::tempdir().expect("a temp container");    let handle = open_phone(&dir);    let object = ScriptedExchange::new([        Reply::ok(&json!({"business": {"kind": "personal", "database_id": DATABASE, "timezone": "Asia/Kolkata"}, "tools": [], "tables": [], "etag": "e1"}).to_string()),        Reply::ok(&json!({"person": {"id": "owner-person", "phone": "+919000000009", "role": "owner"}, "version": 3}).to_string()),    ]);    call_with(&handle, "personal.connect", &ask(), object as Arc<dyn Exchange>).expect("connected");    let client = handle.client();    let two_days_ago = (client.clock().now() - chrono::Duration::days(2)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true);    // Real receipts, minted as a write is (QUEUE BAD OP 3: invented `x'00'` bytes are now set aside as undecodable by    // the pass, as they should be), then held two days for want of a key.    client        .with_writer(|file| {            let mut ids = cotton_client::seams::op_ids(Arc::new(cotton_client::seams::SeededRandom::new(9)));            let at = "2026-11-24T10:00:00.000Z";            for (row, change) in [("todo-a", "create"), ("todo-a", "update"), ("todo-b", "create")] {                let mut patch = serde_json::Map::new();                patch.insert("title".into(), json!(format!("Invented {row} {change}")));                if change == "create" {                    patch.insert("workspace_id".into(), json!(file.workspace_id));                    patch.insert("status".into(), json!("open"));                    patch.insert("created_at".into(), json!(at));                }                patch.insert("updated_at".into(), json!(at));                let change = if change == "create" { cotton_store::mint::Change::create("cotton_todos", row, patch) } else { cotton_store::mint::Change::update("cotton_todos", row, patch) };                cotton_store::mint::mint(                    file.driver,                    &cotton_store::mint::Act {                        actor: cotton_store::actor::Actor::DeviceJob(cotton_store::actor::JobName::named("test").expect("a job name")),                        verb: "add_todo".into(),                        history: cotton_store::mint::History::None,                        changes: vec![change],                    },                    &cotton_store::mint::clock::writer_clock(file.driver, 1_764_000_000_000, &mut ids).map_err(|error| error.to_string())?,                    &mut ids,                    cotton_store::mint::Held::Replica,                )                .map_err(|error| error.to_string())?;            }            file.driver                .run(                    "UPDATE _outbox SET queued_at = ?, last_error = ?, attempts = 3 WHERE tbl = 'cotton_todos'",                    &[                        rusqlite::types::Value::Text(two_days_ago.clone()),                        rusqlite::types::Value::Text(cotton_store::outbox::coded(Some("seal_key_missing"), "seal_key_missing: no key for an invented table")),                    ],                )                .map_err(|error| error.to_string())?;            Ok(())        })        .expect("queued");    let state = client.device_state().expect("a report");    assert_eq!(state["waiting_by_code"]["seal_key_missing"], json!(3), "{state}");    assert_eq!(state["waiting_by_table"]["cotton_todos"], json!(2), "{state}");    assert!(state["unsent"].as_u64().is_some_and(|things| things >= 2) && state["unsent_ops"].as_u64().is_some_and(|ops| ops >= 3), "{state}");    assert_eq!(state["oldest_seal_waiting_at"], json!(two_days_ago), "{state}");    let said = state.to_string();    assert!(!said.contains("todo-a") && !said.contains("invented table"), "no row id or reason in the report: {said}");    let line = crate::methods::shell_account::tile_line(&client);    assert!(line.starts_with("3 changes can't sync"), "{line}");}