Cotton code
213 lines · 8.9 KB · RustRaw
//! Cotton Data: the rules behind what the app says about the database//! (assets/design/data/DECISIONS.md, CONTRACT.md). Pure: no file, no clock,//! no network. The phone's `data_app` gathers the facts; this decides the words.//!//! - which app uses a table ([`apps_of`]), and which group it is listed under//!   ([`group_of`]): an app's, the assistants', Cotton's own, or a leftover;//! - whether a table is sealed and which fields stay clear ([`seal_of`]);//! - how a count, a size and a moment are said ([`count`], [`size`], [`ago`]);//! - a row's one line, from its table's slip ([`rows::sentence`]), and each//!   field drawn by its type ([`rows::field`]).//!//! **Read only.** Nothing here writes, and nothing the app calls writes: the//! module has no write to offer.pub mod rows;use serde_json::Value;use crate::rules::shell_lines::LineSet;#[cfg(test)]mod tests;/// The `data` line set.pub fn lines() -> &'static LineSet {    static LINES: std::sync::OnceLock<LineSet> = std::sync::OnceLock::new();    LINES.get_or_init(|| LineSet::shipped("data").expect("the kit ships the data line set"))}/// One line of the `data` set; a missing line is a kit bug the line test catches, said as its key.pub fn say(line: &str, fills: &[(&str, &str)]) -> String {    lines().say(line, fills).unwrap_or_else(|| line.to_string())}/// The family's apps, in the order a person meets them, each with the kit/// whose tables it keeps. A table used by several is listed under the first.pub const FAMILY: [(&str, &str); 11] = [    ("Days", "days"),    ("Words", "notes"),    ("Story", "story"),    ("Comms", "messages"),    ("Post", "mail"),    ("Secrets", "keys"),    ("Books", "books"),    ("Cinemas", "cinemas"),    ("Health", "health"),    ("Meetings", "meetings"),    ("Downloads", "downloads"),];/// Tables the assistants keep: their memory and their sessions. No app draws/// them; an assistant writes them over its connection.pub const ASSISTANT_TABLES: [&str; 7] = ["memory", "project", "session", "prompt", "session_task", "session_message", "agent_account"];/// Tables no assistant's window ever opens (`apps/business/src/agent_statement.ts` NEVER).pub const NEVER: [&str; 3] = ["code_credential", "passkey", "secret"];/// Tables whose values only Secrets opens: Data lists their rows' names, never a value.pub fn secret_table(table: &str) -> bool {    NEVER.contains(&table)}/// The apps that use `table`, in [`FAMILY`] order.pub fn apps_of(table: &str) -> Vec<&'static str> {    FAMILY.iter().filter(|(_, kit)| crate::kit::AppKit::tables_of(kit).iter().any(|t| t == table)).map(|(label, _)| *label).collect()}/// Where the Tables list puts a table.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Group {    /// Used by an app (the first, in [`FAMILY`] order), and maybe others.    App { app: &'static str, also: Vec<&'static str> },    /// Kept by the assistants (and maybe drawn by an app too).    Assistants { also: Vec<&'static str> },    /// Cotton's own working parts: devices, keys, tokens. Open by design.    Cotton,    /// Retired: its rows wait for the server to erase them.    Retired,    /// No app uses it any more.    Unused,}/// The group `table` is listed under. `internal` is the definition's own/// mark (the object's own table).pub fn group_of(table: &str, internal: bool) -> Group {    if crate::retired::GONE_TABLES.contains(&table) {        return Group::Retired;    }    let apps = apps_of(table);    if ASSISTANT_TABLES.contains(&table) {        return Group::Assistants { also: apps };    }    if let Some((first, rest)) = apps.split_first() {        return Group::App { app: first, also: rest.to_vec() };    }    if internal || crate::seal::rule::open_by_design(table).is_some() || crate::kit::AppKit::tables_of("shell").iter().any(|t| t == table) {        return Group::Cotton;    }    Group::Unused}/// Whether a table is sealed, and what the server can read of it.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Seal {    /// Opened only on the person's phones; `clear` are the fields the server keeps readable to sort and sync.    Sealed { clear: Vec<String> },    /// Cotton's own working parts, read by the server by design.    Open,    /// Still read by the server until its lock is switched on.    Pending,}/// The seal of a table, from its definition as stored (JSON): its own `seal`/// block, else the default rule (`seal/default.json`).pub fn seal_of(definition: &Value) -> Seal {    let id = definition["id"].as_str().unwrap_or_default();    if crate::seal::rule::pending(id).is_some() {        return Seal::Pending;    }    if definition["internal"] == Value::Bool(true) || crate::seal::rule::open_by_design(id).is_some() {        return Seal::Open;    }    let own: Option<Vec<String>> = definition.get("seal").map(|seal| seal["clear"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect());    let clear = own.or_else(|| crate::seal::rule::default_seal(definition).map(|seal| seal.clear)).unwrap_or_default();    Seal::Sealed { clear }}/// A count with its thousands grouped: `96,214`.pub fn count(n: u64) -> String {    let digits = n.to_string();    let mut out = String::with_capacity(digits.len() + digits.len() / 3);    for (i, c) in digits.chars().enumerate() {        if i > 0 && (digits.len() - i) % 3 == 0 {            out.push(',');        }        out.push(c);    }    out}/// A number of rows in words: "No rows", "1 row", "96,214 rows".pub fn rows_line(n: u64) -> String {    // English has no "zero" plural form, so the line's zero is picked here.    if n == 0 {        return lines().say("rows.count.zero", &[]).unwrap_or_default();    }    say("rows.count", &[("n", &count(n))])}/// A size in bytes, as the storage screens say it (1,000 to a KB, as the cap is/// counted): "520 MB", "3.2 MB", "48 KB", "6.5 GB". Under ten units it keeps one/// decimal, dropped when it is zero.pub fn size(bytes: u64) -> String {    const UNITS: [(&str, f64); 4] = [("GB", 1e9), ("MB", 1e6), ("KB", 1e3), ("bytes", 1.0)];    let b = bytes as f64;    for (unit, scale) in UNITS {        if b >= scale || unit == "bytes" {            let v = b / scale;            if unit == "bytes" {                return format!("{bytes} bytes");            }            let one = (v * 10.0).round() / 10.0;            return if one < 10.0 && one.fract() != 0.0 { format!("{one:.1} {unit}") } else { format!("{} {unit}", v.round() as u64) };        }    }    unreachable!()}/// How long ago `then` was, against `now` (both in milliseconds): "today",/// "yesterday", "3 days ago", else the date ("3 Oct 2026", the year left out in/// the same year).pub fn ago(then_ms: i64, now_ms: i64) -> String {    use chrono::{Datelike, TimeZone, Utc};    let (Some(then), Some(now)) = (Utc.timestamp_millis_opt(then_ms).single(), Utc.timestamp_millis_opt(now_ms).single()) else { return String::new() };    let days = (now.date_naive() - then.date_naive()).num_days();    match days {        d if d <= 0 => say("say.today", &[]),        1 => say("say.yesterday", &[]),        d if d < 7 => say("say.days_ago", &[("n", &d.to_string())]),        _ if then.year() == now.year() => then.format("%-d %b").to_string(),        _ => then.format("%-d %b %Y").to_string(),    }}/// A date, as the app says it on a line: "3 Oct 2026".pub fn day(ms: i64) -> String {    use chrono::{TimeZone, Utc};    Utc.timestamp_millis_opt(ms).single().map(|t| t.format("%-d %b %Y").to_string()).unwrap_or_default()}/// The first fill's estimate for `rows_bytes` of rows, in whole minutes, never under one (DECISIONS question 3).////// Measured at the owner's size on dev (26 Nov 2026, the Data proof in a release build, 600,000 invented rows whose/// measured room is 770 MB): Kept on this phone after about 60 minutes, 0.21 MB of rows a second all told. Where the/// time goes, from a profile of the sync thread: about 30% fetching pages, 17% SQLite's WAL checkpoints (each with an/// fsync), 16% writing rows (much of it the statement journal spilling to a file), the rest opening, indexing and/// waiting. The 0.5 MB a second this said before was 29 MB of sealed rows timed on a loaded box.pub fn fill_minutes(rows_bytes: u64) -> u64 {    (rows_bytes as f64 / 0.21e6 / 60.0).ceil().max(1.0) as u64}/// The room a phone keeping everything holds for `rows_bytes` of rows: the rows and this phone's own search index/// of them. Measured at the owner's size on dev: 770 MB of rows made a 2.2 GB copy once its index had settled, so/// three times the rows (the same three times Keep everything asks to start on).pub fn kept_bytes(rows_bytes: u64) -> u64 {    rows_bytes.saturating_mul(3)}/// Whether Keep everything starts on: the phone must have three times the/// room the rows take, plus the 2 GB it always leaves free (DECISIONS question 3).pub fn keep_starts_on(rows_bytes: u64, free_bytes: u64) -> bool {    free_bytes >= rows_bytes.saturating_mul(3).saturating_add(2_000_000_000)}