Cotton code
385 lines · 19.9 KB · RustRaw
//! A fresh phone-only database's own calls answer: a phone that started its//! own database and has met no Mac. Rigby build 2's walk (22 Oct 2026) found//! these refused on a fresh install, in its Debug screen's failure list.//! Every name and row is synthetic.use std::sync::{Arc, Mutex};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine;use cotton_client::transport::{ClientAnswer, ClientRequest, ServerFetch, ServerRefusal};use serde_json::{json, Value};use crate::handle::{CottonHandle, OpenConfig, OpenMode};use crate::methods::MethodError;/// A phone that started its own database: `local`, no server address.fn a_phone_on_its_own() -> (tempfile::TempDir, CottonHandle) {    a_phone_on_its_own_with(None)}/// The same phone in an app whose manifest is `manifest`.fn a_phone_on_its_own_with(manifest: Option<Value>) -> (tempfile::TempDir, 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");    std::fs::write(        layout.connection_json(),        serde_json::to_vec_pretty(&json!({            "mode": "local",            // Empty, which is what `start_local` writes: there is no server.            "baseUrl": "",            "workspaceId": crate::fixture::WORKSPACE,            "ownerId": crate::fixture::OWNER,            "connectedAt": "2026-10-22T06: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");    drop(crate::fixture::seeded(&replica));    let handle = CottonHandle::open(OpenConfig {        mode: 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(URL_SAFE_NO_PAD.encode([7u8; 32])),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest,    })    .expect("an open core");    (dir, handle)}fn ask(handle: &CottonHandle, method: &str, request: Value) -> Result<Value, MethodError> {    crate::methods::dispatch(handle, method, &request)}/// RULE: keep.audience answers through the dispatch, which takes `database` off the request and names that file, so the method reads the named file and never requires the argument.////// WHY: 22 Oct 2026, Rigby build 2's walk — the record page and the/// new-record form ask `keep.audience { database, table, id? }`, the dispatch/// strips `database` before any method runs, and the method then refused/// every caller with "opening a record needs database".#[test]fn keep_audience_answers_the_database_the_call_names() {    let (_dir, handle) = a_phone_on_its_own();    for request in [        json!({ "database": crate::fixture::WORKSPACE, "table": "todo" }),        json!({ "database": crate::fixture::WORKSPACE, "table": "todo", "id": "00000000-0000-4000-8000-000000000001" }),        json!({ "table": "todo" }),    ] {        let answer = ask(&handle, "keep.audience", request.clone())            .unwrap_or_else(|error| panic!("{request}: {}: {}", error.code, error.message));        // A personal database offers no Only you: there is nobody else in it.        assert_eq!(answer["offered"], json!(false), "{request}: {answer}");        assert_eq!(answer["audience"], Value::Null, "{request}: {answer}");    }}/// A fresh install before its first open: no connection record, no database.fn a_fresh_install() -> (tempfile::TempDir, 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");    let handle = CottonHandle::open(OpenConfig {        mode: 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(URL_SAFE_NO_PAD.encode([7u8; 32])),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: None,    })    .expect("an open core");    (dir, handle)}/// Ask through the C boundary, as CottonCore does: the envelope, and what/// the boundary logs.fn ask_over_ffi(handle: &mut CottonHandle, method: &str, request: Value) -> Value {    let method = std::ffi::CString::new(method).unwrap();    let body = std::ffi::CString::new(request.to_string()).unwrap();    unsafe {        let ptr = crate::ffi::cotton_call(handle, method.as_ptr(), body.as_ptr());        let answer = serde_json::from_slice(std::ffi::CStr::from_ptr(ptr).to_bytes()).unwrap();        crate::ffi::cotton_string_free(ptr);        answer    }}fn debug_section(handle: &CottonHandle, heading: &str) -> Vec<String> {    crate::shell::diagnostics::debug_sections(handle)        .into_iter()        .find(|section| section.heading == heading)        .unwrap_or_else(|| panic!("Debug has a {heading} section"))        .lines}/// RULE: On a database no server serves — a phone that started its own, or a fresh install before its first open has made one — devices.pending sends nothing and answers the typed refusal not_served; Debug lists it under "Not used on this device" and never under Failures.////// WHY: 22 Oct 2026, Rigby build 3 (at f7fef5070, after e24cf807e) still/// listed push.register and devices.pending no_server. iOS hands the app its/// alert token at launch, BEFORE the first open has written a connection/// record, and with no record `no_mac_yet` answered "served", so both went to a transport/// with no address. e24cf807e's guard asked after the record was written and/// never met that order (architect's row C1).#[test]fn a_server_less_database_calls_no_server_and_debug_lists_it_as_not_used() {    #[derive(Debug, Default)]    struct Server(Mutex<Vec<ClientRequest>>);    impl ServerFetch for Server {        fn call(&self, request: ClientRequest) -> Result<ClientAnswer, ServerRefusal> {            self.0.lock().unwrap().push(request);            Err(ServerRefusal::offline("no address").with_code("no_server"))        }    }    let boot = [("devices.pending", json!({}))];    let (_fresh_dir, fresh) = a_fresh_install();    let (_own_dir, own) = a_phone_on_its_own();    for (name, mut handle) in [("a fresh install", fresh), ("a phone on its own", own)] {        let server = Arc::new(Server::default());        handle.client().set_fetch(Some(server.clone()));        for (method, request) in &boot {            let answer = ask_over_ffi(&mut handle, method, request.clone());            assert_eq!(answer["ok"], json!(false), "{name}: {method}: {answer}");            assert_eq!(answer["error"]["code"], json!(crate::phone::database_calls::NOT_SERVED), "{name}: {method}: {answer}");        }        assert!(server.0.lock().unwrap().is_empty(), "{name}: a database no server serves sends nothing");        let failures = debug_section(&handle, "Failures").join("\n");        let not_used = debug_section(&handle, "Not used on this device");        for (method, _) in &boot {            assert!(!failures.contains(method), "{name}: {method} is not a failure: {failures}");            assert!(not_used.iter().any(|line| line == method), "{name}: {method} is listed as not used: {not_used:?}");        }    }}/// RULE: Every database is created with the sync engine's tables, copy and schema_move, so a fresh database's Home sync line and move line read their rows and never "No tool draws this table".////// WHY: 22 Oct 2026, Rigby build 2's walk — copy.json went with the/// definitions 13e1775e7 deleted, while the sync engine's rows still lean on/// it for every word; the shell never carried it, so a fresh database/// refused every `records.list {table: "copy"}` Home asks each 20 seconds.#[test]fn a_fresh_database_reads_its_copies_and_its_moves() {    let (_dir, handle) = a_phone_on_its_own();    for table in ["copy", "schema_move"] {        let answer = ask(&handle, "records.list", json!({ "database": crate::fixture::WORKSPACE, "table": table }))            .unwrap_or_else(|error| panic!("{table}: {}: {}", error.code, error.message));        assert!(answer["records"].is_array(), "{table}: {answer}");    }}/// RULE: Every database is created with the shell kit's face choices (`face_settings`), so a database the phone starts reads and keeps the face each deck wears and never answers "No tool draws this table".////// WHY: 1 Nov 2026, local Cotton's first walk — a fresh install opened Home/// under a "Face choice: No tool draws this table." alert: the deck reads/// `face_settings` on every open, the object serves it with the shell, and/// the shell a phone writes left it out.#[test]fn a_fresh_database_keeps_its_face_choices() {    let (_dir, handle) = a_phone_on_its_own();    let list = |handle: &CottonHandle| {        ask(handle, "records.list", json!({ "database": crate::fixture::WORKSPACE, "table": "face_settings" }))            .unwrap_or_else(|error| panic!("{}: {}", error.code, error.message))    };    assert_eq!(list(&handle)["records"].as_array().map(Vec::len), Some(0));    this_devices_row(&handle);    ask(&handle, "records.create", json!({ "database": crate::fixture::WORKSPACE, "table": "face_settings", "data": { "table": "person", "face": "person.passport" } }))        .unwrap_or_else(|error| panic!("{}: {}", error.code, error.message));    assert_eq!(list(&handle)["records"].as_array().map(Vec::len), Some(1));}/// This device's own row, approved by itself, as a phone that founds its/// database writes it.fn this_devices_row(handle: &CottonHandle) -> String {    let slot = handle.client().receipt_signer_slot();    let signer = slot.get().expect("a receipt signer");    handle        .client()        .with_writer(|file| {            crate::fixture::device_row(file.driver, &signer.device_key());            Ok(())        })        .expect("this device's row");    handle.client().self_device_id().expect("this device's id")}/// RULE: In an app whose manifest says "sync": false, This Device says the database lives here alone and shows none of the serving, paired, approved, queue, to-send or sessions facts — through records.get and through its live device.facts, whatever state exists; an app that syncs keeps them.////// WHY: 22 Oct 2026, Rigby build 2's walk — a fresh Rigby (one device, no/// Mac) showed "Serving Mac: <this phone>", "Paired … Approved by the/// server" and two counts of a queue that will never be sent.#[test]fn an_app_that_never_syncs_shows_this_device_alone() {    let gone = crate::phone::device_here::SYNC_ONLY;    let (_dir, handle) = a_phone_on_its_own_with(Some(json!({"name": "Fixture", "sync": false})));    assert!(!handle.client().syncs());    let id = this_devices_row(&handle);    let record = ask(&handle, "records.get", json!({ "table": "device", "id": id })).expect("this device's record");    let facts = ask(&handle, "device.facts", json!({ "deviceId": id })).expect("this device's facts");    for data in [&record["data"], &facts["data"]] {        for column in gone {            assert_eq!(data[*column], Value::Null, "{column} is a sync fact: {data}");        }        assert!(data["ambient"].as_str().is_some_and(|said| said.starts_with("alone")), "{data}");    }    // The live overlay names every cleared column, so it clears what an    // earlier read drew.    let live: Vec<&str> = facts["live"].as_array().expect("live").iter().filter_map(Value::as_str).collect();    assert!(gone.iter().all(|column| live.contains(column)), "{live:?}");    let (_dir, syncing) = a_phone_on_its_own();    assert!(syncing.client().syncs());    let id = this_devices_row(&syncing);    let record = ask(&syncing, "records.get", json!({ "table": "device", "id": id })).expect("this device's record");    assert_ne!(record["data"]["approved_at"], Value::Null, "an app that syncs keeps its pairing: {record}");}/// RULE: This Device counts one queue once: its header's changes waiting and its To send fact are the same number, read from the one count (`current_pending`: the outbox and the writes held for the Mac's time).////// WHY: 22 Oct 2026, Rigby build 3's walk — "10 changes waiting to send" in/// the header against "20 changes to send" in the fact: the To send fact/// added the held writes again on top of a count that already holds them.#[test]fn this_device_counts_its_queue_once() {    let (_dir, handle) = a_phone_on_its_own();    let id = this_devices_row(&handle);    for title in ["Invented errand", "Invented call back", "Invented parcel"] {        ask(&handle, "records.create", json!({ "table": "todo", "data": { "title": title } })).expect("a todo");    }    let held = handle.client().with_file(|file| Ok(cotton_client::sync::cycle::current_held(file.driver))).expect("the file");    assert!(held.is_some_and(|n| n > 0), "a phone with no Mac holds its writes for the Mac's time: {held:?}");    let record = ask(&handle, "records.get", json!({ "table": "device", "id": id })).expect("this device's record");    let facts = ask(&handle, "device.facts", json!({ "deviceId": id })).expect("this device's facts");    // The header says the record's changes waiting; the To send fact is the    // live overlay's.    let waiting = record["data"]["changes_waiting"].as_u64();    assert!(waiting.is_some_and(|n| n > 0), "{record}");    assert_eq!(facts["data"]["receipts_to_send"].as_u64(), waiting, "one queue, one number: {facts}");    if let Some(also) = facts["data"].get("changes_waiting").filter(|n| !n.is_null()) {        assert_eq!(also.as_u64(), waiting, "{facts}");    }}/// RULE: Export's catalogue is part of the shell, including on a database/// with no object; every table it offers resolves through that same catalogue.#[test]fn a_phone_only_database_lists_its_tables_for_export() {    let (_dir, handle) = a_phone_on_its_own_with(Some(json!({"name": "Fixture", "sync": false})));    let definitions = ask(&handle, "definitions.tables", json!({})).expect("definitions");    assert!(definitions["definitions"].as_array().unwrap().iter().any(|d| d["id"] == "everything"));    let answer = ask(&handle, "records.list", json!({"table":"everything", "limit":200})).expect("export tables");    assert!(answer["records"].as_array().unwrap().iter().any(|row| row["id"] == "todo"));    let id = this_devices_row(&handle);    let acts = ask(&handle, "shell.opened", json!({"table":"device", "id":id})).expect("this device's acts");    let actions = acts["acts"].as_array().unwrap();    assert!(actions.iter().any(|act| act["label"] == "Add samples"), "{acts}");    assert!(actions.iter().any(|act| act["label"] == "Remove samples"), "{acts}");}/// RULE: Add samples installs each installed kit's carried examples and/// Remove samples bins exactly those examples, including plain kit tables.#[test]fn kit_samples_can_be_added_and_removed_on_a_phone_only_database() {    let (_dir, handle) = a_phone_on_its_own_with(Some(json!({"name":"Fixture", "sync":false})));    let device = this_devices_row(&handle);    let command = ask(&handle, "records.command", json!({"table":"device", "id":device, "command":"add_samples"})).expect("the device fan adds samples");    let added = command.get("answer").unwrap_or(&command);    assert!(added["kit_records"].as_u64().is_some_and(|n| n > 0), "{added}");    let books = ask(&handle, "records.list", json!({"table":"book"})).expect("books");    assert!(books["records"].as_array().is_some_and(|rows| !rows.is_empty()), "{books}");    let command = ask(&handle, "records.command", json!({"table":"device", "id":device, "command":"remove_samples"})).expect("the device fan removes samples");    let removed = command.get("answer").unwrap_or(&command);    assert_eq!(removed["removed"], added["added"]);    let books = ask(&handle, "records.list", json!({"table":"book"})).expect("books after removal");    assert_eq!(books["records"], json!([]));}/// RULE: On a Cotton copy standing on its own (it syncs, its database is the/// person's, nothing signed in yet) this device's row says `signed_out` and its/// acts are Sign in, Share ink and Erase alone.#[test]fn a_cotton_copy_on_its_own_offers_sign_in_share_ink_and_erase_alone() {    let read = |handle: &CottonHandle| -> (Value, Vec<String>, Value) {        let id = this_devices_row(handle);        let record = ask(handle, "records.get", json!({"table": "device", "id": id})).expect("this device's record");        let acts = ask(handle, "shell.opened", json!({"table": "device", "id": id})).expect("this device's acts");        let ids = acts["acts"].as_array().unwrap().iter().map(|act| act["id"].as_str().unwrap().to_string()).collect();        (record["data"]["session"].clone(), ids, record)    };    let (_dir, cotton) = a_phone_on_its_own();    let (session, acts, record) = read(&cotton);    assert_eq!(session, json!("signed_out"), "{record}");    assert_eq!(acts, ["sign_in", "share_ink", "erase_here"], "{acts:?}");}/// RULE: On an app that never syncs (Rigby) this device's row says `local`:/// no Sign in, no Sync now, and Add / Remove samples stand.#[test]fn a_copy_that_never_syncs_offers_no_sync_now() {    let (_dir, handle) = a_phone_on_its_own_with(Some(json!({"name":"Fixture", "sync":false})));    let id = this_devices_row(&handle);    let record = ask(&handle, "records.get", json!({"table": "device", "id": id})).expect("this device's record");    assert_eq!(record["data"]["session"], json!("local"), "{record}");    let acts = ask(&handle, "shell.opened", json!({"table": "device", "id": id})).expect("this device's acts");    let ids: Vec<&str> = acts["acts"].as_array().unwrap().iter().filter_map(|act| act["id"].as_str()).collect();    assert!(!ids.contains(&"sync_now") && !ids.contains(&"sign_in"), "{ids:?}");    assert!(ids.contains(&"add_samples") && ids.contains(&"remove_samples"), "{ids:?}");}/// The synthetic September statement (`fixtures/money/september_statement.json`)/// as a Cotton package, written at `path`.fn statement_package(path: &std::path::Path) {    use cotton_store::cottonpkg::{Manifest, Package, PackagedTable, FORMAT};    const SOURCE: &str = "synthetic-invented-bank";    let fixture: Value = serde_json::from_str(include_str!("../../fixtures/money/september_statement.json")).expect("the statement fixture");    let records: Vec<(String, Vec<serde_json::Map<String, Value>>)> = fixture["tables"]        .as_object()        .expect("its tables")        .iter()        .map(|(table, rows)| {            let rows = rows                .as_array()                .expect("a table's records")                .iter()                .map(|row| {                    let mut row = row.as_object().expect("a record").clone();                    row.insert("workspace_id".into(), json!(SOURCE));                    row                })                .collect();            (table.clone(), rows)        })        .collect();    let package = Package {        manifest: Manifest {            format: FORMAT,            schema_version: cotton_store::schema::ddl::SCHEMA_VERSION,            source_database: SOURCE.into(),            exported_at: "2026-10-01T09:00:00.000Z".into(),            tables: records.iter().map(|(table, rows)| PackagedTable { table: table.clone(), rows: rows.len() as u64 }).collect(),            media: Vec::new(),        },        records,        media: Default::default(),    };    std::fs::write(path, package.to_bytes().expect("the package's bytes")).expect("the package");}/// Writes the walk's package where `COTTON_WALK_PACKAGE` says.#[test]#[ignore = "writes the walk's synthetic statement package"]fn write_walk_package() {    let path = std::env::var("COTTON_WALK_PACKAGE").expect("COTTON_WALK_PACKAGE names the file to write");    statement_package(std::path::Path::new(&path));}