//! A contact, found or made, from ONE way of reaching somebody (schema v36, spec //! 2026-09-05-mac-ingest-messages-calls-design §D4). //! //! The port of `packages/core/src/messages/resolveContact.ts`. //! //! Until v36 a contact WAS a phone: `cotton_msg_contacts.phone_e164`, NOT NULL //! and unique, and the import engine looked a counterpart up by it. An iMessage //! counterpart can be an Apple ID EMAIL, and one person reaches you from two //! numbers — so the ways of reaching a contact became rows //! (`cotton_msg_contact_handles`) and this module is the one place that turns a //! handle into a contact id. //! //! ONE FUNCTION, because two would eventually disagree, and here a disagreement //! is two contact rows for one human — which is two DM threads, which is a //! conversation split down the middle in front of the person whose conversation //! it is. //! //! The writes are RETURNED as changes, never applied — the import engine writes a //! thread, its participants and its messages in one batch, and a contact that //! landed while the batch it belongs to failed is a row nobody asked for. //! //! # What changed in the port, and why //! //! The TypeScript takes a `SqlDriver` and issues three statements against it. //! This crate opens no database, so the seam is [`ContactDriver`], a trait with //! one method per QUESTION rather than a general `all(sql, params)`: there are //! exactly three, they are fixed, and a domain-shaped trait means a server's //! implementation cannot accidentally send a different `WHERE`. The statements //! themselves are declared beside the phone's driver, in cotton-core's //! `messages::resolve_contact` (`people_handles_sql`, `CONTACT_BY_HANDLE_SQL`, //! `CONTACT_BY_PHONE_SQL`); the Worker's `import/reader.ts` asks the same //! questions of its object. Moved from cotton-core so the Worker runs this //! rule as WASM over a JS driver. use std::collections::BTreeMap; use serde_json::{Map, Value}; use crate::change::Change; use crate::ids::{contact_handle_id, msg_contact_handle_id, msg_contact_id}; pub use crate::phone::Region; use crate::messages::{js_trim, truthy_str}; const CONTACTS: &str = "cotton_msg_contacts"; const HANDLES: &str = "cotton_msg_contact_handles"; /// Mirrors `cotton_msg_contact_handles.kind` (less `cotton`): a phone, an /// email, and since v90 an Instagram, Facebook or LinkedIn handle — the same /// kinds a person carries in `cotton_person_handles`, so one enum serves both. pub use crate::handles::HandleKind as ContactHandleKind; pub use crate::handles::{ handle_from, handle_key, handles_from, normalize_contact_handle, normalize_contact_handle_in, require_handle, ContactHandle, ContactSource, NoUsableHandle, }; /// A person this file already knows, as the fold answers. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct MatchedPerson { pub id: String, pub full_name: Option, } /// One row of the people-by-handle read over `cotton_person_handles`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct PersonHandleRow { pub id: String, pub full_name: Option, /// `None` where the JSON array held something that is not a string — the /// TypeScript's `typeof row.value !== "string"`, which steps over the row. pub value: Option, } /// The three columns [`find_contact_by_handle`] reads. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] pub struct ContactRow { pub id: String, pub display_name: Option, pub person_id: Option, } /// Whatever the driver said. The TypeScript lets the exception through untouched; /// this carries its message so a handler can do the same. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] #[error("{0}")] pub struct ContactError(pub String); /// The three questions this module asks a file. /// /// One method per question rather than a general `all(sql, params)`: the /// statements are fixed and declared above, so an implementation runs them rather /// than composing its own — which is what stops a visibility filter (the archived /// person, the workspace) going missing in a second spelling. pub trait ContactDriver { /// `people_handles_sql` (cotton-core) for this kind, bound to `workspace_id`. fn people_handles( &self, workspace_id: &str, kind: ContactHandleKind, ) -> Result, ContactError>; /// `CONTACT_BY_HANDLE_SQL` (cotton-core). fn contact_by_handle( &self, workspace_id: &str, handle: &ContactHandle, ) -> Result, ContactError>; /// `CONTACT_BY_PHONE_SQL` (cotton-core). fn contact_by_phone( &self, workspace_id: &str, phone: &str, ) -> Result, ContactError>; } /// The people this file holds, by the handles they carry. /// /// A person's handles are rows of `cotton_person_handles` (v90), read here at /// READ time, so a person who gains a number or an Instagram handle tomorrow /// claims the calls and conversations that were already there, with no /// backfill. The rows are who(handle)'s (`cotton_store::protocol::who`, /// PEOPLE BUILD 1): a person or a handle in the bin names nobody, and an /// archived person is still who their handle names. /// /// Phones are normalised on the way out because an address book spells one number /// four ways, and emails are lower-cased for the same reason. Ambiguity loses: a /// handle two different people both claim resolves to NEITHER, because attaching /// somebody's calls to the wrong human is worse than attaching them to nobody. /// /// A `BTreeMap` rather than the TypeScript's insertion-ordered `Map`: only `get` /// and `has` are ever asked of it, so the order is not observable, and an ordered /// map keeps a test failure readable. pub fn people_by_handle( db: &D, workspace_id: &str, ) -> Result, ContactError> { // `None` in this map is the sentinel for "two people claim this handle", kept // so a third claimant cannot un-poison it. let mut claims: BTreeMap> = BTreeMap::new(); for kind in ContactHandleKind::ALL { for row in db.people_handles(workspace_id, kind)? { let Some(value) = row.value.as_deref() else { continue; }; let Some(handle) = normalize_contact_handle(kind, value) else { continue; }; let person = MatchedPerson { id: row.id.clone(), full_name: row.full_name.clone(), }; match claims.get(&handle_key(&handle)) { None => { claims.insert(handle_key(&handle), Some(person)); } Some(Some(seen)) if seen.id != person.id => { claims.insert(handle_key(&handle), None); } Some(_) => {} } } } Ok(claims .into_iter() .filter_map(|(key, person)| person.map(|person| (key, person))) .collect()) } /// The contact this handle already belongs to, or `None`. Reads only. pub fn find_contact_by_handle( db: &D, workspace_id: &str, handle: &ContactHandle, ) -> Result, ContactError> { if let Some(row) = db.contact_by_handle(workspace_id, handle)? { return Ok(Some(row)); } // The PRIMARY phone, second. A contact whose handle row has not landed yet — // one written by a build older than v36, or by a device whose handle op is // still in its outbox — is still that number's contact, and resolving it here // is what stops a second contact being minted beside it. The handle row is // then written by `resolve_contact`, so the fallback heals the file as it // reads it. if handle.kind != ContactHandleKind::Phone { return Ok(None); } db.contact_by_phone(workspace_id, &handle.value) } /// What a caller hands [`resolve_contact`]. pub struct ResolveContactArgs<'a, D: ContactDriver + ?Sized> { pub db: &'a D, pub workspace_id: &'a str, /// What a derived contact or handle id is made under — the open file's, /// which is not always `workspace_id` (a database made at the stop keeps /// the old file's ids). pub namespace: &'a str, pub handle: &'a ContactHandle, /// What the source called them. Never overwrites a name the file already has. pub display_name: Option<&'a str>, /// A People id the CALLER matched. Beats the handle match below. pub person_id: Option<&'a str>, /// ISO stamp for rows this creates — the batch's, never a fresh clock. pub now: &'a str, /// Mints an id for a row that has no derived one. `FnMut`, because a batch /// resolving forty counterparts asks for forty ids. pub new_id: &'a mut dyn FnMut() -> String, /// The people fold, when the caller already has it (a batch resolves many). pub people: Option<&'a BTreeMap>, } #[derive(Debug, Clone, PartialEq)] pub struct ResolvedContact { pub contact_id: String, /// The rows this resolution owes the file, in the order they must land. pub changes: Vec, pub created: bool, } fn upsert(table: &str, row_id: &str, patch: Map) -> Change { Change::upsert(table, row_id, patch) } /// Find or create the ONE contact reachable at this handle. /// /// The order is the whole rule: /// /// 1. the handle row, then the primary phone — an existing contact always wins, /// because minting a second one splits a conversation. /// 2. a name and a People link are filled only where the file HAS none. An /// owner-corrected name outranks whatever an export happened to call somebody, /// and a link the owner made outranks a match. /// 3. a new contact carries the handle as its PRIMARY phone when the handle is a /// phone, and no number at all when it is an email — the reason `phone_e164` /// became nullable. /// 4. the handle row itself, always, under its derived id, so two devices /// resolving the same number converge rather than racing the UNIQUE. /// /// A handle nobody claims and nobody named still becomes a contact: an /// unidentified number that sent forty messages is a real counterpart, and the /// person naming them later edits ONE row. /// /// Every patch below is built as a `serde_json::Map` in the TypeScript's own key /// ORDER: a patch is stored as JSON in the op log, so its key order is observable /// and the workspace enables serde_json's `preserve_order` for exactly this. pub fn resolve_contact( args: ResolveContactArgs<'_, D>, ) -> Result { let ResolveContactArgs { db, workspace_id, namespace, handle, display_name, person_id, now, new_id, people, } = args; let mut changes: Vec = Vec::new(); // `args.displayName?.trim() ? args.displayName.trim() : null` — a name that is // only whitespace is no name at all. let display_name = display_name .map(js_trim) .and_then(|name| truthy_str(Some(name))); let folded; let people = match people { Some(people) => people, None => { folded = people_by_handle(db, workspace_id)?; &folded } }; let matched = people.get(&handle_key(handle)); // `args.personId ?? matched?.id ?? null` — NULLISH coalescing, so a caller // that passed an id keeps it even where the fold found somebody else. let person_id = person_id.or_else(|| matched.map(|person| person.id.as_str())); if let Some(existing) = find_contact_by_handle(db, workspace_id, handle)? { let mut patch = Map::new(); if truthy_str(existing.display_name.as_deref()).is_none() { if let Some(display_name) = display_name { patch.insert("display_name".to_string(), Value::from(display_name)); } } if truthy_str(existing.person_id.as_deref()).is_none() { // `if (!existing.personId && personId)` — both sides truthiness, so a // blank id fills nothing rather than blanking a column. if let Some(person_id) = truthy_str(person_id) { patch.insert("person_id".to_string(), Value::from(person_id)); } } if !patch.is_empty() { // `{ ...patch, updated_at: now }` — `updated_at` last, and only when // something actually changed. An upsert of nothing is not a write. patch.insert("updated_at".to_string(), Value::from(now)); changes.push(upsert(CONTACTS, &existing.id, patch)); } changes.extend(contact_handle_changes( namespace, workspace_id, &existing.id, handle, now, )); return Ok(ResolvedContact { contact_id: existing.id, changes, created: false, }); } // DERIVED from (workspace, phone) when there IS a phone, because that is // `cotton_msg_contacts UNIQUE (workspace_id, phone_e164)` and two devices // that each met this number before they were joined have to be one contact // when the files merge. // // The honest limit: an EMAIL-ONLY contact has no phone, so its id is still // minted. That index does not bind it either — SQLite's UNIQUE lets any // number of NULLs through — so a merge leaves two contact rows whose ONE // derived handle row (`contact_handle_id`) points at whichever of them the // fold kept. The person merges them; nothing is lost and nothing is // rejected. // A social handle (v90) IS the sender's identity on that site — a sender // there has no phone — so its contact is derived from the handle and two // reads of one sender are one contact. let contact_id = match handle.kind { ContactHandleKind::Phone => msg_contact_id(namespace, &handle.value), ContactHandleKind::Email => new_id(), social => msg_contact_handle_id(namespace, social.as_str(), &handle.value), }; let mut patch = Map::new(); patch.insert("id".to_string(), Value::from(contact_id.as_str())); patch.insert("workspace_id".to_string(), Value::from(workspace_id)); // The handle IS the primary phone when it is one; an email-only contact has // no number, and inventing one would put a fake handle in front of a real // person. patch.insert( "phone_e164".to_string(), match handle.kind { ContactHandleKind::Phone => Value::from(handle.value.as_str()), _ => Value::Null, }, ); patch.insert( "display_name".to_string(), match display_name.or_else(|| matched.and_then(|person| person.full_name.as_deref())) { Some(name) => Value::from(name), None => Value::Null, }, ); patch.insert( "person_id".to_string(), match person_id { Some(id) => Value::from(id), None => Value::Null, }, ); // Nobody verified anything: an imported contact never gets an auth user. patch.insert("auth_user_id".to_string(), Value::Null); patch.insert("vip".to_string(), Value::Bool(false)); patch.insert("muted".to_string(), Value::Bool(false)); patch.insert("blocked".to_string(), Value::Bool(false)); patch.insert("created_at".to_string(), Value::from(now)); patch.insert("updated_at".to_string(), Value::from(now)); changes.push(upsert(CONTACTS, &contact_id, patch)); changes.extend(contact_handle_changes( namespace, workspace_id, &contact_id, handle, now, )); Ok(ResolvedContact { contact_id, changes, created: true, }) } /// The handle row, under its derived id. /// /// Emitted unconditionally — an upsert of a row that is already there is a no-op /// under LWW, and the alternative (reading first) would cost a query per /// counterpart on a batch that resolves hundreds of them. /// /// Exported because a caller that has ALREADY settled which contact a counterpart /// is needs to record the other handles that counterpart named, without /// re-deciding the contact — the import engine does exactly that when a source /// hands over a number and an Apple ID for one person. pub fn contact_handle_changes( namespace: &str, workspace_id: &str, contact_id: &str, handle: &ContactHandle, now: &str, ) -> Vec { let id = contact_handle_id(namespace, handle.kind.as_str(), &handle.value); let mut patch = Map::new(); patch.insert("id".to_string(), Value::from(id.as_str())); patch.insert("workspace_id".to_string(), Value::from(workspace_id)); patch.insert("contact_id".to_string(), Value::from(contact_id)); patch.insert("kind".to_string(), Value::from(handle.kind.as_str())); patch.insert("value".to_string(), Value::from(handle.value.as_str())); patch.insert("created_at".to_string(), Value::from(now)); vec![upsert(HANDLES, &id, patch)] } #[cfg(test)] #[path = "resolve_contact_tests.rs"] mod tests;