Cotton code
177 lines · 10.8 KB · RustRaw
use super::*;use serde_json::Value;fn cases() -> Value {    serde_json::from_str(include_str!("cut_cases.json")).unwrap()}fn s(v: &Value) -> Option<String> {    v.as_str().map(str::to_string)}/// A connection with the phone's mail tables as the cuts read them, and the key and time functions registered as the/// phone registers them: a mail's landing kept beside it in [`LANDED`] by a trigger as the store's keeps it. (The/// store's own DDL and the kit tables' are checked by cotton-core's `mail_cuts_on_the_kit_tables`.)fn connection() -> rusqlite::Connection {    let db = rusqlite::Connection::open_in_memory().unwrap();    let flags = rusqlite::functions::FunctionFlags::SQLITE_UTF8 | rusqlite::functions::FunctionFlags::SQLITE_DETERMINISTIC;    db.create_scalar_function(KEY_FUNCTION, 1, flags, |ctx| Ok(ctx.get::<Option<String>>(0)?.map(|k| normalise_key(&k)))).unwrap();    db.create_scalar_function(TIME_FUNCTION, 1, flags, |ctx| Ok(ctx.get::<Option<String>>(0)?.and_then(|t| normalise_time(&t)))).unwrap();    let cut = |t: &str| format!("CREATE TABLE {t} (id TEXT PRIMARY KEY, \"key\" TEXT, \"before\" TEXT, \"at\" TEXT, \"except\" TEXT, deleted_at TEXT, made_at TEXT, state TEXT); CREATE INDEX {t}_key ON {t} (\"key\");");    db.execute_batch(&format!(        "CREATE TABLE {EMAILS} (id TEXT PRIMARY KEY, thread_id TEXT, from_email TEXT, sent_at TEXT, landed_at TEXT, updated_at TEXT, subject TEXT, unread INTEGER NOT NULL DEFAULT 0, trashed_at TEXT);         CREATE INDEX emails_thread ON {EMAILS} (thread_id);         CREATE TABLE cotton_email_threads (id TEXT PRIMARY KEY, trashed_at TEXT);         CREATE TABLE _seal_parked (tbl TEXT, id TEXT, body TEXT);         CREATE TABLE {CUTS} (kind TEXT NOT NULL, id TEXT NOT NULL, \"key\" TEXT NOT NULL, \"before\" TEXT NOT NULL, \"at\" TEXT NOT NULL, \"except\" TEXT, made_at TEXT NOT NULL, state TEXT, PRIMARY KEY (kind, id));         CREATE INDEX _mail_cuts_key ON {CUTS} (kind, \"key\");         CREATE TABLE {LANDED} (id TEXT PRIMARY KEY, landed_at TEXT NOT NULL, \"key\" TEXT NOT NULL, domain TEXT NOT NULL) WITHOUT ROWID;         CREATE TRIGGER landed_made AFTER INSERT ON {EMAILS} WHEN NEW.landed_at IS NOT NULL BEGIN INSERT INTO {LANDED} VALUES (NEW.id, NEW.landed_at, {KEY_FUNCTION}(NEW.from_email), substr({KEY_FUNCTION}(NEW.from_email), instr({KEY_FUNCTION}(NEW.from_email), '@'))); END;         CREATE TABLE {OWN} (\"key\" TEXT PRIMARY KEY) WITHOUT ROWID;         {} {} {}",        cut(BIN_TABLE),        cut(READ_TABLE),        cut(ARCHIVE_TABLE)    ))    .unwrap();    // The kit's cut tables reach the predicate through the triggers, as on the phone.    for (table, kind) in KINDS {        for statement in mirror(table, kind) {            db.execute_batch(&statement).unwrap();        }    }    db}/// RULE (MAIL PREDICATE phase 2, decision 6 and rules 1 to 7): the predicate with cuts answers every shared case/// exactly as the Worker's mirror does (apps/business/test/mail-predicate.test.ts runs the same file). A sealed row/// not yet opened waits in the parks, never in `cotton_emails`, so it is neither live nor binned, and a conversation/// of sealed mail only is neither.#[test]fn the_cuts_answer_every_shared_case() {    let file = cases();    for case in file["cases"].as_array().unwrap() {        let name = case["name"].as_str().unwrap();        let db = connection();        for (table, list) in [(BIN_TABLE, "bin"), (READ_TABLE, "read"), (ARCHIVE_TABLE, "archive")] {            for c in case[list].as_array().unwrap() {                db.execute(&format!("INSERT INTO {table} VALUES (?, ?, ?, ?, ?, ?, ?, ?)"), rusqlite::params![s(&c["id"]), s(&c["key"]), s(&c["before"]), s(&c["at"]), s(&c["except"]), s(&c["deleted_at"]), s(&c["made_at"]), s(&c["state"])]).unwrap();            }        }        for own in case["own"].as_array().into_iter().flatten() {            db.execute(&format!("INSERT INTO {OWN} VALUES (?)"), [normalise_key(own.as_str().unwrap())]).unwrap();        }        let mails = case["mails"].as_array().unwrap();        let mut threads: Vec<String> = Vec::new();        for m in mails {            let thread = s(&m["thread_id"]).unwrap();            if !threads.contains(&thread) {                threads.push(thread.clone());                // Stored as never binned: a conversation's own flag is not trusted where a cut applies.                db.execute("INSERT INTO cotton_email_threads VALUES (?, NULL)", [&thread]).unwrap();            }            if m["sealed"] == true {                db.execute("INSERT INTO _seal_parked VALUES ('cotton_emails', ?, ?)", rusqlite::params![s(&m["id"]), m["data"].to_string()]).unwrap();                continue;            }            db.execute(                &format!("INSERT INTO {EMAILS} VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"),                rusqlite::params![s(&m["id"]), thread, s(&m["from_email"]), s(&m["sent_at"]), s(&m["landed_at"]), s(&m["updated_at"]), s(&m["subject"]), m["unread"].as_i64().unwrap(), s(&m["trashed_at"])],            )            .unwrap();        }        let ids = |table: &str, condition: String| -> Vec<String> {            let mut statement = db.prepare(&format!("SELECT id FROM {table} e WHERE {condition} ORDER BY id")).unwrap();            statement.query_map([], |row| row.get(0)).unwrap().map(Result::unwrap).collect()        };        let (live_ids, binned_ids, unread_ids, read_ids, archived_ids) = (ids(EMAILS, live("e.")), ids(EMAILS, binned("e.")), ids(EMAILS, unread("e.")), ids(EMAILS, read("e.")), ids(EMAILS, archived("e.")));        for m in mails {            let id = m["id"].as_str().unwrap().to_string();            let expect = &m["expect"];            let state = match (live_ids.contains(&id), binned_ids.contains(&id)) {                (true, false) => "live",                (false, true) => "binned",                (false, false) => "waiting",                (true, true) => panic!("{name}: {id} is both live and binned"),            };            assert_eq!(state, expect["state"].as_str().unwrap(), "{name}: {id}");            let is_unread = match (unread_ids.contains(&id), read_ids.contains(&id)) {                (true, false) => Some(true),                (false, true) => Some(false),                (false, false) => None,                (true, true) => panic!("{name}: {id} is both read and unread"),            };            assert_eq!(is_unread, expect["unread"].as_bool(), "{name}: {id} unread");            assert_eq!(archived_ids.contains(&id), expect["archived"] == true, "{name}: {id} archived");            let at: Option<String> = db.query_row(&format!("SELECT {} FROM {EMAILS} e WHERE e.id = ?", binned_at("e.")), [&id], |row| row.get(0)).unwrap_or(None);            assert_eq!(at, s(&expect["binned_at"]), "{name}: {id} binned_at");        }        let (live_threads, binned_threads) = (ids("cotton_email_threads", live_thread("e.")), ids("cotton_email_threads", binned_thread("e.")));        for t in case["threads"].as_array().into_iter().flatten() {            let id = t["id"].as_str().unwrap().to_string();            let state = match (live_threads.contains(&id), binned_threads.contains(&id)) {                (true, false) => "live",                (false, true) => "binned",                (false, false) => "waiting",                (true, true) => panic!("{name}: thread {id} is both"),            };            assert_eq!(state, t["state"].as_str().unwrap(), "{name}: thread {id}");        }    }}/// RULES 2, 5 and 8: one normaliser for keys, one shape for times, who stamps `at`, and which keys are refused, the/// same answers the mirror gives.#[test]fn keys_times_and_the_cut_moment_answer_the_shared_cases() {    let file = cases();    for k in file["keys"].as_array().unwrap() {        assert_eq!(normalise_key(k[0].as_str().unwrap()), k[1].as_str().unwrap(), "{k}");    }    for k in file["refused_keys"].as_array().unwrap() {        assert_eq!(refused_key(k[0].as_str().unwrap()), k[1].as_str(), "{k}");    }    for t in file["times"].as_array().unwrap() {        assert_eq!(normalise_time(t[0].as_str().unwrap()), s(&t[1]), "{t}");    }    for c in file["cut_at"].as_array().unwrap() {        let shown: Vec<Option<&str>> = c["shown_landed"].as_array().unwrap().iter().map(Value::as_str).collect();        assert_eq!(cut_at(shown), s(&c["at"]), "{c}");    }    for c in file["check_cut_at"].as_array().unwrap() {        assert_eq!(check_cut_at(c["at"].as_str().unwrap(), c["newest_known"].as_str()), c["refused"].as_str(), "{c}");    }    assert!(public_domains().iter().all(|d| normalise_key(d) == *d && !d.starts_with('@')));    // By the registrable suffix: a name under a public domain is public; a lookalike is not.    assert!(is_public_domain("mail.yahoo.co.uk") && is_public_domain("gmail.com"));    assert!(!is_public_domain("notgmail.com") && !is_public_domain("gmail.com.invented.example"));}/// RULE 8: what the mail decoder writes as `sent_at` is already in the one shape.#[test]fn the_decoders_sent_at_is_pinned() {    for ms in [0_i64, 1_764_000_000_123, 1_764_000_000_000] {        let text = crate::js::to_iso_string(ms).unwrap();        assert!(is_pinned(&text), "{text}");    }}/// RULE (schema 157): `_mail_cuts` follows the kit's cut tables: a cut made is there, a changed `except` follows, a/// row still sealed (no key yet) is not a cut until it opens, and Undo (a deleted row, or the row gone) takes it out.#[test]fn the_cuts_table_follows_the_kits_cut_tables() {    let db = connection();    let held = || -> Vec<(String, String, Option<String>)> {        let mut s = db.prepare(&format!("SELECT kind, id, \"except\" FROM {CUTS} ORDER BY kind, id")).unwrap();        s.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))).unwrap().map(Result::unwrap).collect()    };    db.execute(&format!("INSERT INTO {BIN_TABLE} VALUES ('c-1', 'ada@example.test', '2026-11-20T10:00:00.000Z', '2026-11-20T10:00:00.000Z', NULL, NULL, '2026-11-20T10:00:00.000Z', 'live')"), []).unwrap();    db.execute(&format!("INSERT INTO {READ_TABLE} VALUES ('c-2', NULL, NULL, NULL, NULL, NULL, NULL, NULL)"), []).unwrap();    assert_eq!(held(), [("bin".to_string(), "c-1".to_string(), None)], "a sealed row is not a cut yet");    db.execute(&format!("UPDATE {READ_TABLE} SET \"key\" = '*', \"before\" = '2026-11-20T10:00:00.000Z', \"at\" = '2026-11-20T10:00:00.000Z', made_at = '2026-11-20T10:00:00.000Z' WHERE id = 'c-2'"), []).unwrap();    db.execute(&format!("UPDATE {BIN_TABLE} SET \"except\" = '[\"m-1\"]' WHERE id = 'c-1'"), []).unwrap();    assert_eq!(held(), [("bin".to_string(), "c-1".to_string(), Some("[\"m-1\"]".to_string())), ("read".to_string(), "c-2".to_string(), None)]);    db.execute(&format!("UPDATE {BIN_TABLE} SET deleted_at = '2026-11-20T10:00:05.000Z' WHERE id = 'c-1'"), []).unwrap();    db.execute(&format!("DELETE FROM {READ_TABLE} WHERE id = 'c-2'"), []).unwrap();    assert!(held().is_empty(), "Undo takes the cut out");}