Cotton code
479 lines · 23.5 KB · RustRaw
//! THE HEADLESS DAYS WALK: invitations between two people on Cotton (CONTRACT.md//! §15, §17), driven straight through the C ABI the Android JNI wraps//! (`cotton_open` / `cotton_call`), against the DEV Worker, with no emulator.//! Each phone asks the core what Days' Android surface asks it.//!//! The flows (one line each, `FLOW <n> <name> PASS|FAIL (<ms>ms): <said>`)://!//! 1. sign-in — A and B sign in with invented numbers on the Days core.//! 2. connect — A writes to B in chat and B answers: each is the other's person//!    (`days.people_find` lists the other first, as on Cotton).//! 3. invite — A puts B on an event; `days.tell` says B gets it in Days; A's//!    `days.invitations` sends it sealed; B's lands it as B's own event, "A invited you".//! 4. answer — B says Coming; A's chip reads Coming.//! 5. change — A moves it to 20:00; B's copy moves and B is told.//! 6. call off — A takes B off; B's copy goes and B is told.//! 7. stranger — A puts C (never connected) on an event: nothing reaches C,//!    and C's number is told apart from nobody's (the route is `none`).//! 8. at size — A holds COTTON_WALK_SIZE events of their own (default 1500)//!    and invites B to 40 more; every invitation lands at B; the passes are timed.//!//! SKIPPED unless COTTON_WALK_SERVER (the dev Worker) and COTTON_WALK_CODE_FILE//! (the dev code's file: read, never printed) are set. The numbers are invented//! for each run (+1555018 and four digits); nothing real is touched.use std::ffi::{c_char, CStr, CString};use std::path::PathBuf;use std::time::{Duration, Instant};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use cotton_ffi::{cotton_call, cotton_close, cotton_open, cotton_string_free, CottonHandle};use serde_json::{json, Value};use sha2::{Digest, Sha256};const APP_VERSION: &str = "headless-days";const FLAVOUR: &str = "days";const ARRIVAL: Duration = Duration::from_secs(60);const ZONE: &str = "Asia/Kolkata";struct Walk {    server: String,    code: String,    run: String,    size: usize,}impl Walk {    fn from_env() -> Option<Walk> {        let var = |name: &str| std::env::var(name).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty());        let (server, file) = (var("COTTON_WALK_SERVER")?, var("COTTON_WALK_CODE_FILE")?);        let file = match file.strip_prefix("~/") {            Some(rest) => PathBuf::from(std::env::var("HOME").expect("HOME")).join(rest),            None => PathBuf::from(file),        };        let code = std::fs::read_to_string(&file).unwrap_or_else(|e| panic!("the dev code file {} could not be read: {e}", file.display())).trim().to_string();        let run = var("COTTON_WALK_RUN").unwrap_or_else(|| format!("{:03}", (std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() % 900) + 100));        let size = var("COTTON_WALK_SIZE").and_then(|s| s.parse().ok()).unwrap_or(1500);        Some(Walk { server, code, run, size })    }    /// An invented number for this run: +1 555 018 <run> <slot>.    fn number(&self, slot: u32) -> String {        format!("+1555018{}{slot}", self.run)    }}struct Phone {    handle: *mut CottonHandle,    _container: tempfile::TempDir,    number: String,    name: &'static str,    key: String,}impl Phone {    fn open(walk: &Walk, number: &str, name: &'static str) -> Result<Phone, String> {        let container = tempfile::tempdir().map_err(|e| format!("no tempdir: {e}"))?;        std::fs::create_dir_all(container.path().join("cotton")).map_err(|e| e.to_string())?;        let config = json!({            "containerPath": container.path().join("cotton").to_string_lossy(),            "appVersion": APP_VERSION,            "timeZone": ZONE,            "deviceSecret": URL_SAFE_NO_PAD.encode(Sha256::digest(format!("cotton headless days {number}").as_bytes())),            "flavor": "dev",            "manifest": manifest(&walk.server),        });        let text = CString::new(config.to_string()).expect("no NUL");        let mut error: *mut c_char = std::ptr::null_mut();        // SAFETY: a NUL-terminated config and a writable error slot, as the JNI hands them.        let handle = unsafe { cotton_open(text.as_ptr(), &mut error) };        if handle.is_null() {            return Err(format!("cotton_open refused: {}", take(error)));        }        Ok(Phone { handle, _container: container, number: number.to_string(), name, key: String::new() })    }    fn call(&self, method: &str, request: Value) -> Result<Value, String> {        let method_c = CString::new(method).expect("no NUL");        let request_c = CString::new(request.to_string()).expect("no NUL");        // SAFETY: a live handle and NUL-terminated strings; the answer is owned and freed by `take`.        let answer = take(unsafe { cotton_call(self.handle, method_c.as_ptr(), request_c.as_ptr()) });        let answer: Value = serde_json::from_str(&answer).map_err(|e| format!("{method}: the answer is not JSON ({e})"))?;        if answer["ok"] == json!(true) {            return Ok(answer["data"].clone());        }        let error = &answer["error"];        Err(format!("{} {method}: {} {}", self.name, error["code"].as_str().unwrap_or("?"), error["message"].as_str().unwrap_or("?")))    }    /// A `days.*` call with what Days' Clock adds to every ask.    fn days(&self, method: &str, mut request: Value) -> Result<Value, String> {        request["timezone"] = json!(ZONE);        request["today"] = json!(today());        request["language"] = json!("en");        self.call(method, request)    }    fn keyed(&self, method: &str, mut request: Value) -> Result<Value, String> {        request["privateKey"] = json!(self.key);        self.call(method, request)    }    fn sign_in(&mut self, walk: &Walk) -> Result<String, String> {        self.call("personal.standLocal", json!({ "signedOut": true }))?;        let challenge = self.call("personal.code", json!({ "server": walk.server, "phone": self.number }))?;        let mut ask = json!({ "server": walk.server, "challengeId": challenge["challengeId"], "code": walk.code });        if let Some(database) = challenge.get("databaseId").filter(|d| !d.is_null()) {            ask["databaseId"] = database.clone();        }        let answer = self.call("personal.signIn", ask)?;        let database = answer["databaseId"].as_str().or(challenge["databaseId"].as_str()).ok_or("personal.signIn named no database")?.to_string();        let credential = answer["credential"].as_str().ok_or("personal.signIn granted no credential")?;        self.call("personal.connect", json!({ "server": walk.server, "databaseId": database, "credential": credential, "deviceName": format!("headless days {}", self.name), "appVersion": APP_VERSION }))?;        // The first phone of a new database founds its vault and takes the data key, as SealedKeys.unlock does        // (the person's own unlock on Android): without it nothing sealed can be sent.        let vault = URL_SAFE_NO_PAD.encode(Sha256::digest(format!("cotton headless days vault {}", self.number).as_bytes()));        let _ = self.call("sync.now", json!({}));        let before = self.call("seal.status", json!({}))?;        let begun = Instant::now();        while self.call("seal.status", json!({}))?["keyHeld"] != json!(true) {            // Founding writes the vault's wrap; it opens once the object holds it, so a pass and the unlock again.            if let Err(e) = self.call("vault.unlock", json!({ "privateKey": vault, "name": format!("headless days {}", self.name) })) {                if !e.contains("vault_not_wrapped_yet") {                    return Err(format!("{e}; seal.status before {}", short(&before)));                }            }            let _ = self.call("sync.now", json!({}));            if begun.elapsed() > ARRIVAL {                return Err(format!("{}: no data key after the vault's unlock: {}", self.name, short(&self.call("seal.status", json!({}))?)));            }            std::thread::sleep(Duration::from_secs(2));        }        self.key = self.call("chat.key", json!({}))?["privateKey"].as_str().ok_or("chat.key minted no key")?.to_string();        self.keyed("chat.register", json!({ "ratchet": true }))?;        Ok(database)    }    /// One send-and-take pass, as Days runs it on coming to the front.    fn pass(&self) -> Result<Value, String> {        self.days("days.invitations", json!({}))    }    /// Passes until `until` holds of what was said, or ARRIVAL passes; answers every line said on the way.    fn wait_said(&self, what: &str, until: impl Fn(&[String]) -> bool) -> Result<Vec<String>, String> {        self.wait_said_for(what, ARRIVAL, until)    }    fn wait_said_for(&self, what: &str, arrival: Duration, until: impl Fn(&[String]) -> bool) -> Result<Vec<String>, String> {        let started = Instant::now();        let mut said = Vec::new();        loop {            let pass = self.pass()?;            said.extend(pass["said"].as_array().into_iter().flatten().filter_map(|s| s.as_str().map(str::to_string)));            if until(&said) {                return Ok(said);            }            if started.elapsed() > arrival {                return Err(format!("{}: {what} did not come in {}s (said {said:?})", self.name, arrival.as_secs()));            }            std::thread::sleep(Duration::from_secs(2));        }    }    /// The id of the event called `title` on `day`, as the list draws it.    fn event_on(&self, day: &str, title: &str) -> Result<Option<Value>, String> {        let span = self.days("days.span", json!({ "from": day, "to": day }))?;        Ok(find_row(&span, title))    }    fn sheet(&self, id: &str) -> Result<Value, String> {        self.days("days.item", json!({ "table": "event", "id": id }))    }}impl Drop for Phone {    fn drop(&mut self) {        // SAFETY: the pointer cotton_open answered, closed once.        unsafe { cotton_close(self.handle) };    }}/// The first row anywhere in an answer whose words are `title`.fn find_row(v: &Value, title: &str) -> Option<Value> {    match v {        Value::Object(map) => {            if map.get("words").and_then(Value::as_str) == Some(title) && (map.contains_key("id") || map.contains_key("opens")) {                return Some(v.clone());            }            map.values().find_map(|c| find_row(c, title))        }        Value::Array(items) => items.iter().find_map(|c| find_row(c, title)),        _ => None,    }}fn row_id(row: &Value) -> Option<String> {    row["id"].as_str().or(row["opens"]["id"].as_str()).map(str::to_string)}fn today() -> String {    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as i64 + 5 * 3600 + 1800;    day_of(now / 86_400)}/// The civil date of a day number (days since 1970-01-01).fn day_of(days: i64) -> String {    let z = days + 719_468;    let era = z.div_euclid(146_097);    let doe = z - era * 146_097;    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);    let mp = (5 * doy + 2) / 153;    let d = doy - (153 * mp + 2) / 5 + 1;    let m = if mp < 10 { mp + 3 } else { mp - 9 };    let y = yoe + era * 400 + i64::from(m <= 2);    format!("{y:04}-{m:02}-{d:02}")}fn days_ahead(n: i64) -> String {    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as i64 + 5 * 3600 + 1800;    day_of(now / 86_400 + n)}fn take(text: *mut c_char) -> String {    if text.is_null() {        return String::new();    }    // SAFETY: an owned string from the C ABI, freed once with its own free.    let owned = unsafe { CStr::from_ptr(text) }.to_string_lossy().into_owned();    unsafe { cotton_string_free(text) };    owned}fn manifest(server: &str) -> Value {    let path = cotton_store::manifest_dir().join("../../apps/cotton/App/Flavours").join(FLAVOUR).join("flavour.json");    let mut whole: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{} reads: {error}", path.display()))).expect("JSON");    if whole["business"]["server"].is_object() {        whole["business"]["server"] = json!(server);    }    whole}fn short(v: &Value) -> String {    let s = v.to_string();    if s.len() > 400 { format!("{}…", &s[..400]) } else { s }}struct Flows {    failed: Vec<String>,}impl Flows {    fn run(&mut self, n: u32, name: &str, flow: impl FnOnce() -> Result<String, String>) -> bool {        let started = Instant::now();        let outcome = flow();        let ms = started.elapsed().as_millis();        match &outcome {            Ok(said) => println!("FLOW {n} {name} PASS ({ms}ms): {said}"),            Err(said) => {                println!("FLOW {n} {name} FAIL ({ms}ms): {said}");                self.failed.push(format!("{n} {name}"));            }        }        outcome.is_ok()    }}fn ensure(ok: bool, said: impl FnOnce() -> String) -> Result<(), String> {    if ok { Ok(()) } else { Err(said()) }}#[test]fn days_invitations_walk_through_the_core_against_the_dev_worker() {    let Some(walk) = Walk::from_env() else {        eprintln!("SKIPPED: set COTTON_WALK_SERVER and COTTON_WALK_CODE_FILE to walk Days against the dev Worker");        return;    };    let mut flows = Flows { failed: Vec::new() };    let (na, nb, nc) = (walk.number(1), walk.number(2), walk.number(3));    println!("run {} numbers A {na} B {nb} C {nc} size {}", walk.run, walk.size);    let mut a = Phone::open(&walk, &na, "A").expect("A opens");    let mut b = Phone::open(&walk, &nb, "B").expect("B opens");    let day = days_ahead(3);    let signed = flows.run(1, "sign-in", || {        a.sign_in(&walk)?;        b.sign_in(&walk)?;        Ok("A and B signed in on the Days core".into())    });    assert!(signed, "nothing further can walk");    flows.run(2, "connect", || {        let started = a.call("chat.start", json!({ "number": nb }))?;        let ab = started["thread"].as_str().ok_or("no thread")?.to_string();        a.keyed("chat.send", json!({ "thread": ab, "body": "hello from A" }))?;        let begun = Instant::now();        let ba = loop {            b.keyed("chat.incoming", json!({}))?;            let list = b.call("chat.list", json!({}))?;            if let Some(t) = list["rows"].as_array().or(list["threads"].as_array()).into_iter().flatten().find(|r| r.to_string().contains(&na)) {                break t["thread"].as_str().or(t["id"].as_str()).unwrap_or_default().to_string();            }            ensure(begun.elapsed() < ARRIVAL, || "B never heard A".into())?;            std::thread::sleep(Duration::from_secs(2));        };        b.keyed("chat.send", json!({ "thread": ba, "body": "hi A" }))?;        std::thread::sleep(Duration::from_secs(3));        let found = a.days("days.people_find", json!({ "words": "" }))?;        let first = &found["rows"][0];        ensure(first["via"] == json!("cotton") && first.to_string().contains(&nb), || format!("A's people {}", short(&found)))?;        Ok(format!("B is A's person on Cotton: {}", short(first)))    });    let mut event = String::new();    flows.run(3, "invite", || {        let added = a.days("days.add", json!({ "words": "Invented dinner", "day": day, "time": "19:00", "where": "days" }))?;        event = added["id"].as_str().ok_or("no id")?.to_string();        let people = json!([{ "number": nb, "name": "Bea" }]);        let told = a.days("days.tell", json!({ "table": "event", "id": event, "people": people }))?;        ensure(told["lines"] == json!(["Bea gets it in Days."]), || format!("tell {}", short(&told)))?;        let changed = a.days("days.change", json!({ "table": "event", "id": event, "people": people }))?;        ensure(changed["google"] == json!("waiting"), || format!("change {}", short(&changed)))?;        let sent = a.pass()?;        ensure(sent["sent"] == json!(1), || format!("A's pass {}; A's sheet {}", short(&sent), short(&a.sheet(&event).map(|s| s["people"].clone()).unwrap_or_default())))?;        let said = b.wait_said("the invitation", |s| s.iter().any(|l| l.contains("invited you")))?;        let row = b.event_on(&day, "Invented dinner")?.ok_or("B's day has no dinner")?;        let sheet = b.sheet(&row_id(&row).ok_or("no id")?)?;        ensure(sheet["invitation"]["choices"].as_array().is_some_and(|c| c.len() == 3), || format!("B's sheet {}", short(&sheet)))?;        Ok(format!("B was told {said:?}; B's sheet says {}", sheet["says"]))    });    flows.run(4, "answer", || {        let row = b.event_on(&day, "Invented dinner")?.ok_or("B's day has no dinner")?;        let id = row_id(&row).ok_or("no id")?;        b.days("days.answer", json!({ "id": id, "answer": "accepted" }))?;        b.pass()?;        let said = a.wait_said("B's answer", |s| s.iter().any(|l| l.contains("coming")))?;        let chip = &a.sheet(&event)?["people"]["rows"][0];        ensure(chip["answerWords"] == json!("Coming"), || format!("A's chip {}", short(chip)))?;        Ok(format!("A was told {said:?}; the chip reads {}", chip["answerWords"]))    });    flows.run(5, "change", || {        a.days("days.change", json!({ "table": "event", "id": event, "time": "20:00" }))?;        a.pass()?;        let said = b.wait_said("the change", |s| s.iter().any(|l| l.contains("changed")))?;        let row = b.event_on(&day, "Invented dinner")?.ok_or("B's dinner went")?;        ensure(row.to_string().contains("20:00"), || format!("B's row {}", short(&row)))?;        Ok(format!("B was told {said:?}; B's dinner is at 20:00"))    });    flows.run(6, "call off", || {        let told = a.days("days.tell", json!({ "table": "event", "id": event, "people": [] }))?;        a.days("days.change", json!({ "table": "event", "id": event, "people": [] }))?;        a.pass()?;        let said = b.wait_said("the call-off", |s| s.iter().any(|l| l.contains("called off")))?;        ensure(b.event_on(&day, "Invented dinner")?.is_none(), || "B's dinner still stands".into())?;        Ok(format!("A was shown {}; B was told {said:?}", told["lines"]))    });    flows.run(7, "stranger", || {        let added = a.days("days.add", json!({ "words": "Invented lunch", "day": day, "time": "13:00", "where": "days" }))?;        let id = added["id"].as_str().ok_or("no id")?;        let told = a.days("days.tell", json!({ "table": "event", "id": id, "people": [{ "number": nc, "name": "Cal" }] }))?;        let mut c = Phone::open(&walk, &nc, "C")?;        c.sign_in(&walk)?;        a.days("days.change", json!({ "table": "event", "id": id, "people": [{ "number": nc, "name": "Cal" }] }))?;        let sent = a.pass()?;        std::thread::sleep(Duration::from_secs(5));        let took = c.pass()?;        ensure(took["said"].as_array().is_none_or(|s| s.is_empty()) && c.event_on(&day, "Invented lunch")?.is_none(), || format!("C took {}", short(&took)))?;        Ok(format!("A was shown {}; A's pass {}; C took nothing", told["lines"], short(&sent)))    });    flows.run(8, "at size", || {        let began = Instant::now();        for n in 0..walk.size {            let at = days_ahead((n % 360) as i64 - 180);            a.days("days.add", json!({ "words": format!("Invented block {n}"), "day": at, "time": format!("{:02}:00", 6 + n % 5), "where": "days" }))?;        }        let seeded = began.elapsed();        let mut ids = Vec::new();        for n in 0..40 {            let at = days_ahead(5 + n % 20);            let added = a.days("days.add", json!({ "words": format!("Invented supper {n}"), "day": at, "time": "20:00", "where": "days" }))?;            let id = added["id"].as_str().ok_or("no id")?.to_string();            a.days("days.change", json!({ "table": "event", "id": id, "people": [{ "number": nb, "name": "Bea" }] }))?;            ids.push(id);        }        let started = Instant::now();        let mut sent = 0;        for _ in 0..10 {            let pass = a.pass()?;            let n = pass["sent"].as_u64().unwrap_or(0);            sent += n;            if n == 0 {                break;            }        }        let send_ms = started.elapsed().as_millis();        ensure(sent == 40, || format!("A sent {sent} of 40"))?;        let started = Instant::now();        let said = b.wait_said("40 invitations", |s| s.iter().filter(|l| l.contains("invited you")).count() >= 40)?;        let take_ms = started.elapsed().as_millis();        let span = a.days("days.span", json!({ "from": days_ahead(-30), "to": days_ahead(30) }))?;        let span_ms = {            let t = Instant::now();            a.days("days.span", json!({ "from": days_ahead(-30), "to": days_ahead(30) }))?;            t.elapsed().as_millis()        };        Ok(format!(            "A holds {} events (seeded in {}s); 40 invitations sent in {send_ms}ms, all {} landed at B in {take_ms}ms; a two-month span reads in {span_ms}ms ({} bytes)",            walk.size + 42,            seeded.as_secs(),            said.iter().filter(|l| l.contains("invited you")).count(),            span.to_string().len()        ))    });    assert!(flows.failed.is_empty(), "flows failed: {:?}", flows.failed);}/// THE PARTNER FOR A HAND WALK: an invented phone that asks COTTON_WALK_PARTNER (the emulator's invented number) to/// be one of its people, waits until the emulator accepts in Settings › Your people, invites it to "Invented/// supper" three days ahead at 19:00, waits for its answer, moves the supper to 20:00, and after a minute takes it/// off the list. Each step prints `PARTNER <step>`; the hand walk follows on the emulator. SKIPPED without the variables.#[test]fn partner_for_a_hand_walk_on_the_emulator() {    let (Some(walk), Some(guest)) = (Walk::from_env(), std::env::var("COTTON_WALK_PARTNER").ok().filter(|v| !v.is_empty())) else {        eprintln!("SKIPPED: set COTTON_WALK_SERVER, COTTON_WALK_CODE_FILE and COTTON_WALK_PARTNER");        return;    };    let wait = Duration::from_secs(900);    let mut b = Phone::open(&walk, &walk.number(9), "Partner").expect("opens");    b.sign_in(&walk).expect("signs in");    let _ = b.call("people.add", json!({ "number": guest, "name": "Walk partner" })).map_err(|e| println!("PARTNER add said {e}"));    println!("PARTNER asked {guest} from {} — accept it on the emulator (Settings › Your people)", b.number);    let begun = Instant::now();    loop {        let found = b.days("days.people_find", json!({ "words": "" })).expect("people");        if found["rows"].as_array().into_iter().flatten().any(|r| r["via"] == json!("cotton") && r.to_string().contains(&guest)) {            break;        }        assert!(begun.elapsed() < wait, "the emulator never accepted");        std::thread::sleep(Duration::from_secs(5));    }    println!("PARTNER connected");    let day = days_ahead(3);    let id = b.days("days.add", json!({ "words": "Invented supper", "day": day, "time": "19:00", "where": "days" })).expect("add")["id"].as_str().unwrap().to_string();    b.days("days.change", json!({ "table": "event", "id": id, "people": [{ "number": guest, "name": "Walk guest" }] })).expect("people");    println!("PARTNER invited: {}", short(&b.pass().expect("pass")));    let said = b.wait_said_for("the guest's answer", wait, |s| s.iter().any(|l| l.contains("is coming") || l.contains("may come") || l.contains("is not coming"))).expect("an answer");    println!("PARTNER heard {said:?}");    b.days("days.change", json!({ "table": "event", "id": id, "time": "20:00" })).expect("moved");    println!("PARTNER moved it to 20:00: {}", short(&b.pass().expect("pass")));    std::thread::sleep(Duration::from_secs(90));    b.days("days.change", json!({ "table": "event", "id": id, "people": [] })).expect("off");    println!("PARTNER took the guest off: {}", short(&b.pass().expect("pass")));}