Cotton code
236 lines · 12.5 KB · RustRaw
//! FIRST SYNC STATES (coordinator, 26 Nov 2026): every app's first screens say that the person's things are still//! coming while its first sync runs, never that there are none. The owner saw Post say "No mail here yet. Add an//! account to bring it in." and "0 mails" while 280,000 mail rows were still on their way: Post's mail tables are a//! kit's late tables, pulled by the pass after the first one, so the copy read as whole (`copy_standing::Held`) while//! its mail had not come.//!//! A copy is in its first sync ([`judged`]) while://! - its first pull has not ended, or its rows wait for the account's key, or for another device to let it in//!   (`copy_standing::of`, as before); or//! - its first fill still owes tables it left for the next pass (`cotton_client::transport::object::first_fill_owes`),//!   and one of them is a table this answer reads. The pictures' rows (`media`), which every first fill leaves for//!   later, keep no list but Photos' in its first sync.//!//! Each answer [`SPECS`] names then carries `firstSync`://!//! ```json//! "firstSync": { "state": "bringing" | "unreached", "line": "Loading your data…",//!                "seen": { "state": "catching_up", "line": "Syncing 1,200 of 3,108", "percent": 38, … } }//! ```//!//! `line` is the standing's words (`copy_standing::Standing::words`). `seen` is what Account and every home say of sync//! (`shell_account::seen`, from `seen_of`), so the count is the same one: "Syncing 1,200 of 3,108" while a counted pass//! runs. Where an answer would say it is empty, its empty line is `line` instead. Where it would say a zero count in//! words ("0 mails", "0 notes"), that line is the count (`seen.line` while a pass is counting, else `line`). A count//! that is a number stays the number, and a shell draws no zero while `firstSync` stands. A refusal that a record or//! a table is not here ("No tool draws this table", which a copy whose definitions have not come says) is//! `not_here_yet` in `line`'s words. Once the first sync is over, no answer carries `firstSync` and every empty line is//! the answer's own.use serde_json::{json, Value};use crate::methods::MethodError;use crate::phone::copy_standing::{self, Standing};use crate::shell::client::ClientController;/// Post's mail tables, the ones its homes read.const MAIL: &[&str] = &["email_thread", "email", "email_sender", "email_participant", "email_draft", "mail_history", "email_account", "email_cut", "email_bin_cut", "email_read_cut"];/// One answer that says empty or zero: the tables it reads (`None`: any a first fill owes but the pictures'), the/// paths of the lines it says when empty, and the paths of the count lines it says in words.pub struct Spec {    pub method: &'static str,    pub tables: Option<&'static [&'static str]>,    pub empty: &'static [&'static [&'static str]],    pub counts: &'static [&'static [&'static str]],}const EMPTY: &[&[&str]] = &[&["empty"]];const EMPTY_TITLE: &[&[&str]] = &[&["empty", "title"]];const NONE: &[&[&str]] = &[];/// Every home, list and count answer of the shared core that says empty or zero (the keys the phone builders read:/// report.md "FIRST SYNC STATES").pub const SPECS: &[Spec] = &[    // Post    Spec { method: "mail.home", tables: Some(MAIL), empty: EMPTY, counts: NONE },    Spec { method: "mail.list", tables: Some(MAIL), empty: EMPTY, counts: NONE },    Spec { method: "mail.side", tables: Some(MAIL), empty: NONE, counts: NONE },    // mail.you says its first sync once itself (the card), its rows from what the phone holds (owner, 26 Nov 2026).    Spec { method: "mail.you", tables: Some(MAIL), empty: NONE, counts: NONE },    Spec { method: "mail.senders", tables: Some(MAIL), empty: EMPTY, counts: NONE },    Spec { method: "mail.files", tables: Some(MAIL), empty: EMPTY, counts: NONE },    Spec { method: "mail.accounts", tables: Some(MAIL), empty: EMPTY, counts: NONE },    // Words    Spec { method: "notes.list", tables: None, empty: EMPTY, counts: &[&["count_words"]] },    Spec { method: "notes.side", tables: None, empty: NONE, counts: NONE },    Spec { method: "notes.fan", tables: None, empty: NONE, counts: NONE },    // Comms    Spec { method: "chat.list", tables: None, empty: &[&["words", "empty"]], counts: NONE },    // Cinemas    Spec { method: "cinemas.home", tables: None, empty: EMPTY, counts: NONE },    Spec { method: "cinemas.you", tables: None, empty: NONE, counts: NONE },    // Data    Spec { method: "data.tables", tables: None, empty: EMPTY, counts: NONE },    Spec { method: "data.rows", tables: None, empty: EMPTY, counts: NONE },    Spec { method: "data.lately", tables: None, empty: EMPTY, counts: NONE },    // Story    Spec { method: "story.list", tables: None, empty: EMPTY, counts: NONE },    // Secrets    Spec { method: "vault.items", tables: None, empty: EMPTY_TITLE, counts: NONE },    Spec { method: "secrets.people", tables: None, empty: EMPTY_TITLE, counts: NONE },    // Health    Spec { method: "health.people", tables: None, empty: EMPTY, counts: NONE },    Spec { method: "health.reports", tables: None, empty: EMPTY, counts: NONE },    // The shared shell: Days' today, the fan apps' lists, decks and streams, any table's records    Spec { method: "shell.home", tables: None, empty: NONE, counts: NONE },    Spec { method: "shell.today", tables: None, empty: EMPTY, counts: NONE },    Spec { method: "shell.list", tables: None, empty: EMPTY, counts: NONE },    Spec { method: "shell.deck", tables: None, empty: EMPTY, counts: NONE },    Spec { method: "shell.stream", tables: None, empty: EMPTY, counts: NONE },    Spec { method: "shell.fan", tables: None, empty: NONE, counts: NONE },    Spec { method: "records.list", tables: None, empty: EMPTY, counts: NONE },    Spec { method: "groups.list", tables: None, empty: EMPTY, counts: NONE },];/// The spec of `method`, when it is a home, list or count answer.pub fn spec(method: &str) -> Option<&'static Spec> {    SPECS.iter().find(|spec| spec.method == method)}/// The table every first fill leaves for later, which keeps no list but Photos' loading.const PICTURES: &str = "media";/// Whether an answer reading `tables` stands in a first sync, and how: the copy's own standing while it has not come/// whole; else bringing (or unreached, its last pass failed) while its first fill still owes one of `tables`.pub fn judged(standing: Standing, owed: Option<&[String]>, tables: Option<&[&str]>, last_pass_failed: bool) -> Option<Standing> {    if standing != Standing::Held {        return Some(standing);    }    let owed = owed?;    let reads = |table: &String| match tables {        Some(tables) => tables.contains(&table.as_str()),        None => table != PICTURES,    };    owed.iter().any(reads).then_some(if last_pass_failed { Standing::Unreached } else { Standing::Bringing })}/// Where `client`'s copy stands for an answer reading `tables`, `None` once its first sync is over.pub fn of(client: &ClientController, tables: Option<&[&str]>) -> Option<Standing> {    let standing = copy_standing::of(client);    let owed = if standing == Standing::Held && client.signed_in() && client.object_door().is_some() {        client.with_file(|file| cotton_client::transport::object::first_fill_owes(file.driver)).ok().flatten()    } else {        None    };    judged(standing, owed.as_deref(), tables, client.last_pass_failed())}/// The `firstSync` object for a standing, with `seen` (the count Account says).pub fn said(standing: Standing, seen: Value) -> Value {    let mut said = json!({ "state": standing.word(), "line": standing.words(), "seen": seen });    // A slow or missed answer mid-sync is not a headline (owner, 26 Nov 2026, on Post): a home may keep the loading    // words (`bringing`) and its count, with `trying` as the small line under them.    if standing == Standing::Unreached {        said["bringing"] = json!(Standing::Bringing.words());        said["trying"] = json!(cotton_core::rules::shell_lines::LineSet::shipped("boot").and_then(|lines| lines.say("home.trying", &[])));    }    said}/// `answer` as `spec` says it in a first sync: `firstSync`, its empty lines in `firstSync.line`, its count lines in/// the count. A line that is not there (an answer with rows says no empty line) is left absent.pub fn apply(spec: &Spec, first: &Value, answer: &mut Value) {    let Some(line) = first["line"].as_str().map(str::to_string) else { return };    let count = if first["seen"]["state"] == "catching_up" { first["seen"]["line"].as_str().map(str::to_string).unwrap_or_else(|| line.clone()) } else { line.clone() };    for path in spec.empty {        if let Some(slot) = at(answer, path).filter(|slot| slot.is_string()) {            *slot = json!(line);        }    }    for path in spec.counts {        let Some(slot) = at(answer, path).filter(|slot| slot.is_string()) else { continue };        let before = std::mem::replace(slot, json!(count));        // The same count said again on a row (mail.you's Storage row says "0 mails" as its title, as the card does).        if let Some(said) = before.as_str() {            replace_equal(answer, said, &count);        }    }    if answer.is_object() {        answer["firstSync"] = first.clone();    }}fn at<'a>(answer: &'a mut Value, path: &[&str]) -> Option<&'a mut Value> {    let mut slot = answer;    for key in path {        slot = slot.as_object_mut()?.get_mut(*key)?;    }    Some(slot)}fn replace_equal(value: &mut Value, said: &str, count: &str) {    match value {        Value::String(text) if text == said => *text = count.to_string(),        Value::Array(items) => items.iter_mut().for_each(|item| replace_equal(item, said, count)),        Value::Object(map) => map.values_mut().for_each(|item| replace_equal(item, said, count)),        _ => {}    }}/// A refusal that a record or a table is not here, said while the first sync runs: `not_here_yet` in `line`'s words./// "No tool draws this table" is what a copy whose definitions have not come says of a table it will hold (a read/// refuses it `unreadable`; Story's list, which lays its own rows first, `write_refused`).pub fn refused(first: &Value, refusal: MethodError) -> MethodError {    let not_here = matches!(refusal.code.as_str(), "not_found" | "record_not_found")        || (matches!(refusal.code.as_str(), "unreadable" | "write_refused") && refusal.message.starts_with("No tool draws this table"));    match first["line"].as_str() {        Some(line) if not_here => MethodError::new(copy_standing::NOT_HERE_YET, line),        _ => refusal,    }}/// The copy's parked sealed rows by why, as `firstSync.parked` says them (FIRST SYNC 6): `waitingParent` (rows that/// opened and wait for the row they belong to, no error) apart from `refused`. Counted off the code index at most/// every [`PARKED_FOR`], since every home answer of a first sync carries it; `None` when none is parked.fn parked_now(client: &ClientController) -> Option<Value> {    static SEEN: std::sync::Mutex<Option<(std::path::PathBuf, std::time::Instant, Option<Value>)>> = std::sync::Mutex::new(None);    let database = client.current_database().ok()?;    let path = client.layout().replica(&database);    let mut seen = SEEN.lock().unwrap_or_else(|poisoned| poisoned.into_inner());    if let Some((at, when, said)) = seen.as_ref() {        if *at == path && when.elapsed() < PARKED_FOR {            return said.clone();        }    }    let counted = rusqlite::Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX)        .ok()        .and_then(|db| crate::shell::database_files::parked_rows(&db))        .and_then(|parked| serde_json::to_value(parked).ok());    *seen = Some((path, std::time::Instant::now(), counted.clone()));    counted}/// How long one count of the parked rows stands for every answer.const PARKED_FOR: std::time::Duration = std::time::Duration::from_secs(5);/// `dispatch`'s step: a home, list or count answer of a copy in its first sync says so.pub fn on_answer(client: &ClientController, method: &str, answer: Result<Value, MethodError>) -> Result<Value, MethodError> {    let Some(spec) = spec(method) else { return answer };    let Some(standing) = of(client, spec.tables) else { return answer };    let mut first = said(standing, crate::methods::shell_account::seen(client));    if let Some(parked) = parked_now(client) {        first["parked"] = parked;    }    match answer {        Ok(mut answer) => {            apply(spec, &first, &mut answer);            Ok(answer)        }        Err(refusal) => Err(refused(&first, refusal)),    }}#[cfg(test)]#[path = "first_sync_tests.rs"]mod tests;