Cotton code
218 lines · 9.4 KB · RustRaw
//! Words for the local device row, ported from `DeviceHere`/`SyncBackupWords`.use serde_json::{Map, Value};pub fn facts(status: &Value) -> Map<String, Value> {    let mut out = Map::new();    let state = status["state"].as_str();    let no_mac = state == Some("noServerYet");    if state.is_some() {        out.insert("has_server".into(), Value::from(!no_mac));    }    if let Some(fill) = status.get("searchIndex").and_then(Value::as_object) {        if let (Some(a), Some(b)) = (fill["filled"].as_u64(), fill["total"].as_u64()) {            out.insert(                "search_index".into(),                Value::from(format!("{a} of {b} mail")),            );        }    }    if let Some(failed) = status.pointer("/media/failed").and_then(Value::as_array) {        out.insert(            "backups".into(),            Value::from(match failed.len() {                0 => "nothing failed".into(),                1 => "1 file couldn't be backed up".into(),                n => format!("{n} files couldn't be backed up"),            }),        );        if !failed.is_empty() {            out.insert(                "failed_files".into(),                Value::from(                    failed                        .iter()                        .filter_map(failed_line)                        .collect::<Vec<_>>()                        .join("\n"),                ),            );        }    }    if let Some(coming) = status        .pointer("/sync/coming")        .and_then(Value::as_array)        .filter(|v| !no_mac && !v.is_empty())    {        out.insert(            "coming".into(),            Value::from(                coming                    .iter()                    .filter_map(Value::as_str)                    .collect::<Vec<_>>()                    .join("\n"),            ),        );    }    if !no_mac && status["connected"].as_bool() == Some(true) {        let stopped = status.pointer("/loop/stoppedReason").and_then(Value::as_str);        let waiting = status.pointer("/loop/state").and_then(Value::as_str) == Some("waiting")            || (status.pointer("/loop/state").and_then(Value::as_str) == Some("syncing")                && status.pointer("/loop/failures").and_then(Value::as_u64).is_some_and(|n| n > 0));        if let Some(reason) = stopped.filter(|s| !s.is_empty()) {            let mut chars = reason.chars();            if let Some(first) = chars.next() { out.insert("sync_trouble".into(), Value::from(format!("{}{}", first.to_uppercase(), chars.as_str()))); }        } else if waiting {            let error = status.pointer("/loop/lastError").and_then(Value::as_str).filter(|s| !s.is_empty());            out.insert("sync_trouble".into(), Value::from(error.map_or_else(|| "Retrying".into(), |e| format!("Retrying — {e}"))));        }    }    if matches!(status.pointer("/sync/state").and_then(Value::as_str), Some("moving" | "syncing" | "copying")) {        if let Some(refusal) = status.pointer("/loop/wakeRefusal").and_then(Value::as_str).filter(|s| !s.is_empty()) {            out.insert("sync_background".into(), Value::from(format!("The Mac cannot wake this device now: {refusal}")));        }    }    out}/// The phone's real background constraint is an explanation, not a forecast.pub fn facts_for(status: &Value, on_phone: bool) -> Map<String, Value> {    let mut out = facts(status);    if on_phone && matches!(status.pointer("/sync/state").and_then(Value::as_str), Some("moving" | "syncing" | "copying")) {        let mut line = "iOS decides when background time is granted, so a large sync may still finish only when Cotton is opened; a phone that is behind should normally be level within hours without being opened.".to_string();        if let Some(refusal) = status.pointer("/loop/wakeRefusal").and_then(Value::as_str).filter(|value| !value.is_empty()) {            line.push_str(&format!(" The Mac cannot wake this phone now: {refusal}"));        }        out.insert("sync_background".into(), Value::from(line));    }    out}/// How many rows from the database this copy could not keep and set aside/// (`_parked`, direction pull), said on the card's last-try line after what/// the pass itself said: a pass that parks a row goes on and moves its/// position, so this line is the only place the person learns a row was left/// out. None parked says nothing more.pub fn with_parked(out: &mut Map<String, Value>, parked: usize) {    let words = match parked {        0 => return,        1 => "1 row could not be kept on this device".to_string(),        n => format!("{n} rows could not be kept on this device"),    };    let line = match out.get("sync_trouble").and_then(Value::as_str).filter(|said| !said.is_empty()) {        Some(said) => format!("{said} · {words}"),        None => words,    };    out.insert("sync_trouble".into(), Value::from(line));}/// This device's sync as typed columns for its own page, from `sync.status`'s/// `status` asked with `detail: true` (`rules::sync_status`): the receipts/// both ways, the files both ways with their bytes, the serving Mac and its/// last answer, and the detail readings the core said in the shell's words./// A part the status does not carry is left out: unknown, never zero.pub fn sync_facts(status: &Value) -> Map<String, Value> {    let mut out = Map::new();    let mut put = |key: &str, value: Option<&Value>| {        if let Some(value) = value.filter(|value| !value.is_null()) {            out.insert(key.into(), value.clone());        }    };    put("receipts_behind", status.pointer("/receipts/behind"));    put("receipts_to_send", status.pointer("/receipts/toSend"));    put("fetch_count", status.pointer("/bytes/toFetch/count"));    put("fetch_bytes", status.pointer("/bytes/toFetch/bytes"));    put("upload_count", status.pointer("/bytes/toSend/count"));    put("upload_bytes", status.pointer("/bytes/toSend/bytes"));    put("serving_mac", status.get("serving"));    let said = |detail: &str| status.pointer(&format!("/detail/{detail}")).filter(|value| value.as_str().is_some_and(|text| !text.is_empty()));    put("received_since_open", said("received"));    put("sync_tables", said("tables"));    if let Some(at) = status.pointer("/contact/answeredAt").and_then(Value::as_i64).and_then(chrono::DateTime::from_timestamp_millis) {        out.insert("last_contact".into(), Value::from(at.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)));    }    out}/// The facts about sync on this device's own page: whom it syncs with, when/// it paired and who approved it, its queue both ways, and its sessions./// None of them is true of an app that never syncs.pub const SYNC_ONLY: &[&str] = &[    "serving_mac",    "last_contact",    "receipts_behind",    "receipts_to_send",    "fetch_count",    "fetch_bytes",    "upload_count",    "upload_bytes",    "received_since_open",    "sync_tables",    "sync_table_progress",    "sync_trouble",    "sync_background",    "coming",    "changes_waiting",    "waiting_since",    "mac_heard_at",    "last_synced",    "bytes_wanted",    "asked_at",    "approved_at",    "approved_by_device",    "sessions",    "sessions_running",];/// This device's page in an app that never syncs (the manifest's/// `"sync": false`): its one state is that the database lives here alone,/// and every sync fact is cleared — null, so a live overlay clears what an/// earlier read or a stale connection left — whatever state exists.pub fn without_sync(data: &mut Map<String, Value>) {    for column in SYNC_ONLY {        data.insert((*column).into(), Value::Null);    }    let alone = cotton_core::rules::sync_status::Line::Alone { here: Some(crate::phone::commands::THIS_BUILDS_PLATFORM) };    data.insert("ambient".into(), Value::from(alone.key()));}fn failed_line(v: &Value) -> Option<String> {    let key = v["key"].as_str()?;    let name = key.rsplit('/').next().unwrap_or(key);    Some(match v["lastError"].as_str() {        Some(e) => format!("{name} — {e}"),        None => name.into(),    })}#[cfg(test)]mod tests {    use super::*;    use serde_json::json;    /// RULE: Missing measurements are unknown, while a measured empty ledger    /// is empty. (This device's sync state is one typed column from    /// read.sync_state, guarded by this_devices_line_is_exactly_one_state.)    #[test]    fn unread_empty_and_offline_remain_distinct() {        let unread = facts(&json!({}));        assert!(!unread.contains_key("unsent"));        assert!(!unread.contains_key("backups"));        assert!(facts(&json!({"state":"syncing","media":{"failed":[]}})).contains_key("backups"));    }    /// RULE: a row the pass parked is said on the last-try line, by count,    /// after whatever the pass said; none parked adds nothing (dev Worker,    /// 29 Oct 2026: a row this copy could not read used to stop the pass, and    /// now it is set aside and the pass goes on, so the card says so).    #[test]    fn the_last_try_line_says_how_many_rows_were_parked() {        let mut quiet = Map::new();        with_parked(&mut quiet, 0);        assert!(!quiet.contains_key("sync_trouble"));        let mut one = Map::new();        with_parked(&mut one, 1);        assert_eq!(one["sync_trouble"], "1 row could not be kept on this device");        let mut retrying = facts(&json!({"connected":true,"mode":"object","loop":{"state":"waiting","lastError":"offline"}}));        with_parked(&mut retrying, 3);        assert_eq!(retrying["sync_trouble"], "Retrying — offline · 3 rows could not be kept on this device");    }}