Cotton code
272 lines · 15.1 KB · RustRaw
//! MAIL PREDICATE phase 2 (27 Nov 2026; the coordinator's eight rules, NEXT-PHASE2-RULES): the predicate honouring//! one row per act. `email_bin_cut` (Delete of a whole sender or domain), `email_read_cut` (Mark read of many) and//! Archive's `email_cut`, kept as the kit tables `cotton_email_bin_cut`, `cotton_email_read_cut`, `cotton_email_cut`.//! The phone's readers move onto these with the store schema that gives every copy the tables and `cotton_emails`//! its `landed_at` (157, held until Comms is cut from 156); the Worker's mirror (`apps/business/src/mail/predicate.ts`)//! runs the same cases (`cut_cases.json`).//!//! A cut covers a mail when ALL hold://! - the cut row is not deleted and its `state` is not `undone` (PHASE 2 PHONE 2, item 3: a Delete's row is never//!   removed by a phone; its Undo is a versioned write of `state`, so Undo and the erase cannot both win);//! - the mail is not from one of his own addresses ([`OWN`]): a Delete of his work domain leaves his own mail;//! - its key is the mail's address normalised ([`normalise_key`], through the SQL function [`KEY_FUNCTION`] the//!   phone registers), `@` and the mail's domain, or (a read cut only) `*`: equality probes on the cut's `key` index,//!   never a scan. A key is stored normalised by its writer; a key stored any other way covers nothing. `+tag` is not//!   folded: `ada+news@` is its own address;//! - the mail was sent at or before the cut's `before`;//! - the mail LANDED on the server at or before the cut's `at`: `landed_at`, stamped by the server's clock when the//!   row first landed there, which no device, import or stamp can write (rule 3), read from [`LANDED`] (kept beside//!   the mail row, never on it: filling it on a held copy would rewrite every body, PHASE 2 PHONE 2 item 5). A mail//!   with no landing time is never covered (rule 1). An edit after the cut changes nothing;//! - its id is not in the cut's `except`.//!//! Precedence (rule 7), written once: an explicit act on one mail newer than a cut > a bin cut > an archive cut > a//! read cut. The newer act is kept by its writer adding the mail's id to the `except` of EVERY cut of that kind that//! covers it (restore from the Bin: every covering bin cut; back to the Inbox: every covering archive cut; mark//! unread: every covering read cut). So a mail binned by a cut is not archived, and one read by a cut stays unread//! once he marks it so. Bin and read are separate questions: a binned mail is read or unread as its read cuts say.//!//! Who stamps `at` (rule 2): never the phone's clock. `at` is the newest server landing time among the mails the//! screen showed when he tapped ([`cut_at`]), and a cut whose `at` is later than the newest landing this copy knows is//! refused at write ([`check_cut_at`]). So a fast clock covers nothing extra, and mail the server took that this//! phone had not pulled (not on his screen) is not covered.//!//! Two times on a cut (PHASE 2 PHONE 2, item 1): `at` bounds what it covers (server arrival); `made_at` is when he//! tapped (the later of the phone's clock and the newest server time the copy knew). A Delete's Bin date and its 30//! days run from `made_at` alone: a sender quiet for 40 days is never erased the pass after its Delete.//!//! Times (rule 8): every value compared here (`at`, `before`, `sent_at`, `landed_at`) is written in one shape, UTC//! with exactly three fractional digits and `Z` ([`normalise_time`]); a value in another shape is normalised at write//! or refused, never compared as text.use std::sync::LazyLock;pub const BIN_TABLE: &str = "cotton_email_bin_cut";pub const READ_TABLE: &str = "cotton_email_read_cut";pub const ARCHIVE_TABLE: &str = "cotton_email_cut";pub const EMAILS: &str = "cotton_emails";pub const THREADS: &str = "cotton_email_threads";/// Every cut this copy holds (schema 157, device-local), kept from the three kit tables by [`mirror`]'s triggers:/// what the predicate reads, so a copy whose kit made no cut table answers every mail uncut.pub const CUTS: &str = "_mail_cuts";/// Each kit table and its `kind` in [`CUTS`].pub const KINDS: [(&str, &str); 3] = [(BIN_TABLE, "bin"), (READ_TABLE, "read"), (ARCHIVE_TABLE, "archive")];/// When each mail landed on the server, beside the mail row (schema 157, device-local): `id`, `landed_at`, its/// sender's `key` ([`normalise_key`]) and that key's `domain` (`@` and after), so a sender's or a domain's landed mail/// and the newest landing are index seeks. Kept from `cotton_emails.landed_at` by triggers when a pulled row brings/// it, and filled for mail held before 157 by the phone's landing fill without writing the mail row.pub const LANDED: &str = "_mail_landed";/// His own addresses, normalised (schema 157, device-local, kept by the phone): never covered by any cut.pub const OWN: &str = "_mail_own";/// The triggers that keep [`CUTS`] equal to a kit cut table, and the statement that copies what it holds now. A/// deleted row (Undo) leaves [`CUTS`]; a row whose key, `before` or `at` is missing (still sealed) is not a cut yet.pub fn mirror(table: &str, kind: &str) -> Vec<String> {    let put = format!(        "INSERT INTO {CUTS} (kind, id, \"key\", \"before\", \"at\", \"except\", made_at, state) SELECT '{kind}', NEW.id, NEW.\"key\", NEW.\"before\", NEW.\"at\", NEW.\"except\", NEW.made_at, NEW.state \         WHERE NEW.deleted_at IS NULL AND NEW.\"key\" IS NOT NULL AND NEW.\"before\" IS NOT NULL AND NEW.\"at\" IS NOT NULL AND NEW.made_at IS NOT NULL \         ON CONFLICT (kind, id) DO UPDATE SET \"key\" = excluded.\"key\", \"before\" = excluded.\"before\", \"at\" = excluded.\"at\", \"except\" = excluded.\"except\", made_at = excluded.made_at, state = excluded.state"    );    let drop_new = format!("DELETE FROM {CUTS} WHERE kind = '{kind}' AND id = NEW.id AND (NEW.deleted_at IS NOT NULL OR NEW.\"key\" IS NULL OR NEW.\"before\" IS NULL OR NEW.\"at\" IS NULL OR NEW.made_at IS NULL)");    vec![        format!("CREATE TRIGGER IF NOT EXISTS {CUTS}_{kind}_made AFTER INSERT ON {table} BEGIN {put}; END"),        format!("CREATE TRIGGER IF NOT EXISTS {CUTS}_{kind}_changed AFTER UPDATE ON {table} BEGIN {drop_new}; {put}; END"),        format!("CREATE TRIGGER IF NOT EXISTS {CUTS}_{kind}_gone AFTER DELETE ON {table} BEGIN DELETE FROM {CUTS} WHERE kind = '{kind}' AND id = OLD.id; END"),        format!(            "INSERT INTO {CUTS} (kind, id, \"key\", \"before\", \"at\", \"except\", made_at, state) SELECT '{kind}', id, \"key\", \"before\", \"at\", \"except\", made_at, state FROM {table} \             WHERE deleted_at IS NULL AND \"key\" IS NOT NULL AND \"before\" IS NOT NULL AND \"at\" IS NOT NULL AND made_at IS NOT NULL \             ON CONFLICT (kind, id) DO UPDATE SET \"key\" = excluded.\"key\", \"before\" = excluded.\"before\", \"at\" = excluded.\"at\", \"except\" = excluded.\"except\", made_at = excluded.made_at, state = excluded.state"        ),    ]}/// The SQL function, registered on the phone's connections, that is [`normalise_key`]. SQLite's own `lower` folds/// A to Z only.pub const KEY_FUNCTION: &str = "cotton_mail_key";/// The SQL function, registered beside [`KEY_FUNCTION`], that is [`normalise_time`] (NULL for a time not in a shape/// it reads): every time a cut compares passes it, so `…:00Z` and `…:00.000Z` are one moment (review of the rules, 3).pub const TIME_FUNCTION: &str = "cotton_mail_time";/// The most ids one cut's `except` holds (LOW: `json_each` over `except` is read per covered mail). A move back past/// it is refused in words (`act.except_full`): Undo the whole act instead.pub const EXCEPT_MAX: usize = 200;/// What a key's ends are trimmed of, the same set on the phone and the Worker (a JS `trim` takes more than Rust's/// `trim` and the other way round, so neither is used).pub const TRIM: &[char] = &[' ', '\t', '\n', '\r', '\u{000B}', '\u{000C}', '\u{00A0}', '\u{FEFF}', '\u{2028}', '\u{2029}', '\u{3000}'];/// One normaliser for a mail's address and a cut's key: the ends trimmed of [`TRIM`], then lower case by full/// Unicode. Used by the cut's writer, the phone's SQL (through [`KEY_FUNCTION`]) and the Worker's mirror.pub fn normalise_key(key: &str) -> String {    key.trim_matches(TRIM).to_lowercase()}static PUBLIC: LazyLock<Vec<String>> = LazyLock::new(|| {    let file: serde_json::Value = serde_json::from_str(include_str!("public_domains.json")).expect("public_domains.json reads");    file["domains"].as_array().expect("domains").iter().filter_map(|d| d.as_str().map(str::to_string)).collect()});/// The public mail domains a whole-domain cut is refused for (`public_domains.json`).pub fn public_domains() -> &'static [String] {    &PUBLIC}/// A public mail service's domain, or any name under it (`mail.yahoo.co.uk` is yahoo.co.uk's): matched by the/// registrable suffix, never the exact name alone (PHASE 2 PHONE 2, low).pub fn is_public_domain(domain: &str) -> bool {    PUBLIC.iter().any(|p| domain == p || domain.strip_suffix(p.as_str()).is_some_and(|rest| rest.ends_with('.')))}/// Why a cut's key cannot be written, or None. A domain key (`@domain`) names one exact domain, never a public one.pub fn refused_key(key: &str) -> Option<&'static str> {    let normal = normalise_key(key);    if normal != key {        return Some("not_normal");    }    if normal.is_empty() || normal == "@" {        return Some("empty");    }    if let Some(domain) = normal.strip_prefix('@') {        if domain.contains('@') || !domain.contains('.') {            return Some("not_a_domain");        }        if is_public_domain(domain) {            return Some("public_domain");        }    }    None}/// A time in the one shape compared here, `YYYY-MM-DDTHH:MM:SS.mmmZ` in UTC, from an RFC 3339 time with any/// offset and any fractional digits (cut to milliseconds, never rounded); None for anything else.pub fn normalise_time(value: &str) -> Option<String> {    let bytes = value.as_bytes();    // RFC 3339 with the `T` only, so both readers take the same strings.    // A leap second (`:60`) is refused as the TypeScript mirror refuses it.    if bytes.len() < 20 || bytes[10] != b'T' || value.ends_with('z') || &bytes[17..19] == b"60" {        return None;    }    let parsed = chrono::DateTime::parse_from_rfc3339(value).ok()?;    Some(parsed.with_timezone(&chrono::Utc).format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string())}/// A time already in the one shape.pub fn is_pinned(value: &str) -> bool {    normalise_time(value).as_deref() == Some(value)}/// A cut's `at`: the newest server landing time among the mails the screen showed when he tapped. None when none/// of them has one (nothing to cut).pub fn cut_at<'a>(shown_landed: impl IntoIterator<Item = Option<&'a str>>) -> Option<String> {    shown_landed.into_iter().flatten().filter_map(normalise_time).max()}/// Why a cut's `at` cannot be written, or None: it must be pinned and no later than the newest landing this copy/// knows (never the phone's clock).pub fn check_cut_at(at: &str, newest_known: Option<&str>) -> Option<&'static str> {    if !is_pinned(at) {        return Some("not_pinned");    }    match newest_known.and_then(normalise_time) {        Some(newest) if at <= newest.as_str() => None,        _ => Some("later_than_known"),    }}/// The prefix a column of the outer row is read by inside a subquery: `on`, or the table's own name when `on` is/// empty (an unprefixed `id` inside a subquery over [`CUTS`] would be the cut's own).fn outer<'a>(on: &'a str, table: &str) -> std::borrow::Cow<'a, str> {    if on.is_empty() { std::borrow::Cow::Owned(format!("{table}.")) } else { std::borrow::Cow::Borrowed(on) }}fn covering(table: &str, on: &str, star: bool) -> String {    format!("FROM {CUTS} c WHERE {}", covering_where_star(table, on, star))}/// The conditions under which the cut `c` (a row of [`CUTS`]) of `table`'s kind covers the mail whose columns are/// prefixed by `on`: for a query that names both (which cuts cover this mail, for its `except`).pub fn covering_where(table: &str, on: &str) -> String {    covering_where_star(table, on, table == READ_TABLE)}fn covering_where_star(table: &str, on: &str, star: bool) -> String {    let on = outer(on, EMAILS);    let on = on.as_ref();    let kind = KINDS.iter().find(|(t, _)| *t == table).map(|(_, k)| *k).unwrap_or("none");    let address = format!("{KEY_FUNCTION}({on}from_email)");    let star = if star { ", '*'" } else { "" };    format!(        "c.kind = '{kind}' AND c.\"key\" IN ({address}, substr({address}, instr({address}, '@')){star}) \         AND coalesce(c.state, 'live') <> 'undone' \         AND {TIME_FUNCTION}({on}sent_at) <= {TIME_FUNCTION}(c.\"before\") \         AND {TIME_FUNCTION}((SELECT l.landed_at FROM {LANDED} l WHERE l.id = {on}id)) <= {TIME_FUNCTION}(c.\"at\") \         AND {address} NOT IN (SELECT o.\"key\" FROM {OWN} o) \         AND NOT EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(c.\"except\") THEN c.\"except\" ELSE '[]' END) x WHERE x.value = {on}id)"    )}/// A bin cut covers the mail.pub fn bin_covers(on: &str) -> String {    format!("EXISTS (SELECT 1 {})", covering(BIN_TABLE, on, false))}/// A read cut covers the mail.pub fn read_covers(on: &str) -> String {    format!("EXISTS (SELECT 1 {})", covering(READ_TABLE, on, true))}/// An archive cut covers the mail.pub fn archive_covers(on: &str) -> String {    format!("EXISTS (SELECT 1 {})", covering(ARCHIVE_TABLE, on, false))}/// A mail not in the Bin: neither its own `trashed_at` nor a bin cut. Still implies `trashed_at IS NULL`, so the/// partial indexes apply.pub fn live(on: &str) -> String {    format!("({on}trashed_at IS NULL AND NOT {})", bin_covers(on))}/// A mail in the Bin.pub fn binned(on: &str) -> String {    format!("({on}trashed_at IS NOT NULL OR {})", bin_covers(on))}/// A live mail an archive cut covers (a bin cut wins over it).pub fn archived(on: &str) -> String {    format!("({} AND {})", live(on), archive_covers(on))}/// A mail not yet read: its own `unread` and no read cut.pub fn unread(on: &str) -> String {    format!("({on}unread = 1 AND NOT {})", read_covers(on))}/// A mail read.pub fn read(on: &str) -> String {    format!("({on}unread = 0 OR {})", read_covers(on))}/// When a mail went to the Bin: its own `trashed_at`, else the earliest covering bin cut's `made_at` (when he tapped,/// never `at`); NULL when live.pub fn binned_at(on: &str) -> String {    format!("coalesce({on}trashed_at, (SELECT min({TIME_FUNCTION}(c.made_at)) {}))", covering(BIN_TABLE, on, false))}/// A conversation (`cotton_email_threads`, columns prefixed by `on`) is live when any of its mails is live by/// [`live`] (rule 4): derived, never its stored `trashed_at`, which no cut sets.pub fn live_thread(on: &str) -> String {    let on = outer(on, THREADS);    let on = on.as_ref();    format!("EXISTS (SELECT 1 FROM {EMAILS} m WHERE m.thread_id = {on}id AND {})", live("m."))}/// A conversation in the Bin: it holds opened mail and none of it is live. One whose mail is all still sealed is/// neither (waiting).pub fn binned_thread(on: &str) -> String {    let on = outer(on, THREADS);    let on = on.as_ref();    format!("(NOT {} AND EXISTS (SELECT 1 FROM {EMAILS} m WHERE m.thread_id = {on}id))", live_thread(on))}#[cfg(test)]#[path = "cuts_tests.rs"]mod tests;