Cotton code
108 lines · 5.8 KB · RustRaw
//! `developer.inventServedCopy` — COTTON DEV ONLY: invented messages written//! into this phone's own copy exactly as a pull lands the object's rows//! (`ObjectTransport::served_ops`, then `fold::fold_pulled`), then, with//! `whole`, every receipt of the object's made whole again and the trim's//! place forgotten: the copy as a build before schema 151 left it. A hand walk//! can then watch an update trim a large copy in place (coordinator, 21 Nov//! 2026: "prove on an emulator by hand that the app stays usable during the//! trim, typing, opening, sending, on the 200k copy") with no account that//! large on dev. Nothing is sent: the rows are the copy's alone, in their own//! invented conversations. The real Cotton refuses it by name.//!//! ```text//! developer.inventServedCopy { from?, count?, whole? } → { folded, wholeAgain, held }//! ```//!//! `from` (default 0) and `count` (default 2,000, at most 5,000) name the//! invented messages this call lands, so a walk lands 200,000 in a hundred//! calls, each its own short write. `whole: true` alone (no count) makes 2,000//! implied receipts whole a call; `wholeAgain` 0 says it is done.use std::sync::Arc;use serde_json::{json, Value};use crate::handle::CottonHandle;use crate::methods::MethodError;/// The invented conversations the messages are spread over.const THREADS: usize = 30;pub fn invent(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    if handle.flavor() != cotton_core::flavor::Flavor::Dev {        return Err(MethodError::new("not_dev", "developer.inventServedCopy answers only in Cotton Dev"));    }    let client = handle.client();    let database = client.current_database().map_err(|why| MethodError::new("no_database", why))?;    let door = client.object_door().ok_or_else(|| MethodError::new("sign_in_first", "a served copy is a signed-in phone's"))?;    let path = client.layout().replica(&database);    let from = request["from"].as_u64().unwrap_or(0) as usize;    let count = request["count"].as_u64().map_or(if request["whole"] == json!(true) { 0 } else { 2_000 }, |n| n.min(5_000) as usize);    let failed = |why: String| MethodError::new("invent_failed", why);    let mut folded = 0usize;    if count > 0 {        let transport = cotton_client::transport::object::ObjectTransport::new(            door.address.clone(),            Arc::clone(&door.exchange),            door.credential.clone(),            cotton_client::transport::object::ObjectTables::personal(),            path,            Vec::new(),        );        let at = "2026-10-20T09:00:00.000Z";        let words = "Running a little late, will be there by seven; keep a seat for me please";        let mut rows: Vec<Value> = Vec::new();        if from == 0 {            rows.extend((0..THREADS).map(|t| json!({"table": "thread", "id": format!("dev-thread-{t:02}"), "version": 5, "owner": null, "data": {"channel": "whatsapp", "title": format!("Invented chat {t}")}, "created_at": at, "updated_at": at})));        }        rows.extend((from..from + count).map(|i| {            json!({                "table": "message", "id": format!("dev-message-{i:08}"), "version": 10 + i as i64, "owner": null,                "data": {"thread_id": format!("dev-thread-{:02}", i % THREADS), "channel": "whatsapp", "sent_at": at,                         "external_id": format!("dev-{i:012}"), "origin": "imported", "sender_name": "Invented Friend",                         "body": &words[..(20 + i % 50)], "direction": if i % 2 == 0 { "in" } else { "out" }, "media": []},                "created_at": at, "updated_at": at,            })        }));        let ops = transport.served_ops(&rows, &database).map_err(failed)?;        folded = ops.len();        client.with_writer(|file| cotton_store::fold::fold_pulled(&file.driver, &ops).map(|_| ()).map_err(|error| error.to_string())).map_err(failed)?;    }    let mut whole_again = 0usize;    if request["whole"] == json!(true) {        whole_again = client            .with_writer(|file| {                let db = &file.driver;                let rows: Vec<(String, String)> = db                    .all("SELECT DISTINCT tbl, row_id FROM _writes WHERE implied IS NOT NULL LIMIT 2000", &[])                    .map_err(|e| e.to_string())?                    .iter()                    .filter_map(|row| Some((row.text("tbl")?.to_string(), row.text("row_id")?.to_string())))                    .collect();                db.transaction(|db| {                    for (table, id) in &rows {                        cotton_store::receipts::implied::materialize_row(db, table, id)?;                    }                    db.exec("DELETE FROM _trim")                })                .map_err(|e| e.to_string())?;                Ok(rows.len())            })            .map_err(failed)?;    }    let held = client        .with_file(|file| Ok(file.driver.get("SELECT COUNT(*) AS n FROM _writes WHERE row_id LIKE 'dev-message-%'", &[]).map_err(|e| e.to_string())?.and_then(|row| row.int("n")).unwrap_or(0)))        .map_err(failed)?;    Ok(json!({ "folded": folded, "wholeAgain": whole_again, "held": held }))}/// `developer.cutNetwork { on }` (Cotton Dev only): every dial fails as with no network while `on`, and works again/// once it is lifted — a simulator's airplane mode, for walking what the app says offline (sync seen, 26 Nov 2026).pub fn cut_network(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    if handle.flavor() != cotton_core::flavor::Flavor::Dev {        return Err(MethodError::new("not_dev", "developer.cutNetwork answers only in Cotton Dev"));    }    let on = request["on"].as_bool().ok_or_else(|| MethodError::new("bad_request", "on is true or false"))?;    cotton_client::transport::wire::CUT.store(on, std::sync::atomic::Ordering::SeqCst);    Ok(json!({ "cut": on }))}