Cotton code
301 lines · 14.2 KB · RustRaw
//! THE HEADLESS CORE WALK (`pnpm android:core-walk`): the flows the Android//! app runs, driven straight through the C ABI the app's JNI wraps//! (`cotton_open` / `cotton_call` / `cotton_close`, as//! `crates/cotton-android-jni/src/native.rs` calls them), against the DEV//! Worker, with no emulator and no screen. Each flow asks the core what the//! Kotlin shell asks it, in the same order://!//! 1. sign-in — `personal.standLocal {signedOut}` at launch, then the SignIn//!    form's `personal.code` and `personal.signIn`, then `personal.connect`//!    (`shell/core/Session.kt`); the Account card answers connected.//! 2. sync — `sync.now`, then the Account card (`shell.account`): last sync//!    finished, no error.//! 3. send — a second phone signs in, each adds the other (`people.add`), a//!    book is made and synced up, `send.make` sends it (`shell/Send.kt`), the//!    sender's `send.inbox` lists it out and the receiver's lists it in.//! 4. sign-out — `personal.standLocal {signedOut: true}` (`Session.signOut`);//!    the Account card answers signed out.//!//! SKIPPED unless COTTON_WALK_SERVER (the dev Worker), COTTON_WALK_PHONE and//! COTTON_WALK_CODE_FILE (the dev code's file: read, never printed) are set;//! COTTON_WALK_PHONE_B is the receiving phone (Send says so and fails without//! it). Each phone's container is a tempdir. Prints one line per flow://! `FLOW <n> <name> PASS|FAIL (<ms>ms): <what the core answered>`.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_core::rules::shell_lines::resolve;use cotton_ffi::{cotton_call, cotton_close, cotton_open, cotton_string_free, CottonHandle};use serde_json::{json, Value};use sha2::{Digest, Sha256};/// What the Android build says it is (`Flavour.appVersion`'s shape).const APP_VERSION: &str = "headless-walk";/// The flavour the walk opens as: Books, whose shell carries Send.const FLAVOUR: &str = "books";/// How long the receiver waits for a send to reach its inbox.const ARRIVAL: Duration = Duration::from_secs(60);struct Walk {    server: String,    code: String,    phone: String,    phone_b: Option<String>,}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, phone, file) = (var("COTTON_WALK_SERVER")?, var("COTTON_WALK_PHONE")?, 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();        assert!(!code.is_empty(), "the dev code file {} is empty", file.display());        Some(Walk { server, code, phone, phone_b: var("COTTON_WALK_PHONE_B") })    }}/// A refusal as the boundary answers one: its code and sentence.#[derive(Debug)]struct Refused(String);impl std::fmt::Display for Refused {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str(&self.0)    }}/// One phone: a core opened over its own container, as the app opens it.struct Phone {    handle: *mut CottonHandle,    _container: tempfile::TempDir,    number: String,}impl Phone {    fn open(walk: &Walk, number: &str) -> Result<Phone, Refused> {        let container = tempfile::tempdir().map_err(|e| Refused(format!("no tempdir: {e}")))?;        let config = json!({            "containerPath": container.path().join("cotton").to_string_lossy(),            "appVersion": APP_VERSION,            "timeZone": "Asia/Kolkata",            "deviceSecret": device_secret(number),            "flavor": "dev",            "manifest": manifest(&walk.server),        });        std::fs::create_dir_all(container.path().join("cotton")).map_err(|e| Refused(e.to_string()))?;        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(Refused(format!("cotton_open refused: {}", take(error))));        }        Ok(Phone { handle, _container: container, number: number.to_string() })    }    fn call(&self, method: &str, request: Value) -> Result<Value, Refused> {        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| Refused(format!("{method}: the answer is not JSON ({e})")))?;        if answer["ok"] == json!(true) {            return Ok(answer["data"].clone());        }        let error = &answer["error"];        Err(Refused(format!("{method}: {} {}", error["code"].as_str().unwrap_or("?"), error["message"].as_str().unwrap_or("?"))))    }    /// The SignIn form through the core, then the connect `Session.signIn` makes.    fn sign_in(&self, walk: &Walk) -> Result<String, Refused> {        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_else(|| Refused("personal.signIn named no database".into()))?.to_string();        let credential = answer["credential"].as_str().ok_or_else(|| Refused("personal.signIn granted no credential".into()))?;        self.call("personal.connect", json!({ "server": walk.server, "databaseId": database, "credential": credential, "deviceName": "headless walk", "appVersion": APP_VERSION }))?;        Ok(database)    }    fn account(&self) -> Result<Value, Refused> {        self.call("shell.account", json!({}))    }}impl Drop for Phone {    fn drop(&mut self) {        // SAFETY: the pointer cotton_open answered, closed once.        unsafe { cotton_close(self.handle) };    }}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}/// The same device seed for the same number on every run, so a walk files one/// device in each object rather than a new one each push.fn device_secret(number: &str) -> String {    URL_SAFE_NO_PAD.encode(Sha256::digest(format!("cotton headless walk device {number}").as_bytes()))}/// The flavour's flavour.json as the Android shell sends it (`OpenConfig.manifest`):/// every key kept, `business.server`'s `{real, dev}` collapsed to the walk's server.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}/// The Account card's fact under a label, by the kit's own label words.fn fact(account: &Value, label: &str) -> String {    let words = resolve("boot", &format!("account.labels.{label}"), &[], &[]).unwrap_or_default();    account["card"]["facts"].as_array().into_iter().flatten().find(|f| f["label"] == json!(words)).and_then(|f| f["said"].as_str()).unwrap_or_default().to_string()}fn line(set: &str, key: &str) -> String {    resolve(set, key, &[], &[]).unwrap_or_else(|| panic!("the kit says {set}/{key}"))}/// The Account card's stand and glance, short.fn said_of(account: &Value) -> String {    format!("stand {}, \"{}\"", account["stand"].as_str().unwrap_or("?"), account["line"].as_str().unwrap_or("?"))}fn short(id: &str) -> String {    id.chars().take(8).collect()}struct Flow {    failed: bool,}impl Flow {    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();        let (verdict, said) = match &outcome {            Ok(said) => ("PASS", said.clone()),            Err(said) => ("FAIL", said.clone()),        };        println!("FLOW {n} {name} {verdict} ({ms}ms): {said}");        self.failed |= outcome.is_err();        outcome.is_ok()    }}fn r<T>(result: Result<T, Refused>) -> Result<T, String> {    result.map_err(|refused| refused.0)}#[test]fn the_android_flows_walk_through_the_core_against_the_dev_worker() {    let Some(walk) = Walk::from_env() else {        eprintln!("headless walk skipped: COTTON_WALK_SERVER, COTTON_WALK_PHONE and COTTON_WALK_CODE_FILE are not all set");        return;    };    let whole = Instant::now();    let mut flows = Flow { failed: false };    let a = Phone::open(&walk, &walk.phone).unwrap_or_else(|e| panic!("phone a: {e}"));    // 1. Sign-in.    let signed_in = flows.run(1, "sign-in", || {        let database = r(a.sign_in(&walk))?;        let account = r(a.account())?;        let said = format!("database {}, {}", short(&database), said_of(&account));        if account["stand"] == json!("connected") { Ok(said) } else { Err(said) }    });    // 2. Sync.    flows.run(2, "sync", || {        if !signed_in {            return Err("not signed in".into());        }        let pass = r(a.call("sync.now", json!({})))?;        let account = r(a.account())?;        let (synced, error) = (fact(&account, "synced"), fact(&account, "error"));        let finished = resolve("boot", "account.synced.finished", &[], &[("time", "")]).unwrap_or_default();        let said = format!("{}, last sync \"{synced}\", last error \"{error}\", behind {}", said_of(&account), pass.get("behind").unwrap_or(&json!(false)));        let ok = account["stand"] == json!("connected") && !finished.is_empty() && synced.ends_with(&finished) && error == line("boot", "account.error.none");        if ok { Ok(said) } else { Err(said) }    });    // 3. Send.    flows.run(3, "send", || {        if !signed_in {            return Err("not signed in".into());        }        let number_b = walk.phone_b.clone().ok_or("COTTON_WALK_PHONE_B is not set: there is no one to send to")?;        let b = r(Phone::open(&walk, &number_b))?;        r(b.sign_in(&walk)).map_err(|e| format!("phone b signing in: {e}"))?;        // Each adds the other: Your people's one relationship.        r(a.call("people.add", json!({ "number": b.number })))?;        r(b.call("people.add", json!({ "number": a.number })))?;        // A book of a's, up on a's object, as a picked file would be.        let title = format!("Headless walk {}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs());        let made = r(a.call("records.create", json!({ "table": "book", "data": { "title": title, "author": "A. Synthetic" } })))?;        let book = ["/record/id", "/id", "/after/id", "/change/after/id"].iter().find_map(|p| made.pointer(p).and_then(Value::as_str)).ok_or_else(|| format!("records.create named no id: {made}"))?.to_string();        r(a.call("sync.now", json!({})))?;        // The send, as Send.make asks it for a person's row.        let sent = r(a.call("send.make", json!({ "table": "book", "id": book, "to": b.number })))?;        let send = sent["id"].as_str().ok_or_else(|| format!("send.make named no send: {sent}"))?.to_string();        let lists = |inbox: &Value, side: &str| inbox[side].as_array().into_iter().flatten().any(|item| item["id"] == json!(send));        let out = r(a.call("send.inbox", json!({})))?;        if !lists(&out, "out") {            return Err(format!("send {} made (\"{}\") but a's inbox does not list it out", short(&send), sent["receipt"]["words"].as_str().unwrap_or("")));        }        let waited = Instant::now();        loop {            let inbox = r(b.call("send.inbox", json!({})))?;            if lists(&inbox, "in") {                let item = inbox["in"].as_array().into_iter().flatten().find(|item| item["id"] == json!(send)).cloned().unwrap_or_default();                let receipt = sent["receipt"]["words"].as_str().unwrap_or("");                let _ = r(b.call("personal.standLocal", json!({ "signedOut": true })));                return Ok(format!(                    "\"{title}\" sent {} (\"{receipt}\"), a lists it out, b lists it in ({}, {}ms)",                    short(&send),                    item["state"].as_str().unwrap_or("?"),                    waited.elapsed().as_millis()                ));            }            if waited.elapsed() > ARRIVAL {                return Err(format!("send {} out on a, not in b's inbox after {}s", short(&send), ARRIVAL.as_secs()));            }            std::thread::sleep(Duration::from_secs(2));        }    });    // 4. Sign-out.    flows.run(4, "sign-out", || {        r(a.call("personal.standLocal", json!({ "signedOut": true })))?;        let account = r(a.account())?;        let said = said_of(&account);        let ok = account["stand"] != json!("connected") && account["line"] == json!(line("boot", "account.tile.signed_out"));        if ok { Ok(said) } else { Err(said) }    });    drop(a);    println!("WALK {} ({}ms)", if flows.failed { "FAIL" } else { "PASS" }, whole.elapsed().as_millis());    assert!(!flows.failed, "a flow of the headless walk failed (its FLOW line says which)");}