Cotton code
310 lines · 16.2 KB · RustRaw
use rusqlite::types::Value;use super::*;use crate::driver::Driver;use crate::test_support::{seeded_file, WORKSPACE};const AT: &str = "2026-11-27T10:00:00.000Z";fn text(s: &str) -> Value {    Value::Text(s.to_string())}fn person(db: &Driver, id: &str, name: &str) {    db.run(        "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)",        &[text(id), text(WORKSPACE), text(name), text(AT), text(AT)],    )    .unwrap();}fn handle(db: &Driver, id: &str, person: &str, kind: &str, raw: &str, normalised: &str) {    db.run(        "INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 'manual', ?, ?)",        &[text(id), text(WORKSPACE), text(person), text(kind), text(raw), text(normalised), text(AT), text(AT)],    )    .unwrap();}fn contact(db: &Driver, id: &str, phone: Option<&str>, linked: Option<&str>) {    db.run(        "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, person_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",        &[text(id), text(WORKSPACE), phone.map(text).unwrap_or(Value::Null), linked.map(text).unwrap_or(Value::Null), text(AT), text(AT)],    )    .unwrap();}fn contact_handle(db: &Driver, id: &str, contact: &str, kind: &str, value: &str) {    db.run(        "INSERT INTO cotton_msg_contact_handles (id, workspace_id, contact_id, kind, value, created_at) VALUES (?, ?, ?, ?, ?, ?)",        &[text(id), text(WORKSPACE), text(contact), text(kind), text(value), text(AT)],    )    .unwrap();}/// The kit's `shared_handle` as a kitted file lays it (a data-only kit table).fn lay_shared(db: &Driver) {    db.exec(&format!(        "CREATE TABLE IF NOT EXISTS {SHARED_TABLE} (id TEXT PRIMARY KEY, workspace_id TEXT, created_at TEXT, updated_at TEXT, deleted_at TEXT, record_byline TEXT, _hlc TEXT NOT NULL DEFAULT '', _born TEXT, person TEXT, kind TEXT, value TEXT, normalised TEXT, source TEXT)"    ))    .unwrap();}fn shared(db: &Driver, id: &str, person: &str, kind: &str, normalised: &str) {    db.run(        &format!("INSERT INTO {SHARED_TABLE} (id, workspace_id, person, kind, value, normalised, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),        &[text(id), text(WORKSPACE), text(person), text(kind), text(normalised), text(normalised), text(AT), text(AT)],    )    .unwrap();}fn file() -> Driver {    let db = seeded_file("phone-1");    lay_shared(&db);    db}fn who_is(db: &Driver, kind: HandleKind, raw: &str) -> Who {    match who_key(kind, raw, None) {        Some((kind, value)) => who(db, WORKSPACE, kind, &value).unwrap(),        None => Who::Nobody,    }}fn who_one(db: &Driver, kind: HandleKind, raw: &str) -> Option<String> {    who_is(db, kind, raw).one().map(|holder| holder.id.clone())}fn contact_person(db: &Driver, contact: &str) -> Option<String> {    db.get(&format!("SELECT {} AS person FROM cotton_msg_contacts c WHERE c.id = ?", contact_person_sql(shared_held(db), "c")), &[text(contact)])        .unwrap()        .and_then(|row| row.text("person").map(str::to_string))}/// RULE: who(handle) reads any spelling of a number or address through the/// one normaliser, names the living person holding it, and names nobody for/// an archived person (a recycled number), a person or a handle in the bin, or/// a value it cannot read.#[test]fn who_names_the_one_person_a_handle_belongs_to() {    let db = file();    person(&db, "p-asha", "Asha Menon");    handle(&db, "h-1", "p-asha", "phone", "+91 98765 43210", "919876543210");    handle(&db, "h-2", "p-asha", "email", "Asha@Example.com", "asha@example.com");    handle(&db, "h-3", "p-asha", "phone", "100", "100");    assert_eq!(who_one(&db, HandleKind::Phone, "0091 98765-43210").as_deref(), Some("p-asha"));    assert_eq!(who_one(&db, HandleKind::Email, " ASHA@example.com ").as_deref(), Some("p-asha"));    assert_eq!(who_is(&db, HandleKind::Phone, "100"), Who::Nobody, "a kept short code names nobody");    db.exec("UPDATE cotton_person_handles SET trashed_at = '2026-11-02T00:00:00.000Z' WHERE id = 'h-1'").unwrap();    assert_eq!(who_is(&db, HandleKind::Phone, "+919876543210"), Who::Nobody, "a binned handle names nobody");    db.exec("UPDATE cotton_people SET archived_at = '2026-11-01T00:00:00.000Z' WHERE id = 'p-asha'").unwrap();    assert_eq!(who_is(&db, HandleKind::Email, "asha@example.com"), Who::Nobody, "an archived contact answers for no number");    db.exec("UPDATE cotton_people SET archived_at = NULL, trashed_at = '2026-11-02T00:00:00.000Z' WHERE id = 'p-asha'").unwrap();    assert_eq!(who_is(&db, HandleKind::Email, "asha@example.com"), Who::Nobody, "a binned person is nobody");}/// RULE (PEOPLE BUILD 1b): a handle more than one living contact holds is/// shared: who answers every holder by name, a chat from it names nobody as/// if certain (whatever it was linked to), and its title is both names. A/// shared office line is the same; a recycled number whose old holder is/// archived is the new holder's alone.#[test]fn a_shared_landline_names_both_never_the_first() {    let db = file();    person(&db, "p-dad", "Dad");    person(&db, "p-mom", "Mom");    handle(&db, "h-l", "p-dad", "phone", "+44 20 7946 0001", "442079460001");    shared(&db, "s-l", "p-mom", "phone", "442079460001");    match who_is(&db, HandleKind::Phone, "+442079460001") {        Who::Shared(holders) => assert_eq!(holders.iter().map(|h| h.id.as_str()).collect::<Vec<_>>(), ["p-dad", "p-mom"]),        other => panic!("the landline is shared: {other:?}"),    }    contact(&db, "c-l", Some("442079460001"), Some("p-dad"));    assert_eq!(contact_person(&db, "c-l"), None, "never Dad as if certain, even linked to him before");    let names = db        .get(&format!("SELECT {} AS names FROM cotton_msg_contacts c WHERE c.id = 'c-l'", contact_shared_names_sql(true, "c")), &[])        .unwrap()        .and_then(|row| row.text("names").map(str::to_string));    assert_eq!(names.as_deref(), Some("Dad & Mom"));    // Mom archived: the landline is Dad's alone again.    db.exec("UPDATE cotton_people SET archived_at = '2026-11-01T00:00:00.000Z' WHERE id = 'p-mom'").unwrap();    assert_eq!(who_one(&db, HandleKind::Phone, "+442079460001").as_deref(), Some("p-dad"));    // A recycled number: the old holder archived, the new one sharing it.    person(&db, "p-old", "Old Holder");    person(&db, "p-new", "New Holder");    handle(&db, "h-r", "p-old", "phone", "+44 7700 900777", "447700900777");    shared(&db, "s-r", "p-new", "phone", "447700900777");    db.exec("UPDATE cotton_people SET archived_at = '2026-10-01T00:00:00.000Z' WHERE id = 'p-old'").unwrap();    assert_eq!(who_one(&db, HandleKind::Phone, "+447700900777").as_deref(), Some("p-new"));    contact(&db, "c-r", Some("447700900777"), Some("p-old"));    assert_eq!(contact_person(&db, "c-r").as_deref(), Some("p-new"), "the number's living holder, not the old link");}/// RULE: a chat contact's person is derived at read time: a person who gains/// the number later names the contact already there; handles naming two/// people name nobody; a hand link stands only while nothing better is known/// and the person is not in the bin.#[test]fn a_contact_person_is_derived_and_heals_without_a_write() {    let db = file();    contact(&db, "c-1", Some("919876543210"), None);    assert_eq!(contact_person(&db, "c-1"), None);    person(&db, "p-asha", "Asha Menon");    handle(&db, "h-1", "p-asha", "phone", "+91 98765 43210", "919876543210");    assert_eq!(contact_person(&db, "c-1").as_deref(), Some("p-asha"), "the number added later names the old contact");    // A contact with no number, reached by an email and an Instagram name.    contact(&db, "c-2", None, None);    contact_handle(&db, "ch-1", "c-2", "email", "ravi@example.com");    contact_handle(&db, "ch-2", "c-2", "instagram", "ravi.s");    person(&db, "p-ravi", "Ravi");    handle(&db, "h-2", "p-ravi", "email", "ravi@example.com", "ravi@example.com");    assert_eq!(contact_person(&db, "c-2").as_deref(), Some("p-ravi"));    person(&db, "p-other", "Someone else");    handle(&db, "h-3", "p-other", "instagram", "ravi.s", "ravi.s");    assert_eq!(contact_person(&db, "c-2"), None, "two people: nobody");    // Linked by hand, nothing else known.    person(&db, "p-kabir", "Kabir");    contact(&db, "c-3", Some("447700900123"), Some("p-kabir"));    assert_eq!(contact_person(&db, "c-3").as_deref(), Some("p-kabir"));    db.exec("UPDATE cotton_people SET trashed_at = '2026-11-02T00:00:00.000Z' WHERE id = 'p-kabir'").unwrap();    assert_eq!(contact_person(&db, "c-3"), None);}/// RULE (PEOPLE BUILD 1b, review LOW): the derived person is cheap at his size: 1,500 people holding 3,000 numbers,/// 1,000 chat contacts (each a number and a handle), fifty shared landlines. The chat list (every contact's person),/// one person's chats (a filter over the derived person) and the activity read (400 people at a time) each stay/// well under a frame budget in a debug build.#[test]fn the_derived_person_is_cheap_at_his_size() {    let db = file();    db.exec(&format!("CREATE INDEX IF NOT EXISTS idx_shared_normalised ON {SHARED_TABLE} (normalised)")).unwrap();    db.exec("BEGIN").unwrap();    for p in 0..1500 {        person(&db, &format!("p-{p}"), &format!("Person {p}"));        handle(&db, &format!("h-{p}-a"), &format!("p-{p}"), "phone", "x", &format!("4477009{p:05}"));        handle(&db, &format!("h-{p}-b"), &format!("p-{p}"), "phone", "x", &format!("4479009{p:05}"));    }    for s in 0..50 {        shared(&db, &format!("s-{s}"), &format!("p-{}", 1499 - s), "phone", &format!("4477009{s:05}"));    }    for c in 0..1000 {        contact(&db, &format!("c-{c}"), Some(&format!("4477009{c:05}")), None);        contact_handle(&db, &format!("ch-{c}"), &format!("c-{c}"), "phone", &format!("4479009{c:05}"));    }    db.exec("COMMIT").unwrap();    let person_sql = contact_person_sql(true, "c");    let started = std::time::Instant::now();    let all = db.all(&format!("SELECT c.id, {person_sql} AS person FROM cotton_msg_contacts c"), &[]).unwrap();    let list = started.elapsed();    assert_eq!(all.len(), 1000);    assert_eq!(all.iter().filter(|row| row.text("person").is_none()).count(), 50, "the fifty shared landlines name nobody");    let started = std::time::Instant::now();    let mine = db.all(&format!("SELECT c.id FROM cotton_msg_contacts c WHERE {person_sql} = 'p-700'"), &[]).unwrap();    let one = started.elapsed();    assert_eq!(mine.len(), 1);    let ids: Vec<String> = (0..400).map(|p| format!("p-{p}")).collect();    let marks = vec!["?"; ids.len()].join(",");    let started = std::time::Instant::now();    let active = db        .all(&format!("SELECT person FROM (SELECT {person_sql} AS person FROM cotton_msg_contacts c) WHERE person IN ({marks})"), &ids.iter().map(|id| text(id)).collect::<Vec<_>>())        .unwrap();    let activity = started.elapsed();    assert_eq!(active.len(), 350, "four hundred people, fifty of whose numbers are shared");    eprintln!("derived person at his size: list {list:?}, one person {one:?}, activity {activity:?}");    for (what, took) in [("list", list), ("one person", one), ("activity", activity)] {        assert!(took < std::time::Duration::from_millis(400), "{what} took {took:?}");    }}/// RULE (PEOPLE BUILD 1b, review M2): one answer everywhere. No code reads the person a chat contact was linked to/// when it was made (`cotton_msg_contacts.person_id`, the Mac copy's `message_contact` `$.person_id`): every reader/// asks [`contact_person_sql`] (or the Mac copy's `contact_person`, the same rule). The only reads of the stored link/// are the rule's own hand-link fallback, spelled through its `{c}` alias and so never matched here.#[test]fn no_reader_takes_a_chat_contacts_stored_person() {    let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).parent().expect("the crates");    let mut offenders = Vec::new();    let mut read = 0;    let mut stack = vec![crates.to_path_buf()];    while let Some(dir) = stack.pop() {        for entry in std::fs::read_dir(&dir).expect("a folder") {            let path = entry.expect("an entry").path();            let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default().to_string();            if path.is_dir() {                if !["target", "tests", "fixtures", "node_modules"].contains(&name.as_str()) && !name.starts_with('.') {                    stack.push(path);                }                continue;            }            if !name.ends_with(".rs") || name.ends_with("_tests.rs") || name == "tests.rs" || !path.components().any(|c| c.as_os_str() == "src") {                continue;            }            let source = std::fs::read_to_string(&path).expect("the source");            read += 1;            // The aliases this file gives a chat contact: `cotton_msg_contacts c`, and the Mac copy's            // `c.table_id = 'message_contact'`.            let mut aliases: Vec<String> = Vec::new();            // A select naming the table with no alias (`FROM {CONTACTS} WHERE …`, `FROM cotton_msg_contacts WHERE …`)            // reads the stored link as a bare `person_id`.            for line in source.lines() {                for table in ["FROM {CONTACTS} WHERE", "FROM cotton_msg_contacts WHERE", "FROM cotton_msg_contacts\n"] {                    if line.contains(table) && line.contains("SELECT") && line.split(table).next().is_some_and(|select| select.contains("person_id")) {                        offenders.push(format!("{}: {}", path.strip_prefix(crates).unwrap_or(&path).display(), line.trim()));                    }                }            }            for (marker, after) in [("cotton_msg_contacts ", true), (".table_id = 'message_contact'", false)] {                for (at, _) in source.match_indices(marker) {                    let alias: String = if after {                        let rest = source[at + marker.len()..].trim_start_matches("AS ");                        rest.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect()                    } else {                        source[..at].chars().rev().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect::<Vec<_>>().into_iter().rev().collect()                    };                    let keyword = ["WHERE", "ON", "JOIN", "SET", "AS", "LEFT", "ORDER", "GROUP", "LIMIT", "INNER", "USING"].contains(&alias.to_uppercase().as_str());                    if !alias.is_empty() && !keyword && alias.len() <= 8 && !aliases.contains(&alias) {                        aliases.push(alias);                    }                }            }            for (number, line) in source.lines().enumerate() {                let trimmed = line.trim_start();                if trimmed.starts_with("//") || trimmed.starts_with("assert") {                    continue;                }                for alias in &aliases {                    let column = format!("{alias}.person_id");                    let json = format!("json_extract({alias}.data, '$.person_id')");                    let hit = line.match_indices(&column).any(|(at, _)| !line[..at].ends_with(|c: char| c.is_ascii_alphanumeric() || c == '_'));                    if hit || line.contains(&json) {                        offenders.push(format!("{}:{}: {}", path.strip_prefix(crates).unwrap_or(&path).display(), number + 1, trimmed));                    }                }            }        }    }    assert!(read > 500, "the crates were read: {read}");    assert!(offenders.is_empty(), "these read a chat contact's stored person; ask contact_person_sql:\n{}", offenders.join("\n"));}/// RULE (PEOPLE BUILD 1b): a copy that does not hold the kit's `shared_handle` holds no shared handle, and every/// statement reads it only where it is: who and a contact's person still answer there.#[test]fn a_copy_without_the_shared_table_still_answers_who() {    let db = seeded_file("phone-1");    assert!(!shared_held(&db));    person(&db, "p-asha", "Asha Menon");    handle(&db, "h-1", "p-asha", "phone", "+91 98765 43210", "919876543210");    assert_eq!(who_one(&db, HandleKind::Phone, "+919876543210").as_deref(), Some("p-asha"));    contact(&db, "c-1", Some("919876543210"), None);    assert_eq!(contact_person(&db, "c-1").as_deref(), Some("p-asha"));    lay_shared(&db);    assert!(shared_held(&db));}