Cotton code
240 lines · 12.8 KB · RustRaw
//! FIRST SYNC FAST, MEASURED ON DEV (coordinator, 26 Nov 2026: the owner's Post pulled 280,062 rows and showed 14,425//! after 80 minutes). A new phone (the shared core through its C ABI, opened as an app's flavour, as the phones open//! it) signs in on an invented dev account and syncs from nothing, timed://!//! - `front`: `sync.now` pass after pass, as an app in front does.//! - `back`: `sync.now { budgetMs }` slices (COTTON_SPEED_SLICE_MS, default 30000), as iOS's background refresh does.//!//! Each pass prints one `FIRST SYNC SPEED` line: seconds, rows this copy holds (its writes) and parks, rows a second.//! With COTTON_SYNC_TIMES=1 the core prints each page's timings (`[sync-times]`: rows, bytes, the ask, the unseal, the//! ops, the fold). With COTTON_SPEED_CODE_FILE (the account's recovery code) the key is opened after//! COTTON_SPEED_BEFORE passes (default: all of them) and the passes after it are timed the same way.//!//! SKIPPED unless COTTON_WALK_SERVER (the dev Worker), COTTON_WALK_CODE_FILE (the dev sign-in code's file, read and//! never printed) and COTTON_SPEED_NUMBER (an invented number) are set. COTTON_SPEED_FLAVOUR picks the app (default//! `mail`, Post); COTTON_SPEED_MODE `front` or `back`; COTTON_SPEED_MINUTES the most it runs (default 30). Never point//! it at the live server.use std::collections::BTreeMap;use std::ffi::{c_char, CStr, CString};use std::path::PathBuf;use std::time::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-first-sync-speed";fn var(name: &str) -> Option<String> {    std::env::var(name).ok().filter(|v| !v.trim().is_empty())}fn home(path: &str) -> PathBuf {    match path.strip_prefix("~/") {        Some(rest) => PathBuf::from(std::env::var("HOME").expect("HOME")).join(rest),        None => PathBuf::from(path),    }}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}struct Phone {    handle: *mut CottonHandle,    _container: tempfile::TempDir,    private_key: String,}impl Phone {    fn open(server: &str, number: &str, flavour: &str) -> Phone {        let container = tempfile::tempdir().expect("a tempdir");        std::fs::create_dir_all(container.path().join("cotton")).expect("the container");        let seed = format!("cotton first sync {number} {:?}", std::time::SystemTime::now());        let path = cotton_store::manifest_dir().join(format!("../../apps/cotton/App/Flavours/{flavour}/flavour.json"));        let mut manifest: Value = serde_json::from_str(&std::fs::read_to_string(&path).expect("the flavour's manifest")).expect("JSON");        manifest["business"]["server"] = json!(server);        let config = json!({            "containerPath": container.path().join("cotton").to_string_lossy(),            "appVersion": APP_VERSION,            "timeZone": "Asia/Kolkata",            "deviceSecret": URL_SAFE_NO_PAD.encode(Sha256::digest(seed.as_bytes())),            "flavor": "dev",            "manifest": manifest,        });        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) };        assert!(!handle.is_null(), "cotton_open refused {flavour}: {}", take(error));        let private_key = URL_SAFE_NO_PAD.encode(Sha256::digest(format!("vault {seed}").as_bytes()));        Phone { handle, _container: container, private_key }    }    fn call(&self, method: &str, request: Value) -> Result<Value, (String, 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).unwrap_or_else(|e| panic!("{method}: the answer is not JSON ({e})"));        if answer["ok"] == json!(true) {            return Ok(answer["data"].clone());        }        let error = &answer["error"];        Err((error["code"].as_str().unwrap_or("?").to_string(), error["message"].as_str().unwrap_or("?").to_string()))    }    fn must(&self, method: &str, request: Value) -> Value {        self.call(method, request).unwrap_or_else(|(code, message)| panic!("{method}: {code} {message}"))    }    fn sign_in(&self, server: &str, number: &str, code: &str) -> Value {        self.must("personal.standLocal", json!({ "signedOut": true }));        let challenge = self.must("personal.code", json!({ "server": server, "phone": number }));        let mut ask = json!({ "server": server, "challengeId": challenge["challengeId"], "code": code });        if let Some(database) = challenge.get("databaseId").filter(|d| !d.is_null()) {            ask["databaseId"] = database.clone();        }        let answer = self.must("personal.signIn", ask);        let database = answer["databaseId"].as_str().or(challenge["databaseId"].as_str()).expect("a database").to_string();        let credential = answer["credential"].as_str().expect("a credential").to_string();        let connect = json!({ "server": server, "databaseId": database, "credential": credential, "deviceName": "first sync speed", "appVersion": APP_VERSION, "unmetered": true });        self.must("personal.connect", connect.clone());        connect    }    /// What is parked now, by table and code, and whether the key is held.    fn parked(&self) -> (bool, usize, BTreeMap<String, usize>) {        let status = self.must("seal.status", json!({}));        let mut by: BTreeMap<String, usize> = BTreeMap::new();        let rows = status["parked"].as_array().cloned().unwrap_or_default();        for row in &rows {            *by.entry(format!("{} {}", row["table"].as_str().unwrap_or("?"), row["code"].as_str().unwrap_or("?"))).or_default() += 1;        }        (status["keyHeld"] == json!(true), rows.len(), by)    }    /// One `sync.now`, timed, with what it said.    fn pass(&self, step: &str, n: usize) -> bool {        let began = Instant::now();        let said = self.call("sync.now", json!({}));        let (held, parked, by) = self.parked();        let behind = said.as_ref().is_ok_and(|s| s["behind"] == json!(true));        let what = match &said {            Ok(s) => format!("behind {behind}, pulled {}", s.get("pulled").or(s.get("applied")).cloned().unwrap_or(Value::Null)),            Err((code, message)) => format!("refused {code}: {message}"),        };        println!("FIRST SYNC {step} pass {n}: {:.1}s, {what}; key held {held}, parked {parked} {by:?}", began.elapsed().as_secs_f64());        behind || said.is_err()    }}impl Drop for Phone {    fn drop(&mut self) {        // SAFETY: the pointer cotton_open answered, closed once.        unsafe { cotton_close(self.handle) };    }}/// The rows this phone's copy holds (its writes) and parks, read off the copy's files in its container.fn counted(dir: &std::path::Path) -> (i64, i64) {    let mut found = (0, 0);    let mut stack = vec![dir.to_path_buf()];    while let Some(at) = stack.pop() {        let Ok(entries) = std::fs::read_dir(&at) else { continue };        for entry in entries.flatten() {            let path = entry.path();            if path.is_dir() {                stack.push(path);                continue;            }            let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();            if name.ends_with("-wal") || name.ends_with("-shm") || name.ends_with("-journal") {                continue;            }            let Ok(db) = rusqlite::Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) else { continue };            let writes: i64 = db.query_row("SELECT COALESCE(MAX(rowid), 0) FROM _writes", [], |r| r.get(0)).unwrap_or(0);            let parked: i64 = db.query_row("SELECT COUNT(*) FROM _seal_parked", [], |r| r.get(0)).unwrap_or(0);            if writes + parked > found.0 + found.1 {                found = (writes, parked);                if parked > 0 && var("COTTON_SPEED_CODES").is_some() {                    let mut by = db.prepare("SELECT tbl || ' ' || code || ' ' || substr(reason, 1, 90), COUNT(*) FROM _seal_parked GROUP BY 1 ORDER BY 2 DESC LIMIT 6").expect("by code");                    let codes: Vec<(String, i64)> = by.query_map([], |r| Ok((r.get(0)?, r.get(1)?))).expect("codes").flatten().collect();                    println!("FIRST SYNC SPEED parked by code: {codes:?}");                }            }        }    }    found}#[test]fn a_new_phones_first_sync_timed() {    let (Some(server), Some(number)) = (var("COTTON_WALK_SERVER"), var("COTTON_SPEED_NUMBER")) else {        eprintln!("SKIPPED: no COTTON_WALK_SERVER and COTTON_SPEED_NUMBER");        return;    };    assert!(server.contains("-dev") || server.contains("localhost") || server.contains("127.0.0.1"), "measured on the dev server only, not {server}");    let otp = var("COTTON_WALK_CODE").or_else(|| var("COTTON_WALK_CODE_FILE").map(|f| std::fs::read_to_string(home(&f)).expect("the dev code file"))).expect("the dev sign-in code").trim().to_string();    let flavour = var("COTTON_SPEED_FLAVOUR").unwrap_or_else(|| "mail".into());    let mode = var("COTTON_SPEED_MODE").unwrap_or_else(|| "front".into());    let slice: u64 = var("COTTON_SPEED_SLICE_MS").and_then(|n| n.parse().ok()).unwrap_or(30_000);    let minutes: f64 = var("COTTON_SPEED_MINUTES").and_then(|n| n.parse().ok()).unwrap_or(30.0);    let code = var("COTTON_SPEED_CODE_FILE").map(|f| std::fs::read_to_string(home(&f)).expect("the recovery code file").trim().to_string());    let before: usize = var("COTTON_SPEED_BEFORE").and_then(|n| n.parse().ok()).unwrap_or(usize::MAX);    let phone = Phone::open(&server, &number, &flavour);    let began = Instant::now();    phone.sign_in(&server, &number, &otp);    println!("FIRST SYNC SPEED {flavour} {mode}: signed in and connected in {:.1}s", began.elapsed().as_secs_f64());    let dir = phone._container.path().to_path_buf();    let (mut keyed, mut n, mut last) = (code.is_none(), 0usize, (0i64, 0i64));    let mut last_at = Instant::now();    while began.elapsed().as_secs_f64() < minutes * 60.0 {        n += 1;        if !keyed && n > before {            let opening = Instant::now();            let opened = phone.call("recovery.open", json!({ "code": code.as_deref().unwrap_or_default(), "privateKey": phone.private_key, "name": "first sync speed" }));            println!("FIRST SYNC SPEED recovery.open {:.1}s: {:?}", opening.elapsed().as_secs_f64(), opened.as_ref().map(|_| "opened").map_err(|e| e.clone()));            keyed = true;        }        let passing = Instant::now();        let ask = if mode == "back" { json!({ "budgetMs": slice }) } else { json!({}) };        let said = phone.call("sync.now", ask);        let (writes, parked) = counted(&dir);        let secs = last_at.elapsed().as_secs_f64();        let gained = (writes + parked) - (last.0 + last.1);        println!(            "FIRST SYNC SPEED pass {n}{}: {:.1}s, holds {writes} written + {parked} parked (+{gained}, {:.0} rows/s), at {:.0}s; {}",            if keyed && code.is_some() { " (keyed)" } else { "" },            passing.elapsed().as_secs_f64(),            gained as f64 / secs.max(0.001),            began.elapsed().as_secs_f64(),            match &said { Ok(s) => format!("behind {}", s["behind"]), Err((c, m)) => format!("refused {c}: {}", m.chars().take(120).collect::<String>()) }        );        (last, last_at) = ((writes, parked), Instant::now());        let behind = said.as_ref().is_ok_and(|s| s["behind"] == json!(true));        if !behind && said.is_ok() && (keyed || n >= before) {            if code.is_none() || keyed {                // A last pass: a kit's late tables come in the pass after the first fill.                let again = phone.call("sync.now", json!({}));                let (w, p) = counted(&dir);                if (w + p) == (last.0 + last.1) && again.as_ref().is_ok_and(|s| s["behind"] != json!(true)) {                    break;                }                last = (w, p);            }        }    }    let (writes, parked) = counted(&dir);    println!("FIRST SYNC SPEED done in {:.1}s: {writes} written + {parked} parked, {:.0} rows/s overall", began.elapsed().as_secs_f64(), (writes + parked) as f64 / began.elapsed().as_secs_f64());}