Cotton code
394 lines · 17.6 KB · RustRaw
//! The app as the popover drives it: start with a token, a source's thread//! runs it, run-now and pause act, a 401 signs the app out.mod support;use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::Arc;use std::time::{Duration, Instant};use cotton_client::ingest::{DeviceCall, IngestBatch, IngestWork};use cotton_mac::app::{App, Config};use cotton_mac::vault::NoKeyring;use cotton_mac::importer::{Importer, Need, Probe, RunContext, RunError, Schedule, SourceKey};use serde_json::{json, Value};use support::{fixture, Answer, TestServer};const DB: &str = "00000000-0000-4000-8000-000000000001";/// Sends the fixture's calls once per run, cursor `run:<n>`.struct FakeCalls {    runs: Arc<AtomicUsize>,    ready: bool,}impl Importer for FakeCalls {    fn key(&self) -> SourceKey {        SourceKey::Calls    }    fn schedule(&self) -> Schedule {        Schedule::Every(Duration::from_secs(3600))    }    fn probe(&self) -> Probe {        if self.ready {            Probe::ready()        } else {            Probe::needs(Need::FullDiskAccess)        }    }    fn run(&self, _cursor: Option<&str>, ctx: &mut RunContext<'_>) -> Result<String, RunError> {        let n = self.runs.fetch_add(1, Ordering::SeqCst) + 1;        let mut calls: Vec<DeviceCall> = serde_json::from_value(fixture("calls")["calls"].clone()).unwrap();        // As the Mac's call history reader names them: the count a run ends on is what the copy holds from it.        for call in &mut calls {            call.source = cotton_client::ingest::sources::call_history::CALL_SOURCE.to_string();        }        ctx.send(IngestBatch { work: IngestWork::Calls { calls }, read: 2, cursor: Some(format!("batch:{n}")) })?;        Ok(format!("run:{n}"))    }}fn object(status: u16) -> TestServer {    let tables: Vec<Value> = ["call", "person", "person_handle", "message_contact", "message_contact_handle"].into_iter().map(support::object::kit_table).collect();    TestServer::start(move |request| match request.path.split('?').next().unwrap_or("") {        "/v1/definitions" => Answer::json(200, json!({ "business": { "database_id": DB }, "tables": tables })),        "/v1/me" if status == 200 => Answer::json(200, json!({ "person": {}, "version": 1 })),        "/v1/sync" if status == 200 => Answer::json(200, json!({ "version": 1, "rows": [] })),        "/v1/act" if status == 200 => Answer::json(200, json!({ "version": 2, "made": { "call": 2 }, "changed": {} })),        _ => Answer::json(status, json!({ "code": "unauthorized", "message": "revoked" })),    })}/// A source with nothing new: every run sends nothing.struct Quiet {    runs: Arc<AtomicUsize>,}impl Importer for Quiet {    fn key(&self) -> SourceKey {        SourceKey::Calls    }    fn schedule(&self) -> Schedule {        Schedule::Every(Duration::from_secs(3600))    }    fn probe(&self) -> Probe {        Probe::ready()    }    fn run(&self, cursor: Option<&str>, _ctx: &mut RunContext<'_>) -> Result<String, RunError> {        self.runs.fetch_add(1, Ordering::SeqCst);        Ok(cursor.unwrap_or("quiet").to_string())    }}fn open(server: &TestServer, dir: &std::path::Path, importer: impl Importer + 'static) -> App {    let config = Config {        data_dir: dir.to_path_buf(),        object_url: server.url.clone(),        device_id: "dev-1".into(),        machine: "test-mac".into(),        device_name: "Owner's Mac".into(),        app_version: "0.3.0 (12)".into(),        home: dir.to_path_buf(),        helpers_dir: None,    };    App::open(config, vec![Box::new(importer)], Box::new(NoKeyring)).unwrap()}fn wait_for(app: &App, what: impl Fn(&Value) -> bool) -> Value {    let started = Instant::now();    loop {        let status = app.call("status", &json!({}));        if what(&status) {            return status;        }        // A hang guard, not a timing: it returns the moment the status holds.        // Ten seconds tripped under load (rust-main #10210, 14 Nov 2026: the        // whole binary ran 6-10x slower beside the verifier's rust jobs).        assert!(started.elapsed() < Duration::from_secs(60), "timed out; last status {status}");        std::thread::sleep(Duration::from_millis(20));    }}fn calls(status: &Value) -> &Value {    status["sources"].as_array().unwrap().iter().find(|s| s["source"] == "calls").unwrap()}#[test]fn a_started_app_runs_its_source_and_says_what_it_brought() {    let dir = tempfile::tempdir().unwrap();    let server = object(200);    let runs = Arc::new(AtomicUsize::new(0));    let app = open(&server, dir.path(), FakeCalls { runs: runs.clone(), ready: true });    let before = app.call("status", &json!({}));    assert_eq!(before["ok"], true);    assert_eq!(before["signedIn"], false);    assert_eq!(app.call("start", &json!({ "token": "tok", "phone": "+919800000000" }))["ok"], true);    let status = wait_for(&app, |s| calls(s)["total"] == 2 && calls(s)["phase"] == "idle");    assert_eq!(status["signedIn"], true);    assert_eq!(status["phone"], "+919800000000");    assert_eq!(status["host"], server.url.trim_start_matches("http://"));    assert!(status["lastPushAt"].is_string());    assert_eq!(calls(&status)["lastBrought"], 2);    assert_eq!(calls(&status)["schedule"], "Hourly");    // Every request after the definitions carries the token.    assert!(server.requests().iter().all(|r| r.header("authorization") == Some("Bearer tok")));    // Run now runs it again, though the hour is not up. The same two calls land on themselves: none is new, and    // the count stays what is there (the walk's "24 calls" for 12, 23 Nov 2026).    assert_eq!(app.call("runNow", &json!({ "source": "calls" }))["ok"], true);    wait_for(&app, |_| runs.load(Ordering::SeqCst) == 2);    let status = wait_for(&app, |s| calls(s)["phase"] == "idle");    assert_eq!(calls(&status)["total"], 2);    // Each pass names the device once, on its own call, as a phone's first    // sync page does, so the object files its row; the imports carry nothing.    let paths: Vec<String> = server.requests().iter().map(|r| r.path.clone()).collect();    assert_eq!(paths.iter().filter(|p| **p == format!("/v1/me?{FACTS}")).count(), 2, "{paths:?}");    // The calls are decided over the importer's copy and land through import_rows, two rows a pass.    let imports: Vec<Value> = server.requests().iter().filter(|r| r.path == "/v1/act").map(|r| r.json()).collect();    assert_eq!(imports.len(), 2, "{paths:?}");    assert!(imports.iter().all(|act| act["act"] == "import_rows" && act["args"]["rows"].as_array().map(Vec::len) == Some(2)), "{imports:?}");    assert!(paths.iter().all(|p| !p.starts_with("/v1/import")), "{paths:?}");    assert!(paths.iter().filter(|p| p.starts_with("/v1/definitions")).all(|p| p == "/v1/definitions"));    app.stop();}const FACTS: &str = "device_name=Owner%27s+Mac&platform=mac&app_version=0.3.0+%2812%29";// RULE: a pass with nothing to send still names the Mac — one call, and no// other — so a quiet Mac appears on the object at once and is never forgotten.#[test]fn a_quiet_pass_makes_the_one_naming_call_and_no_other() {    let dir = tempfile::tempdir().unwrap();    let server = object(200);    let runs = Arc::new(AtomicUsize::new(0));    let app = open(&server, dir.path(), Quiet { runs: runs.clone() });    assert_eq!(app.call("start", &json!({ "token": "tok", "phone": "+919800000000" }))["ok"], true);    wait_for(&app, |s| calls(s)["phase"] == "idle" && runs.load(Ordering::SeqCst) == 1);    assert_eq!(app.call("runNow", &json!({ "source": "calls" }))["ok"], true);    wait_for(&app, |s| calls(s)["phase"] == "idle" && runs.load(Ordering::SeqCst) == 2);    let paths: Vec<String> = server.requests().iter().map(|r| r.path.clone()).collect();    // The database id is asked once and kept; after it, each pass is the one naming call.    let named = format!("/v1/me?{FACTS}");    assert_eq!(paths, ["/v1/definitions", named.as_str(), named.as_str()]);    app.stop();}#[test]fn a_paused_source_does_not_run_until_resumed() {    let dir = tempfile::tempdir().unwrap();    let server = object(200);    let runs = Arc::new(AtomicUsize::new(0));    let app = open(&server, dir.path(), FakeCalls { runs: runs.clone(), ready: true });    app.call("pause", &json!({ "source": "calls" }));    app.call("start", &json!({ "token": "tok" }));    std::thread::sleep(Duration::from_millis(300));    assert_eq!(runs.load(Ordering::SeqCst), 0);    assert_eq!(calls(&app.call("status", &json!({})))["phase"], "paused");    app.call("resume", &json!({ "source": "calls" }));    wait_for(&app, |s| calls(s)["total"] == 2);    app.stop();}#[test]fn a_source_that_needs_something_says_so_and_does_not_run() {    let dir = tempfile::tempdir().unwrap();    let server = object(200);    let runs = Arc::new(AtomicUsize::new(0));    let app = open(&server, dir.path(), FakeCalls { runs: runs.clone(), ready: false });    app.call("start", &json!({ "token": "tok" }));    let status = wait_for(&app, |s| calls(s)["phase"] == "needs");    assert_eq!(calls(&status)["probe"]["need"]["kind"], "fullDiskAccess");    std::thread::sleep(Duration::from_millis(200));    assert_eq!(runs.load(Ordering::SeqCst), 0);    app.stop();}#[test]fn a_401_signs_the_app_out() {    let dir = tempfile::tempdir().unwrap();    let server = object(401);    let runs = Arc::new(AtomicUsize::new(0));    let app = open(&server, dir.path(), FakeCalls { runs, ready: true });    app.call("start", &json!({ "token": "tok" }));    let status = wait_for(&app, |s| s["signedOut"] == true);    assert_eq!(status["signedIn"], false);    app.stop();}#[test]fn an_unknown_method_or_source_is_refused() {    let dir = tempfile::tempdir().unwrap();    let server = object(200);    let app = open(&server, dir.path(), FakeCalls { runs: Arc::new(AtomicUsize::new(0)), ready: true });    assert_eq!(app.call("nope", &json!({}))["code"], "unknown_method");    assert_eq!(app.call("runNow", &json!({ "source": "fax" }))["code"], "bad_source");}/// Refused by the object on its first `fail` runs, then lands; polled every/// [`REFUSED_EVERY`]./// The poll of [`Refused`]: long enough that a run's own cost on a loaded/// machine (up to about a second seen on CI, where every crate's tests run at/// once) stays well short of the waits the test tells apart.const REFUSED_EVERY: Duration = Duration::from_millis(200);struct Refused {    runs: Arc<std::sync::Mutex<Vec<Instant>>>,    fail: usize,}impl Importer for Refused {    fn key(&self) -> SourceKey {        SourceKey::Whatsapp    }    fn schedule(&self) -> Schedule {        Schedule::Continuous(REFUSED_EVERY)    }    fn probe(&self) -> Probe {        Probe::ready()    }    fn run(&self, _cursor: Option<&str>, _ctx: &mut RunContext<'_>) -> Result<String, RunError> {        let mut runs = self.runs.lock().unwrap();        runs.push(Instant::now());        if runs.len() <= self.fail {            Err(RunError::Failed("the object refused (400 bad_batch): synthetic".to_string()))        } else {            Ok("landed".to_string())        }    }}// RULE (27 Oct 2026): a refused run is retried later each time — its interval// doubled per failure in a row, at most RETRY_CEILING — not every poll: a// WhatsApp page refused every 5 s re-read the same page, and the helper// fetched its media from WhatsApp again each time (36 GB an hour over the// owner's home line). A run that lands puts the source back on its interval.#[test]fn a_refused_source_backs_off_and_a_landed_run_resets_it() {    use cotton_mac::app::{retry_after, RETRY_CEILING};    let five = Duration::from_secs(5);    assert_eq!(retry_after(five, 0), five);    assert_eq!(retry_after(five, 1), Duration::from_secs(10));    assert_eq!(retry_after(five, 3), Duration::from_secs(40));    assert_eq!(retry_after(five, 40), RETRY_CEILING);    let dir = tempfile::tempdir().unwrap();    let server = object(200);    let runs = Arc::new(std::sync::Mutex::new(Vec::new()));    let app = open(&server, dir.path(), Refused { runs: runs.clone(), fail: 4 });    app.call("start", &json!({ "token": "tok", "phone": "+919800000000" }));    // Refused four times: waits of 400, 800, 1600 and 3200 ms after the first    // four runs, where a poll every 200 ms would have run about 30 times.    let started = Instant::now();    // The cap only bounds a stuck source; the gaps below are the rule. Under    // load a run itself took seconds and nine missed 30 s (rust-main 17065).    while runs.lock().unwrap().len() < 9 && started.elapsed() < Duration::from_secs(180) {        std::thread::sleep(Duration::from_millis(10));    }    app.stop();    let at = runs.lock().unwrap().clone();    assert!(at.len() >= 9, "the source stopped running: {} runs", at.len());    let gaps: Vec<Duration> = at.windows(2).map(|pair| pair[1] - pair[0]).collect();    // The wait counts from a run's start, before the calls each run makes    // first, so a gap between two runs' own starts may fall a little short of    // it; the first run alone also asks the database id, so the first gap may    // fall short by that call too (130 ms seen on a loaded box). A source that    // never backed off is still caught by the later gaps.    for (i, failures) in (1..=4).enumerate() {        let wait = retry_after(REFUSED_EVERY, failures);        let least = if i == 0 { wait / 2 } else { wait * 3 / 4 };        assert!(gaps[i] >= least, "run {} came {:?} after a refusal, before {least:?}", i + 2, gaps[i]);    }    // Landed: back on its own poll. A source that kept its four failures would    // wait at least 3200 ms after every run. The first landed run also opens    // the Mac's copy once to recount the source (63 s of it seen at load 55),    // so the gap after it is left out; a run's own cost reached 2.2 s there,    // so only the full kept wait tells the two apart.    let kept = retry_after(REFUSED_EVERY, 4);    for gap in &gaps[5..] {        assert!(*gap < kept, "a landed source still waits: {gaps:?}");    }}// RULE (owner at the Mac, 22 Nov 2026): rows waiting for this Mac to be let in are retried every 30 s at most,// never on the ten-minute back-off, and a new sign-in (an approval from a phone) runs every source at once.#[test]fn waiting_for_the_vault_retries_soon_and_an_approval_runs_at_once() {    use cotton_mac::app::{next_run_after, RETRY_CEILING, VAULT_RETRY};    let five = Duration::from_secs(5);    assert_eq!(next_run_after(five, 40, false), RETRY_CEILING);    assert_eq!(next_run_after(five, 40, true), VAULT_RETRY);    assert_eq!(next_run_after(five, 1, true), Duration::from_secs(10), "a short back-off stays short");    let dir = tempfile::tempdir().unwrap();    let server = object(200);    let runs = Arc::new(std::sync::Mutex::new(Vec::new()));    // Refused every time: the back-off grows to seconds between runs.    let app = open(&server, dir.path(), Refused { runs: runs.clone(), fail: usize::MAX });    app.call("start", &json!({ "token": "tok", "phone": "+919800000000" }));    let started = Instant::now();    while runs.lock().unwrap().len() < 4 && started.elapsed() < Duration::from_secs(30) {        std::thread::sleep(Duration::from_millis(10));    }    let before = runs.lock().unwrap().len();    // The next run is due 1600 ms or more away; a new sign-in runs it now.    app.call("start", &json!({ "token": "tok-approved", "phone": "+919800000000" }));    let asked = Instant::now();    while runs.lock().unwrap().len() == before && asked.elapsed() < Duration::from_secs(5) {        std::thread::sleep(Duration::from_millis(5));    }    let took = asked.elapsed();    app.stop();    assert!(runs.lock().unwrap().len() > before, "the new sign-in ran nothing");    assert!(took < retry_after_for_test(4) / 2, "the new sign-in waited out the back-off: {took:?}");}fn retry_after_for_test(failures: u32) -> Duration {    cotton_mac::app::retry_after(REFUSED_EVERY, failures)}/// Records the cursor each run was given; every run ends at cursor `read`.struct Cursors {    seen: Arc<std::sync::Mutex<Vec<Option<String>>>>,}impl Importer for Cursors {    fn key(&self) -> SourceKey {        SourceKey::Calls    }    fn schedule(&self) -> Schedule {        Schedule::Every(Duration::from_secs(3600))    }    fn probe(&self) -> Probe {        Probe::ready()    }    fn run(&self, cursor: Option<&str>, _ctx: &mut RunContext<'_>) -> Result<String, RunError> {        self.seen.lock().unwrap().push(cursor.map(str::to_string));        Ok("read".to_string())    }}// RULE (owner, 22 Nov 2026, MAC-PANEL.md: "bring older history again" is reachable on the panel, and nothing on// it erases): Bring everything in again reads the source from its start once more — the next run is given no// cursor — and keeps what it counted; the run after goes on from where that one ended.#[test]fn bring_everything_in_again_reads_from_the_start_and_erases_nothing() {    let dir = tempfile::tempdir().unwrap();    let server = object(200);    let seen = Arc::new(std::sync::Mutex::new(Vec::new()));    let app = open(&server, dir.path(), Cursors { seen: seen.clone() });    app.call("start", &json!({ "token": "tok", "phone": "+919800000000" }));    let ran = |n: usize| {        let seen = seen.clone();        move |_: &Value| seen.lock().unwrap().len() >= n    };    wait_for(&app, ran(1));    app.call("runNow", &json!({ "source": "calls" }));    wait_for(&app, ran(2));    assert_eq!(app.call("bringAgain", &json!({ "source": "calls" }))["ok"], true);    wait_for(&app, ran(3));    app.call("runNow", &json!({ "source": "calls" }));    wait_for(&app, ran(4));    assert_eq!(*seen.lock().unwrap(), vec![None, Some("read".to_string()), None, Some("read".to_string())]);    assert_eq!(app.call("bringAgain", &json!({ "source": "nope" }))["code"], "bad_source");    app.stop();}