Cotton code
712 lines · 25.9 KB · RustRaw
//! `packages/core/__tests__/messages/resolveContact.test.ts`, case for case.//!//! One handle in, one contact out (schema v36, spec//! 2026-09-05-mac-ingest-messages-calls-design §D4).//!//! The failure this guards is a conversation split in half: two contact rows for//! one human means two DM threads, in front of the person whose conversation it//! is. So the cases that matter are the ones where a second contact is TEMPTING —//! the same number spelled differently, an Apple ID email beside a number, a//! contact whose handle row has not landed yet, and a person who gains a second//! number later.//!//! The TypeScript drives a real SQLite file through the store's test harness.//! This crate opens no database, so the file below is a `FakeFile`: three vectors//! of rows behind [`ContactDriver`], plus the same `apply` the TypeScript's//! harness has — it folds the returned changes back in, so the next call sees//! them. Every number and address is invented//! [nothing-real-ever-goes-in-cotton-s-public-tree].use std::cell::RefCell;use super::*;use crate::change::OpKind;const WORKSPACE: &str = "ws-1";const NOW: &str = "2026-09-05T09:15:00.000Z";#[derive(Debug, Clone, Default)]struct FakeContact {    id: String,    phone_e164: Option<String>,    display_name: Option<String>,    person_id: Option<String>,    auth_user_id: Option<String>,}#[derive(Debug, Clone)]struct FakeHandle {    id: String,    contact_id: String,    kind: String,    value: String,}#[derive(Debug, Clone)]struct FakePerson {    id: String,    full_name: Option<String>,    phones: Vec<String>,    emails: Vec<String>,    instagram: Vec<String>,    archived: bool,}#[derive(Debug, Default)]struct FakeFile {    contacts: RefCell<Vec<FakeContact>>,    handles: RefCell<Vec<FakeHandle>>,    people: RefCell<Vec<FakePerson>>,    minted: RefCell<usize>,}impl ContactDriver for FakeFile {    fn people_handles(        &self,        workspace_id: &str,        kind: ContactHandleKind,    ) -> Result<Vec<PersonHandleRow>, ContactError> {        assert_eq!(workspace_id, WORKSPACE);        let mut rows = Vec::new();        for person in self.people.borrow().iter() {            if person.archived {                continue;            }            let values = match kind {                ContactHandleKind::Phone => &person.phones,                ContactHandleKind::Email => &person.emails,                ContactHandleKind::Instagram => &person.instagram,                _ => continue,            };            for value in values {                rows.push(PersonHandleRow {                    id: person.id.clone(),                    full_name: person.full_name.clone(),                    value: Some(value.clone()),                });            }        }        Ok(rows)    }    fn contact_by_handle(        &self,        workspace_id: &str,        handle: &ContactHandle,    ) -> Result<Option<ContactRow>, ContactError> {        assert_eq!(workspace_id, WORKSPACE);        let handles = self.handles.borrow();        let Some(row) = handles            .iter()            .find(|row| row.kind == handle.kind.as_str() && row.value == handle.value)        else {            return Ok(None);        };        Ok(self.contact_row(&row.contact_id))    }    fn contact_by_phone(        &self,        workspace_id: &str,        phone: &str,    ) -> Result<Option<ContactRow>, ContactError> {        assert_eq!(workspace_id, WORKSPACE);        let contacts = self.contacts.borrow();        Ok(contacts            .iter()            .find(|contact| contact.phone_e164.as_deref() == Some(phone))            .map(|contact| ContactRow {                id: contact.id.clone(),                display_name: contact.display_name.clone(),                person_id: contact.person_id.clone(),            }))    }}impl FakeFile {    fn contact_row(&self, id: &str) -> Option<ContactRow> {        self.contacts            .borrow()            .iter()            .find(|contact| contact.id == id)            .map(|contact| ContactRow {                id: contact.id.clone(),                display_name: contact.display_name.clone(),                person_id: contact.person_id.clone(),            })    }    fn contact(&self, id: &str) -> FakeContact {        self.contacts            .borrow()            .iter()            .find(|contact| contact.id == id)            .cloned()            .unwrap_or_else(|| panic!("no contact {id}"))    }    fn seed_contact(&self, contact: FakeContact) {        self.contacts.borrow_mut().push(contact);    }    fn seed_person(&self, id: &str, name: &str, phones: &[&str], emails: &[&str]) {        self.people.borrow_mut().push(FakePerson {            id: id.to_string(),            full_name: Some(name.to_string()),            phones: phones.iter().map(|value| value.to_string()).collect(),            emails: emails.iter().map(|value| value.to_string()).collect(),            instagram: Vec::new(),            archived: false,        });    }    fn seed_archived_person(&self, id: &str, name: &str, phones: &[&str]) {        self.people.borrow_mut().push(FakePerson {            id: id.to_string(),            full_name: Some(name.to_string()),            phones: phones.iter().map(|value| value.to_string()).collect(),            emails: Vec::new(),            instagram: Vec::new(),            archived: true,        });    }    /// The TypeScript harness's `apply`: fold what a resolution owed the file    /// back in, so the next call sees it.    fn apply(&self, changes: &[Change]) {        for change in changes {            let Some(patch) = change.patch.as_ref() else {                continue;            };            let text = |key: &str| patch.get(key).and_then(Value::as_str).map(str::to_string);            if change.table == "cotton_msg_contacts" {                let mut contacts = self.contacts.borrow_mut();                match contacts.iter_mut().find(|row| row.id == change.row_id) {                    Some(row) => {                        if patch.contains_key("display_name") {                            row.display_name = text("display_name");                        }                        if patch.contains_key("person_id") {                            row.person_id = text("person_id");                        }                        if patch.contains_key("phone_e164") {                            row.phone_e164 = text("phone_e164");                        }                    }                    None => contacts.push(FakeContact {                        id: change.row_id.clone(),                        phone_e164: text("phone_e164"),                        display_name: text("display_name"),                        person_id: text("person_id"),                        auth_user_id: text("auth_user_id"),                    }),                }            } else if change.table == "cotton_msg_contact_handles" {                let mut handles = self.handles.borrow_mut();                let row = FakeHandle {                    id: change.row_id.clone(),                    contact_id: text("contact_id").unwrap_or_default(),                    kind: text("kind").unwrap_or_default(),                    value: text("value").unwrap_or_default(),                };                match handles.iter_mut().find(|one| one.id == change.row_id) {                    Some(existing) => *existing = row,                    None => handles.push(row),                }            } else {                panic!("unexpected table {}", change.table);            }        }    }    /// `resolve` from the TypeScript: resolve, then apply.    fn resolve(        &self,        handle: &ContactHandle,        display_name: Option<&str>,        person_id: Option<&str>,    ) -> ResolvedContact {        let minted = &self.minted;        let mut new_id = || {            let mut count = minted.borrow_mut();            *count += 1;            format!("contact-{count}")        };        let result = resolve_contact(ResolveContactArgs {            db: self,            workspace_id: WORKSPACE,            namespace: WORKSPACE,            handle,            display_name,            person_id,            now: NOW,            new_id: &mut new_id,            people: None,        })        .expect("the fake file answers");        self.apply(&result.changes);        result    }}fn phone(value: &str) -> ContactHandle {    ContactHandle {        kind: ContactHandleKind::Phone,        value: value.to_string(),    }}/// As a caller passes it: through `normalize_contact_handle`, as the ingest does.fn instagram(value: &str) -> ContactHandle {    normalize_contact_handle(ContactHandleKind::Instagram, value).expect("an Instagram handle")}fn email(value: &str) -> ContactHandle {    ContactHandle {        kind: ContactHandleKind::Email,        value: value.to_string(),    }}// ── normalizeContactHandle ───────────────────────────────────────────────────#[test]fn turns_a_number_into_the_digits_phone_e164_holds_however_it_was_written() {    for raw in [        "+91 90000 00001",        "+919000000001",        "919000000001",        "91-900-000-0001",    ] {        assert_eq!(            normalize_contact_handle(ContactHandleKind::Phone, raw),            Some(phone("919000000001")),            "{raw}"        );    }    // Too short, too long, and not a number at all.    assert_eq!(        normalize_contact_handle(ContactHandleKind::Phone, "4321"),        None    );    assert_eq!(        normalize_contact_handle(ContactHandleKind::Phone, &"9".repeat(16)),        None    );    assert_eq!(        normalize_contact_handle(ContactHandleKind::Phone, "ravi"),        None    );}#[test]fn lower_cases_an_address_and_refuses_what_cannot_be_an_identity() {    assert_eq!(        normalize_contact_handle(ContactHandleKind::Email, "  Ravi@Example.COM "),        Some(email("ravi@example.com"))    );    for bad in [        "ravi-at-example.com",        "@example.com",        "ravi@",        "a@b@c",        "ravi @example.com",    ] {        assert_eq!(            normalize_contact_handle(ContactHandleKind::Email, bad),            None,            "{bad}"        );    }    // Not a deliverability check: an Apple ID nobody can write to is still an    // identity, and that is the question this answers.    assert_eq!(        normalize_contact_handle(ContactHandleKind::Email, "a@b"),        Some(email("a@b"))    );}// ── handleFrom / handlesFrom / requireHandle ─────────────────────────────────#[test]fn prefers_the_phone_and_keeps_the_email_as_a_second_handle() {    let source = ContactSource {        phone: Some("+91 90000 00001"),        email: Some("Ravi@Example.com"),    };    assert_eq!(handle_from(&source, None), Some(phone("919000000001")));    assert_eq!(        handles_from(&source, None),        vec![phone("919000000001"), email("ravi@example.com")]    );}#[test]fn falls_through_to_the_email_when_the_number_will_not_normalise() {    assert_eq!(        handle_from(&ContactSource {            phone: Some("4321"),            email: Some("ravi@example.com"),        }, None),        Some(email("ravi@example.com"))    );}#[test]fn refuses_loudly_when_a_batch_names_no_counterpart_at_all() {    assert_eq!(handle_from(&ContactSource::default(), None), None);    let refusal = require_handle(&ContactSource::default(), None).unwrap_err();    assert!(refusal.to_string().contains("no usable phone or email"));    assert_eq!(refusal.code(), "IMPORT_SHAPE");}// ── resolveContact ───────────────────────────────────────────────────────────#[test]fn creates_a_contact_for_a_phone_with_the_number_as_its_primary() {    let file = FakeFile::default();    let resolved = file.resolve(&phone("919000000001"), None, None);    assert!(resolved.created);    let contact = file.contact(&resolved.contact_id);    assert_eq!(contact.phone_e164.as_deref(), Some("919000000001"));    assert_eq!(contact.display_name, None);    assert_eq!(contact.person_id, None);    // Nobody verified anything.    assert_eq!(contact.auth_user_id, None);    let handles = file.handles.borrow();    assert_eq!(handles.len(), 1);    assert_eq!(        handles[0].id,        contact_handle_id(WORKSPACE, "phone", "919000000001")    );    assert_eq!(handles[0].kind, "phone");    assert_eq!(handles[0].value, "919000000001");    assert_eq!(handles[0].contact_id, resolved.contact_id);}/// The whole point of D4: an iMessage counterpart is an Apple ID, and inventing a/// number for them would put a fake handle in front of a real person.#[test]fn creates_a_contact_for_an_email_with_no_number_at_all() {    let file = FakeFile::default();    let resolved = file.resolve(&email("ravi@icloud.com"), None, None);    assert_eq!(file.contact(&resolved.contact_id).phone_e164, None);    let handles = file.handles.borrow();    assert_eq!(handles.len(), 1);    assert_eq!(handles[0].kind, "email");    assert_eq!(handles[0].value, "ravi@icloud.com");}#[test]fn returns_the_same_contact_the_second_time_and_mints_nothing() {    let file = FakeFile::default();    let first = file.resolve(&phone("919000000001"), None, None);    let second = file.resolve(&phone("919000000001"), None, None);    assert_eq!(second.contact_id, first.contact_id);    assert!(!second.created);    assert_eq!(file.contacts.borrow().len(), 1);}/// A contact written by a build older than v36, or by a device whose handle op is/// still in its outbox. Without the primary-phone fallback this mints a SECOND/// contact for a number the file already has.#[test]fn finds_a_contact_whose_handle_row_has_not_landed_yet_and_heals_the_file() {    let file = FakeFile::default();    file.seed_contact(FakeContact {        id: "legacy".to_string(),        phone_e164: Some("919000000001".to_string()),        display_name: Some("Ravi".to_string()),        ..FakeContact::default()    });    let resolved = file.resolve(&phone("919000000001"), None, None);    assert_eq!(resolved.contact_id, "legacy");    assert!(!resolved.created);    let handles = file.handles.borrow();    assert_eq!(handles.len(), 1);    assert_eq!(handles[0].contact_id, "legacy");}#[test]fn fills_a_name_and_a_person_only_where_the_file_has_none() {    let file = FakeFile::default();    file.seed_contact(FakeContact {        id: "named".to_string(),        phone_e164: Some("919000000001".to_string()),        display_name: Some("Ravi (work)".to_string()),        ..FakeContact::default()    });    file.seed_person("person-ravi", "Ravi Kumar", &["919000000001"], &[]);    file.resolve(&phone("919000000001"), Some("RAVI KUMAR \u{1f4f1}"), None);    let contact = file.contact("named");    // The owner-corrected name outranks whatever a source called them; the empty    // People link is filled from the address book.    assert_eq!(contact.display_name.as_deref(), Some("Ravi (work)"));    assert_eq!(contact.person_id.as_deref(), Some("person-ravi"));}#[test]fn matches_a_person_by_phone_and_by_email_and_takes_the_persons_name() {    let file = FakeFile::default();    file.seed_person(        "person-ravi",        "Ravi Kumar",        &["+91 90000 00001"],        &["Ravi@Example.com"],    );    let by_phone = file.resolve(&phone("919000000001"), None, None);    let by_email = file.resolve(&email("ravi@example.com"), None, None);    for id in [&by_phone.contact_id, &by_email.contact_id] {        let contact = file.contact(id);        assert_eq!(contact.person_id.as_deref(), Some("person-ravi"));        assert_eq!(contact.display_name.as_deref(), Some("Ravi Kumar"));    }    // TWO contacts, one person — which is exactly what the conversation grouping    // is for. Storage never merges them.    assert_ne!(by_email.contact_id, by_phone.contact_id);}#[test]fn takes_a_second_number_joining_the_same_person_later() {    let file = FakeFile::default();    // The person exists with one number; a conversation lands on it.    file.seed_person("person-ravi", "Ravi Kumar", &["919000000001"], &[]);    let first = file.resolve(&phone("919000000001"), None, None);    assert_eq!(        file.contact(&first.contact_id).person_id.as_deref(),        Some("person-ravi")    );    // Later they get a second number and the owner adds it to the person.    file.people.borrow_mut()[0]        .phones        .push("919000000002".to_string());    let second = file.resolve(&phone("919000000002"), None, None);    assert!(second.created);    assert_ne!(second.contact_id, first.contact_id);    // Resolved at READ time, so the new number claims the person with no backfill    // anywhere.    assert_eq!(        file.contact(&second.contact_id).person_id.as_deref(),        Some("person-ravi")    );}#[test]fn lets_the_callers_people_id_beat_the_address_book_match() {    let file = FakeFile::default();    file.seed_person("person-ravi", "Ravi Kumar", &["919000000001"], &[]);    file.seed_person("person-asha", "Asha", &[], &[]);    let resolved = file.resolve(&phone("919000000001"), None, Some("person-asha"));    assert_eq!(        file.contact(&resolved.contact_id).person_id.as_deref(),        Some("person-asha")    );}// ── peopleByHandle ───────────────────────────────────────────────────────────#[test]fn skips_an_archived_person_and_refuses_a_handle_two_people_claim() {    let file = FakeFile::default();    file.seed_person(        "person-ravi",        "Ravi",        &["919000000001", "919000000009"],        &[],    );    file.seed_person("person-asha", "Asha", &["919000000009"], &[]);    file.seed_archived_person("person-old", "Someone Archived", &["919000000003"]);    let people = people_by_handle(&file, WORKSPACE).expect("the fake file answers");    assert_eq!(        people            .get("phone:919000000001")            .map(|person| person.id.as_str()),        Some("person-ravi")    );    // A number two people both claim resolves to NEITHER: attaching somebody's    // calls to the wrong human is worse than attaching them to nobody.    assert!(!people.contains_key("phone:919000000009"));    // An archived person must not be resurrected by a handle.    assert!(!people.contains_key("phone:919000000003"));}// ── contactHandleChanges ─────────────────────────────────────────────────────/// The import engine's case: a source hands over a number and an Apple ID for one/// person. Keeping only the one we keyed on would mean the next batch, carrying/// only the other, mints a second contact beside them.#[test]fn writes_a_second_handle_onto_a_contact_that_already_exists() {    let file = FakeFile::default();    let resolved = file.resolve(&phone("919000000001"), None, None);    let address = email("ravi@icloud.com");    let changes = contact_handle_changes(WORKSPACE, WORKSPACE, &resolved.contact_id, &address, NOW);    assert_eq!(changes.len(), 1);    // Derived from the natural key, so two devices recording the same address for    // the same person converge on ONE row rather than racing the UNIQUE.    assert_eq!(        changes[0].row_id,        contact_handle_id(WORKSPACE, "email", "ravi@icloud.com")    );    file.apply(&changes);    assert_eq!(        find_contact_by_handle(&file, WORKSPACE, &address)            .expect("the fake file answers")            .map(|contact| contact.id),        Some(resolved.contact_id.clone())    );    // The number stays the contact's PRIMARY phone — receipts, the guest path and    // the live socket all key on it.    assert_eq!(        file.contact(&resolved.contact_id).phone_e164.as_deref(),        Some("919000000001")    );}// ── the patches, key for key ─────────────────────────────────────────────────/// A patch is stored as JSON in the op log, so its key ORDER is observable — the/// workspace turns on serde_json's `preserve_order` for exactly this. These are/// the TypeScript object literals' own orders.#[test]fn the_patches_carry_the_typescripts_own_keys_in_the_typescripts_own_order() {    let file = FakeFile::default();    let resolved = file.resolve(&email("ravi@icloud.com"), Some("Ravi"), None);    assert_eq!(resolved.changes.len(), 2);    let contact = resolved.changes[0].patch.as_ref().expect("a patch");    let keys: Vec<&str> = contact.keys().map(String::as_str).collect();    assert_eq!(        keys,        [            "id",            "workspace_id",            "phone_e164",            "display_name",            "person_id",            "auth_user_id",            "vip",            "muted",            "blocked",            "created_at",            "updated_at",        ]    );    assert_eq!(contact.get("phone_e164"), Some(&Value::Null));    assert_eq!(contact.get("vip"), Some(&Value::Bool(false)));    let handle = resolved.changes[1].patch.as_ref().expect("a patch");    let keys: Vec<&str> = handle.keys().map(String::as_str).collect();    assert_eq!(        keys,        [            "id",            "workspace_id",            "contact_id",            "kind",            "value",            "created_at"        ]    );    assert_eq!(resolved.changes[1].kind, OpKind::Upsert);    assert_eq!(resolved.changes[1].table, "cotton_msg_contact_handles");}/// An existing contact with nothing to fill writes NO contact patch at all — an/// upsert of nothing is not a write, and a `updated_at` bump for no change would/// wake every other device's sync for nothing.#[test]fn an_existing_contact_with_nothing_to_fill_owes_only_its_handle_row() {    let file = FakeFile::default();    file.resolve(&phone("919000000001"), Some("Ravi"), None);    let again = file.resolve(&phone("919000000001"), Some("Ravi"), None);    assert_eq!(again.changes.len(), 1);    assert_eq!(again.changes[0].table, "cotton_msg_contact_handles");}// ── Node vectors ─────────────────────────────────────────────────────────────/// Printed by running the TypeScript (`vec_resolvecontact.ts`), pasted verbatim.////// The derived handle ids first: they are what two devices must agree on without/// talking, and the whole convergence argument rests on them being the same/// string on both sides.#[test]fn node_vectors_for_the_derived_handle_ids() {    assert_eq!(        contact_handle_id(WORKSPACE, "phone", "919000000001"),        "df194f37-68f1-2093-ac63-c37a25879b9d"    );    assert_eq!(        contact_handle_id(WORKSPACE, "email", "ravi@icloud.com"),        "1c8bbc3c-cd3b-7550-f3b2-07119febeb1d"    );}/// And the normalisation, where the two runtimes could most easily disagree: an/// ECMAScript `trim` takes a BOM off an address and leaves a NEL on, and/// `toLowerCase` is a full Unicode fold rather than an ASCII one.#[test]fn node_vectors_for_normalisation() {    assert_eq!(        normalize_contact_handle(ContactHandleKind::Email, "\u{feff}Ravi@Example.com\u{feff}"),        Some(email("ravi@example.com"))    );    // A NEL is NOT ECMAScript whitespace, so it is neither trimmed nor refused —    // it stays in the identity, which is the answer Node gives. Rust's own    // `str::trim` would have removed it and produced a different handle, and a    // different handle is a second contact for one human.    assert_eq!(        normalize_contact_handle(ContactHandleKind::Email, "\u{85}ravi@example.com"),        Some(email("\u{85}ravi@example.com"))    );    assert_eq!(        normalize_contact_handle(ContactHandleKind::Email, "RAVI\u{130}@example.com"),        Some(email("ravi\u{69}\u{307}@example.com"))    );    assert_eq!(        normalize_contact_handle(ContactHandleKind::Phone, "\u{feff}+91 (900) 000-0001."),        Some(phone("919000000001"))    );    assert_eq!(        normalize_contact_handle(ContactHandleKind::Phone, "\u{660}\u{661}919000000"),        None    );}// ── social handles (schema v90, one person across apps) ─────────────────────/// RULE: an Instagram sender nobody carries becomes a contact with no person — resolving it never writes or creates a cotton_people row.#[test]fn an_instagram_sender_nobody_carries_stays_unknown_and_makes_no_person() {    let file = FakeFile::default();    file.seed_person("person-asha", "Asha Verma", &["+91 90000 00002"], &[]);    let resolved = file.resolve(&instagram("@Night.Heron_77"), None, None);    assert!(resolved.created);    let contact = file.contact(&resolved.contact_id);    assert_eq!(contact.person_id, None);    assert_eq!(contact.phone_e164, None);    assert!(        resolved.changes.iter().all(|change| change.table != "cotton_people"),        "an unknown sender must never touch the people table"    );    assert_eq!(file.people.borrow().len(), 1);}/// RULE: an Instagram sender links to the one person who carries that handle, however the handle was spelled.#[test]fn an_instagram_sender_links_to_the_person_carrying_the_handle() {    let file = FakeFile::default();    file.seed_person("person-asha", "Asha Verma", &[], &[]);    file.people.borrow_mut()[0].instagram.push("night.heron_77".to_string());    let resolved = file.resolve(&instagram("https://www.instagram.com/Night.Heron_77/"), None, None);    let contact = file.contact(&resolved.contact_id);    assert_eq!(contact.person_id.as_deref(), Some("person-asha"));    // A handle is no phone: the contact carries no invented number.    assert_eq!(contact.phone_e164, None);}