Cotton code
515 lines · 19.6 KB · RustRaw
//! Where this device's sync stands, as ONE read (lane syncstatus, the//! architect's brief of 21 Oct 2026): the three numbers receipts make —//! changes not yet applied, changes not yet sent, bytes still to fetch — and//! the one line Home draws, chosen here from typed states.//!//! Receipts are the sync mechanism: every change has one and each device//! keeps one position in the stream, so the device always knows how many it//! has not applied and how many of its own it has not sent. Bytes (photos,//! documents) come after records, so the line says them last.//!//! THE WORDS ARE DATA. [`Line`] is a typed state with its numbers; the//! sentence is the shell's (`kits/shell/lines/sync.json`), filled by//! [`SyncWords::say`]. Nothing here composes a sentence, and a rewording is a//! change to that file alone.use std::collections::BTreeMap;use serde::{Deserialize, Serialize};use crate::device::pairing::DevicePlatform;/// How long no answer from the serving Mac must have lasted before the line/// says it was not reached. A missed pass is a blip — a lift, a tunnel — and/// a line that said so every time would be noise.pub const NOT_REACHED_AFTER_MS: i64 = 15 * 60 * 1000;/// What this device is to the database: a full device sends its own changes;/// a reader only receives.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum Role {    #[default]    Full,    Reader,}/// The serving Mac's last contact: when it last answered, and the first/// pass since then that went unanswered (epoch milliseconds).#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Contact {    #[serde(default, skip_serializing_if = "Option::is_none")]    pub answered_at: Option<i64>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub silent_since: Option<i64>,}impl Contact {    /// Did the last pass reach the serving Mac? `None` before any pass.    pub fn reached(&self) -> Option<bool> {        match (self.answered_at, self.silent_since) {            (None, None) => None,            (_, Some(_)) => Some(false),            (Some(_), None) => Some(true),        }    }}/// The receipts in both directions.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Receipts {    /// Receipts the serving Mac holds that this device has not applied, as    /// the Mac last counted them; `None` when it has not said.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub behind: Option<u64>,    /// The Mac counts only up to its cap: `behind` is "at least".    #[serde(default, skip_serializing_if = "std::ops::Not::not")]    pub at_least: bool,    /// This device's own receipts not yet sent (its outbox and held writes).    pub to_send: u64,    /// When a pass last applied receipts here (epoch milliseconds).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub last_applied_at: Option<i64>,}/// A count of files and their bytes. Either may be unknown.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct Pile {    #[serde(default, skip_serializing_if = "Option::is_none")]    pub count: Option<u64>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub bytes: Option<u64>,}impl Pile {    fn waiting(&self) -> bool {        self.count.is_some_and(|count| count > 0) || self.bytes.is_some_and(|bytes| bytes > 0)    }}/// The bytes in both directions: what keep rules still want fetched, and/// what this device has filed and not yet uploaded.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Bytes {    pub to_fetch: Pile,    pub to_send: Pile,}/// One table on the detail page.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct TableFacts {    pub rows: u64,    /// The newest receipt this device holds for the table (epoch ms).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub last_receipt_at: Option<i64>,}/// What the line is chosen from.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Facts {    pub role: Role,    /// No other device holds this database — founded here and never    /// joined by a Mac — so there is no serving Mac to reach, and this    /// device is never its own peer.    #[serde(default, skip_serializing_if = "std::ops::Not::not")]    pub alone: bool,    /// What this device is, for the line that says it holds the database    /// alone; `None` when it does not know.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub here: Option<DevicePlatform>,    /// The serving Mac's name, as its device row says it.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub serving: Option<String>,    /// This device syncs with Cotton's server (its person's own database    /// there), not with a Mac: the line names no Mac (a phone said "Up to    /// date with your Mac", launch walk of Words, 22 Nov 2026).    #[serde(default, skip_serializing_if = "std::ops::Not::not")]    pub with_cotton: bool,    pub contact: Contact,    pub receipts: Receipts,    pub bytes: Bytes,}/// The one line, as a typed state. Precedence, first that holds:/// alone, not reached, receiving, sending, fetching, reader only, up to date —/// records before bytes, and an unreachable Mac before anything it would/// have moved.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(tag = "state", rename_all = "snake_case")]pub enum Line {    UpToDate {        #[serde(default, skip_serializing_if = "Option::is_none")]        with: Option<String>,        at: i64,    },    Receiving {        #[serde(default, skip_serializing_if = "Option::is_none")]        with: Option<String>,        n: u64,        #[serde(default, skip_serializing_if = "std::ops::Not::not")]        at_least: bool,    },    Sending {        #[serde(default, skip_serializing_if = "Option::is_none")]        with: Option<String>,        n: u64,    },    Fetching {        count: u64,        bytes: u64,    },    NotReached {        #[serde(default, skip_serializing_if = "Option::is_none")]        with: Option<String>,        /// When the Mac last answered; `None` when it never has.        #[serde(default, skip_serializing_if = "Option::is_none")]        since: Option<i64>,    },    ReaderOnly {        #[serde(default, skip_serializing_if = "Option::is_none")]        with: Option<String>,        at: i64,    },    /// The database lives on this device only: nothing to reach, nothing    /// wrong — a calm line, never the red one.    Alone {        #[serde(default, skip_serializing_if = "Option::is_none")]        here: Option<DevicePlatform>,    },}impl Line {    /// The line `facts` say at `now_ms`.    pub fn of(facts: &Facts, now_ms: i64) -> Line {        if facts.alone {            return Line::Alone { here: facts.here };        }        let with = facts.serving.clone().filter(|name| !name.trim().is_empty());        let contact = &facts.contact;        let silent_from = contact.silent_since.map(|since| contact.answered_at.unwrap_or(since));        let Some(at) = contact.answered_at.filter(|_| {            !silent_from.is_some_and(|from| now_ms.saturating_sub(from) >= NOT_REACHED_AFTER_MS)        }) else {            return Line::NotReached { with, since: contact.answered_at };        };        if let Some(n) = facts.receipts.behind.filter(|n| *n > 0) {            return Line::Receiving { with, n, at_least: facts.receipts.at_least };        }        if facts.role == Role::Full && facts.receipts.to_send > 0 {            return Line::Sending { with, n: facts.receipts.to_send };        }        if facts.bytes.to_fetch.waiting() {            let pile = facts.bytes.to_fetch;            return Line::Fetching { count: pile.count.unwrap_or(0), bytes: pile.bytes.unwrap_or(0) };        }        match facts.role {            Role::Reader => Line::ReaderOnly { with, at },            Role::Full => Line::UpToDate { with, at },        }    }    /// The key of the shell's words this line is said with.    pub fn key(&self) -> &'static str {        match self {            Line::UpToDate { .. } => "up_to_date",            Line::Receiving { n: 1, at_least: false, .. } => "receiving_one",            Line::Receiving { at_least: true, .. } => "receiving_at_least",            Line::Receiving { .. } => "receiving",            Line::Sending { n: 1, .. } => "sending_one",            Line::Sending { .. } => "sending",            Line::Fetching { count: 1, .. } => "fetching_one",            Line::Fetching { .. } => "fetching",            Line::NotReached { since: Some(_), .. } => "not_reached",            Line::NotReached { since: None, .. } => "not_reached_never",            Line::ReaderOnly { .. } => "reader_only",            Line::Alone { here: Some(DevicePlatform::Ios) } => "alone_ios",            Line::Alone { here: Some(DevicePlatform::Android) } => "alone_android",            Line::Alone { here: Some(DevicePlatform::Mac) } => "alone_mac",            Line::Alone { here: Some(DevicePlatform::Linux) } => "alone_linux",            Line::Alone { here: None } => "alone",        }    }    /// Every key a line may be said with, for the guard that the shell's    /// words have each.    pub const KEYS: &'static [&'static str] = &[        "up_to_date",        "receiving",        "receiving_one",        "receiving_at_least",        "sending",        "sending_one",        "fetching",        "fetching_one",        "not_reached",        "not_reached_never",        "reader_only",        "alone",        "alone_ios",        "alone_android",        "alone_mac",        "alone_linux",    ];}/// The shell's words for the line (`kits/shell/lines/sync.json`).#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct SyncWords {    pub format_version: u32,    pub id: String,    /// One template a [`Line::key`]; `{with}`, `{at}`, `{since}`, `{n}`,    /// `{count}` and `{bytes}` are filled.    pub lines: BTreeMap<String, String>,    /// The words of a line when this device syncs with Cotton's server    /// ([`Facts::with_cotton`]), by [`Line::key`]: no Mac is named. A key    /// they lack is said in `lines`' words.    #[serde(default)]    pub cotton: BTreeMap<String, String>,    /// What a screen says over one row before the person changes it    /// (`sync.row`): `coming`, while the pass under way still brings rows of    /// its table.    #[serde(default)]    pub row: BTreeMap<String, String>,    /// What the Sync page says of changes that cannot be sent and will not go by themselves (UNSENT HEAL,    /// `sync.stuck`): the line, its detail and its two acts.    #[serde(default)]    pub unsent: BTreeMap<String, String>,    /// What `{with}` is when the serving Mac has no name here.    pub unnamed: String,    /// What a table no tool draws is counted under.    pub other: String,    pub ages: Ages,    /// The detail page's lines: what came since open, one per tool, and    /// every table with its rows and newest receipt, one per table.    pub detail: Detail,    pub sizes: Sizes,}/// The detail page's line templates: `{tool}` `{n}`; `{table}` `{rows}` `{at}`.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Detail {    pub received: String,    pub table: String,    pub table_unstamped: String,}/// The detail page's two readings, in the shell's words: one line per tool/// that received changes since the app opened, and one per table.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]#[serde(rename_all = "camelCase")]pub struct DetailSaid {    pub received: String,    pub tables: String,}/// How long ago, said: `{n}` is filled.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Ages {    pub now: String,    pub minutes: String,    pub hours: String,    pub days: String,}/// A count of bytes, said: `{n}` is filled.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Sizes {    pub megabytes: String,    pub gigabytes: String,}/// The shipped words, when nothing in a database says otherwise.impl Default for SyncWords {    fn default() -> Self {        SyncWords::shipped().clone()    }}/// The shipped words.pub const SHIPPED: &str = include_str!("../../kits/shell/lines/sync.json");impl SyncWords {    /// The shell's shipped words.    pub fn shipped() -> &'static SyncWords {        static WORDS: std::sync::OnceLock<SyncWords> = std::sync::OnceLock::new();        WORDS.get_or_init(|| serde_json::from_str(SHIPPED).expect("kits/shell/lines/sync.json is the sync words"))    }    /// The words a database says: its `lines` rows first, the shipped words    /// for any line it has no row for (`rules::shell_lines`).    pub fn of_rows(rows: &[super::shell_lines::LineRow]) -> SyncWords {        super::shell_lines::resolved("sync", rows)            .and_then(|file| serde_json::from_value(file).ok())            .unwrap_or_else(|| SyncWords::shipped().clone())    }    /// `line` in these words at `now_ms`. A key the words lack says nothing,    /// which the guard over the shipped file keeps from happening.    pub fn say(&self, line: &Line, now_ms: i64) -> String {        self.say_with(line, false, now_ms)    }    /// `line` at `now_ms`, in the words for syncing with Cotton's server when    /// `with_cotton` ([`Self::cotton`]), else in the words naming the Mac.    pub fn say_with(&self, line: &Line, with_cotton: bool, now_ms: i64) -> String {        let cotton = with_cotton.then(|| self.cotton.get(line.key())).flatten();        let Some(template) = cotton.or_else(|| self.lines.get(line.key())) else { return String::new() };        let with = match line {            Line::UpToDate { with, .. }            | Line::Receiving { with, .. }            | Line::Sending { with, .. }            | Line::NotReached { with, .. }            | Line::ReaderOnly { with, .. } => with.as_deref(),            Line::Fetching { .. } | Line::Alone { .. } => None,        }        .unwrap_or(&self.unnamed);        let mut said = template.replace("{with}", with);        match line {            Line::UpToDate { at, .. } | Line::ReaderOnly { at, .. } => {                said = said.replace("{at}", &self.age(now_ms.saturating_sub(*at)));            }            Line::Receiving { n, .. } | Line::Sending { n, .. } => said = said.replace("{n}", &grouped(*n)),            Line::Fetching { count, bytes } => {                said = said.replace("{count}", &grouped(*count)).replace("{bytes}", &self.size(*bytes));            }            Line::NotReached { since, .. } => {                if let Some(since) = since {                    said = said.replace("{since}", &self.age(now_ms.saturating_sub(*since)));                }            }            Line::Alone { .. } => {}        }        // A Mac's name at the start of a sentence is already capitalised;        // the unnamed words are not.        capitalised(&said)    }    /// One line per tool, in the order given, `{n}` grouped.    pub fn received_lines(&self, by_tool: &BTreeMap<String, u64>) -> String {        by_tool            .iter()            .map(|(tool, n)| self.detail.received.replace("{tool}", &capitalised(tool)).replace("{n}", &grouped(*n)))            .collect::<Vec<_>>()            .join("\n")    }    /// One line per table, by name: its rows, and how long ago its newest    /// receipt was when it has one.    pub fn table_lines(&self, tables: &BTreeMap<String, TableFacts>, now_ms: i64) -> String {        tables            .iter()            .map(|(table, facts)| {                let template = if facts.last_receipt_at.is_some() { &self.detail.table } else { &self.detail.table_unstamped };                let mut said = template.replace("{table}", table).replace("{rows}", &grouped(facts.rows));                if let Some(at) = facts.last_receipt_at {                    said = said.replace("{at}", &self.age(now_ms.saturating_sub(at)));                }                said            })            .collect::<Vec<_>>()            .join("\n")    }    pub fn age(&self, ms: i64) -> String {        let minutes = ms.max(0) / 60_000;        let (template, n) = match minutes {            0 => return self.ages.now.clone(),            1..=59 => (&self.ages.minutes, minutes),            60..=1439 => (&self.ages.hours, minutes / 60),            _ => (&self.ages.days, minutes / 1440),        };        template.replace("{n}", &n.to_string())    }    fn size(&self, bytes: u64) -> String {        let megabytes = bytes.div_ceil(1_000_000).max(1);        if megabytes < 1_000 {            return self.sizes.megabytes.replace("{n}", &megabytes.to_string());        }        let tenths = bytes.div_ceil(100_000_000);        self.sizes.gigabytes.replace("{n}", &format!("{}.{}", tenths / 10, tenths % 10))    }}/// The line with its words, as a screen draws it.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct Said {    #[serde(flatten)]    pub line: Line,    pub words: String,}/// The whole read: the facts, what came since this app opened by tool, the/// per-table detail when it was asked for, and the line.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]#[serde(rename_all = "camelCase")]pub struct Status {    #[serde(flatten)]    pub facts: Facts,    /// Receipts applied since this app opened, by the tool each table    /// belongs to; tables no tool draws under the words' `other`.    pub received_since_open: BTreeMap<String, u64>,    #[serde(skip_serializing_if = "Option::is_none")]    pub tables: Option<BTreeMap<String, TableFacts>>,    /// The detail page's readings, said only when it asked (`detail: true`).    #[serde(skip_serializing_if = "Option::is_none")]    pub detail: Option<DetailSaid>,    pub line: Said,}impl Status {    /// The read `facts` make at `now_ms`, `received` being what has come    /// since this app opened by store table, and `tool_of` naming the tool a    /// store table belongs to.    pub fn of(        facts: Facts,        received: &BTreeMap<String, u64>,        tool_of: impl Fn(&str) -> Option<&'static str>,        tables: Option<BTreeMap<String, TableFacts>>,        words: &SyncWords,        now_ms: i64,    ) -> Status {        let mut by_tool: BTreeMap<String, u64> = BTreeMap::new();        for (table, n) in received.iter().filter(|(_, n)| **n > 0) {            let tool = tool_of(table).map_or_else(|| words.other.clone(), str::to_string);            *by_tool.entry(tool).or_default() += n;        }        let line = Line::of(&facts, now_ms);        let said = words.say_with(&line, facts.with_cotton, now_ms);        let detail = tables.as_ref().map(|tables| DetailSaid {            received: words.received_lines(&by_tool),            tables: words.table_lines(tables, now_ms),        });        Status { facts, received_since_open: by_tool, tables, detail, line: Said { line, words: said } }    }}/// `41000` as `41,000`.fn grouped(count: u64) -> String {    let digits = count.to_string();    let mut out = String::with_capacity(digits.len() + digits.len() / 3);    for (at, digit) in digits.chars().enumerate() {        if at > 0 && (digits.len() - at) % 3 == 0 {            out.push(',');        }        out.push(digit);    }    out}fn capitalised(text: &str) -> String {    let mut chars = text.chars();    match chars.next() {        Some(first) => first.to_uppercase().chain(chars).collect(),        None => String::new(),    }}#[cfg(test)]#[path = "sync_status_tests.rs"]mod tests;