Cotton code
626 lines · 24.4 KB · RustRaw
//! Contact sync — the rules. The port of `packages/core/src/engine/contactSync.ts`//! (spec `2026-08-25-cotton-contact-sync-design.md` §3, §4).//!//! **Pure.** Given a linked person as Cotton holds them, what the phone shows//! now, and what the phone showed last time (the snapshot), decide what//! changes — without touching a database, the address book or a file. The//! app's runner reads and writes; this file only decides, which is what lets//! every row of the spec's tables be a unit test.//!//! The one idea: a snapshot lets us tell a PHONE edit from a COTTON edit.//!//! ```text//!   phone  ≠ snapshot → the phone changed since we last looked//!   cotton ≠ snapshot → Cotton holds something the phone did not give it//! ```//!//! A phone change flows in only when Cotton is untouched; when both moved,//! Cotton wins (the divergence stays until the mirror, §7, pushes it back).//! With no snapshot yet — a person imported before v8 — the phone fills EMPTY//! fields only.use cotton_store::protocol::js::is_js_whitespace;use serde::{Deserialize, Serialize};/// `PersonBirthday` — month 1–12, day 1–31, and the year when the person said.////// The components are `i64`, not `f64` like the media engine's dimensions,/// because a snapshot is WRITTEN BACK as JSON into the owner's file: serde/// prints an `f64` 1 as `1.0` where `JSON.stringify` prints `1`, and a/// snapshot that differs from the TypeScript's by two characters is a/// byte-equality comparison (`snapshots_equal`) that never agrees again. A/// fractional component is a malformed row, and refusing to read one is/// better than silently rewriting everybody's.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pub struct PersonBirthday {    /// 1–12.    pub month: i64,    /// 1–31.    pub day: i64,    /// Known birth year, or `None` when the person never said.    ///    /// `#[serde(default)]` because the phone's mapper omits the key entirely    /// when the person never said — `{ month: 3, day: 14 }` is a birthday the    /// TypeScript reads and canonicalises to `year: null`.    #[serde(default)]    pub year: Option<i64>,}/// One address-book contact as the People tool reads it.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct DeviceContact {    /// Stable per-device contact id — the idempotent re-import key.    pub device_contact_id: String,    pub full_name: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub phones: Option<Vec<String>>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub emails: Option<Vec<String>>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub org: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub role_title: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub city: Option<String>,    /// Month 1–12, which is what the Swift importer's `DateComponents.month`    /// already gives it    /// (`apps/cotton/Sources/CottonUI/Screens/Day/People/PeopleImportSheet.swift`).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub birthday: Option<PersonBirthday>,    /// Whether the address book holds a photo for this contact.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub image_available: Option<bool>,}/// What the phone last showed for a linked person — the contact-sync rules'/// memory (spec §3). Written only when it changed, so a daily refresh over/// thousands of unchanged people queues no op.////// `photo_sha` is the digest of the RAW thumbnail bytes (stable across runs/// for an unchanged photo; a re-encode is not). `avatar_key` is the key Cotton/// minted FROM the phone's photo, the last time it did — how the rules tell/// "this photo came from the phone" from "the owner picked their own". It is/// not cleared when the phone's photo goes away.////// The field ORDER is the TypeScript's, and it is load-bearing:/// `snapshots_equal` is a byte comparison of the serialised form.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct DeviceContactSnapshot {    /// Always 1. Carried as a number so the JSON says `"v":1`.    pub v: i64,    /// Every field is `#[serde(default)]`, and that is the TypeScript's own    /// defence written into the type: `parseDeviceContactSnapshot` checks only    /// `v === 1` and casts, so a row written by another version can reach the    /// rules missing a list. Canonicalising a missing list to an empty one is    /// what lets the rules DECIDE on such a row rather than compare against    /// `undefined`.    #[serde(default)]    pub full_name: String,    #[serde(default)]    pub phones: Vec<String>,    #[serde(default)]    pub emails: Vec<String>,    #[serde(default)]    pub org: Option<String>,    #[serde(default)]    pub role_title: Option<String>,    #[serde(default)]    pub city: Option<String>,    #[serde(default)]    pub birthday: Option<PersonBirthday>,    #[serde(default)]    pub photo_sha: Option<String>,    #[serde(default)]    pub avatar_key: Option<String>,}/// The person as these rules read them — the TypeScript's/// `Pick<IPerson, ContactFieldName | …>`, spelled as a struct because Rust has/// no structural subtyping. A caller keeps its own row type and builds one of/// these at its own boundary.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ContactPerson {    pub id: String,    pub full_name: String,    pub phones: Vec<String>,    pub emails: Vec<String>,    pub org: Option<String>,    pub role_title: Option<String>,    pub city: Option<String>,    pub birthday: Option<PersonBirthday>,    /// `null` for a hand-made person the address book knows nothing about.    pub device_contact_id: Option<String>,    pub device_contact_snapshot: Option<DeviceContactSnapshot>,    pub archived_at: Option<String>,    pub avatar_key: Option<String>,}/// The address-book subset, canonical: trimmed, de-duplicated, `None` for/// empty.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ContactFields {    pub full_name: String,    pub phones: Vec<String>,    pub emails: Vec<String>,    pub org: Option<String>,    pub role_title: Option<String>,    pub city: Option<String>,    pub birthday: Option<PersonBirthday>,}/// Every field the rules walk.////// The TypeScript derives this list from a map that/// `satisfies Record<ContactFieldName, true>`, so a field left out fails to/// COMPILE — a field the phone could never update, silently. Rust gets the/// same guarantee from the `match`es below being exhaustive over this enum.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub enum ContactFieldName {    FullName,    Phones,    Emails,    Org,    RoleTitle,    City,    Birthday,}impl ContactFieldName {    /// In the TypeScript's declared order — the order `plan_fields` walks and    /// the order a patch's keys come out in.    pub const ALL: [ContactFieldName; 7] = [        ContactFieldName::FullName,        ContactFieldName::Phones,        ContactFieldName::Emails,        ContactFieldName::Org,        ContactFieldName::RoleTitle,        ContactFieldName::City,        ContactFieldName::Birthday,    ];    pub const fn as_str(self) -> &'static str {        match self {            ContactFieldName::FullName => "fullName",            ContactFieldName::Phones => "phones",            ContactFieldName::Emails => "emails",            ContactFieldName::Org => "org",            ContactFieldName::RoleTitle => "roleTitle",            ContactFieldName::City => "city",            ContactFieldName::Birthday => "birthday",        }    }}/// One field's value, whatever its type — the TypeScript's/// `ContactFields[ContactFieldName]` union, which Rust needs a name for.#[derive(Debug, Clone, PartialEq)]pub enum FieldValue {    Text(String),    List(Vec<String>),    OptText(Option<String>),    Birthday(Option<PersonBirthday>),}impl FieldValue {    /// `isEmpty` — null, the empty list, or the empty string.    pub fn is_empty(&self) -> bool {        match self {            FieldValue::Text(value) => value.is_empty(),            FieldValue::List(values) => values.is_empty(),            FieldValue::OptText(value) => match value {                None => true,                Some(value) => value.is_empty(),            },            FieldValue::Birthday(value) => value.is_none(),        }    }}/// Value equality for one field — a list IN ORDER, a birthday as its triple.////// ORDER IS CONTENT: `["+91 2", "+91 1"]` is not `["+91 1", "+91 2"]`. §4.1/// keeps the phone's order and the first number is the primary one, so a list/// the owner reordered on the phone is a change the rules adopt like any/// other.////// The TypeScript compares `JSON.stringify(a ?? null)` against the same of/// `b`; in Rust the derived structural equality says the same thing, because/// every value here has already been through the canonicalisers (which fix a/// birthday's key order) and `null` and `undefined` are one shape.pub fn field_equal(a: &FieldValue, b: &FieldValue) -> bool {    a == b}impl ContactFields {    /// Read one field out — the TypeScript's `fields[field]`.    pub fn get(&self, field: ContactFieldName) -> FieldValue {        match field {            ContactFieldName::FullName => FieldValue::Text(self.full_name.clone()),            ContactFieldName::Phones => FieldValue::List(self.phones.clone()),            ContactFieldName::Emails => FieldValue::List(self.emails.clone()),            ContactFieldName::Org => FieldValue::OptText(self.org.clone()),            ContactFieldName::RoleTitle => FieldValue::OptText(self.role_title.clone()),            ContactFieldName::City => FieldValue::OptText(self.city.clone()),            ContactFieldName::Birthday => FieldValue::Birthday(self.birthday),        }    }}/// `String.prototype.trim`, which is NOT `str::trim`.////// The two whitespace sets differ at both ends: JavaScript trims U+FEFF (a/// BOM pasted in front of a phone number from a spreadsheet) and Rust does/// not, while Rust trims U+0085 (NEL) and JavaScript does not. Both are pinned/// by Node vector, because this trim decides whether a field counts as EMPTY —/// and an empty field is the one the pull is allowed to fill.fn js_trim(value: &str) -> &str {    value.trim_matches(is_js_whitespace)}/// `text` — trim, and the empty string becomes `None`.fn text(value: Option<&str>) -> Option<String> {    let trimmed = value.map(js_trim).unwrap_or("");    if trimmed.is_empty() {        None    } else {        Some(trimmed.to_string())    }}/// `list` — trim each, drop the blanks, keep the first of any duplicate, and/// keep the ORDER.fn list(values: Option<&[String]>) -> Vec<String> {    let mut out: Vec<String> = Vec::new();    for value in values.unwrap_or(&[]) {        let trimmed = js_trim(value);        if !trimmed.is_empty() && !out.iter().any(|kept| kept == trimmed) {            out.push(trimmed.to_string());        }    }    out}/// `birthday` — rebuilt in one key order, with a missing year as `null`.fn birthday(value: Option<PersonBirthday>) -> Option<PersonBirthday> {    value.map(|value| PersonBirthday {        month: value.month,        day: value.day,        year: value.year,    })}/// What the phone shows, canonical.pub fn contact_fields(contact: &DeviceContact) -> ContactFields {    ContactFields {        full_name: js_trim(&contact.full_name).to_string(),        phones: list(contact.phones.as_deref()),        emails: list(contact.emails.as_deref()),        org: text(contact.org.as_deref()),        role_title: text(contact.role_title.as_deref()),        city: text(contact.city.as_deref()),        birthday: birthday(contact.birthday),    }}/// What Cotton holds, canonical — the same shape, so the two compare.pub fn person_fields(person: &ContactPerson) -> ContactFields {    ContactFields {        full_name: js_trim(&person.full_name).to_string(),        phones: list(Some(&person.phones)),        emails: list(Some(&person.emails)),        org: text(person.org.as_deref()),        role_title: text(person.role_title.as_deref()),        city: text(person.city.as_deref()),        birthday: birthday(person.birthday),    }}/// A stored snapshot, canonical — through the SAME helpers as the other two.////// `parseDeviceContactSnapshot` trusts `v === 1` and casts, so a hand-edited/// or future-written row could reach here missing a list; canonicalising/// defends that without changing a single well-formed comparison.pub fn snapshot_fields(snapshot: &DeviceContactSnapshot) -> ContactFields {    ContactFields {        // `text(...) ?? ""` — a snapshot's name is a string, and a blank one        // canonicalises to the empty string rather than to null.        full_name: text(Some(&snapshot.full_name)).unwrap_or_default(),        phones: list(Some(&snapshot.phones)),        emails: list(Some(&snapshot.emails)),        org: text(snapshot.org.as_deref()),        role_title: text(snapshot.role_title.as_deref()),        city: text(snapshot.city.as_deref()),        birthday: birthday(snapshot.birthday),    }}/// The fields to write on the person — only the keys that change.////// Each field is `Option<…>` of its own type: `None` is ABSENT (the/// TypeScript's missing key, "leave it alone") and `Some(None)` on a nullable/// field is an explicit clear. That distinction is why this is not one/// `Option` deep — `#[serde(skip_serializing_if = "Option::is_none")]` then/// makes the JSON the TypeScript's `Partial<ContactFields>` exactly, in/// declaration order, which is `ContactFieldName::ALL`'s order.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ContactFieldPatch {    #[serde(default, skip_serializing_if = "Option::is_none")]    pub full_name: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub phones: Option<Vec<String>>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub emails: Option<Vec<String>>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub org: Option<Option<String>>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub role_title: Option<Option<String>>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub city: Option<Option<String>>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub birthday: Option<Option<PersonBirthday>>,}impl ContactFieldPatch {    /// Is the patch empty — the TypeScript's `Object.keys(patch).length === 0`?    pub fn is_empty(&self) -> bool {        self.full_name.is_none()            && self.phones.is_none()            && self.emails.is_none()            && self.org.is_none()            && self.role_title.is_none()            && self.city.is_none()            && self.birthday.is_none()    }    /// The keys set, in the declared order — the TypeScript's `Object.keys`.    pub fn keys(&self) -> Vec<ContactFieldName> {        ContactFieldName::ALL            .into_iter()            .filter(|field| self.has(*field))            .collect()    }    pub fn has(&self, field: ContactFieldName) -> bool {        match field {            ContactFieldName::FullName => self.full_name.is_some(),            ContactFieldName::Phones => self.phones.is_some(),            ContactFieldName::Emails => self.emails.is_some(),            ContactFieldName::Org => self.org.is_some(),            ContactFieldName::RoleTitle => self.role_title.is_some(),            ContactFieldName::City => self.city.is_some(),            ContactFieldName::Birthday => self.birthday.is_some(),        }    }    /// `patch[field] = value` — the TypeScript's `assign`, which is sound for    /// the same reason: the value was read from `ContactFields` under this    /// exact key.    pub fn assign(&mut self, field: ContactFieldName, value: FieldValue) {        match (field, value) {            (ContactFieldName::FullName, FieldValue::Text(value)) => self.full_name = Some(value),            (ContactFieldName::Phones, FieldValue::List(value)) => self.phones = Some(value),            (ContactFieldName::Emails, FieldValue::List(value)) => self.emails = Some(value),            (ContactFieldName::Org, FieldValue::OptText(value)) => self.org = Some(value),            (ContactFieldName::RoleTitle, FieldValue::OptText(value)) => {                self.role_title = Some(value)            }            (ContactFieldName::City, FieldValue::OptText(value)) => self.city = Some(value),            (ContactFieldName::Birthday, FieldValue::Birthday(value)) => {                self.birthday = Some(value)            }            // Unreachable: every caller reads the value out of `ContactFields`            // under the same key it assigns. Ignoring rather than panicking is            // the library rule — a pure function may not blow up on a caller's            // mistake — and the `keys()` a caller reads back would not show it.            _ => {}        }    }}/// §4.1 — which of the phone's fields flow into Cotton.////// ```text///   no snapshot:                               adopt into EMPTY fields only///   phone == snapshot:                         nothing///   phone moved, Cotton still at the snapshot: adopt (even an emptier value —///                                              a number removed on the phone///                                              is removed here; a list is///                                              replaced whole)///   both moved:                                Cotton wins/// ```////// `full_name` is never adopted as empty — the mapper drops nameless contacts,/// so this is belt-and-braces, not a path.pub fn plan_fields(person: &ContactPerson, contact: &DeviceContact) -> ContactFieldPatch {    let phone = contact_fields(contact);    let cotton = person_fields(person);    let prior = person.device_contact_snapshot.as_ref().map(snapshot_fields);    let mut patch = ContactFieldPatch::default();    for field in ContactFieldName::ALL {        let next = phone.get(field);        if field == ContactFieldName::FullName && next.is_empty() {            continue;        }        let held = cotton.get(field);        if field_equal(&next, &held) {            continue;        }        let Some(prior) = prior.as_ref() else {            if held.is_empty() && !next.is_empty() {                patch.assign(field, next);            }            continue;        };        let was = prior.get(field);        let phone_moved = !field_equal(&next, &was);        let cotton_moved = !field_equal(&held, &was);        if phone_moved && !cotton_moved {            patch.assign(field, next);        }    }    patch}/// Whether the phone's current photo replaces what Cotton shows.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum PhotoDecision {    Adopt,    Keep,}/// §4.3 — whether the phone's current photo replaces what Cotton shows./// `raw_sha` is the digest of the phone's thumbnail, `None` when the book has/// none for this contact.////// The same shape as the field rule, with one asymmetry: the phone can CHANGE/// a face, never take one away. "Cotton moved" for a photo means Cotton's key/// is not the one we minted from the phone last time (`snapshot.avatar_key`)/// — so a photo the owner picked in the editor, or a/// removal the owner made, all keep.pub fn decide_photo(person: &ContactPerson, raw_sha: Option<&str>) -> PhotoDecision {    let Some(raw_sha) = raw_sha else {        return PhotoDecision::Keep;    };    let Some(prior) = person.device_contact_snapshot.as_ref() else {        return if person.avatar_key.is_none() {            PhotoDecision::Adopt        } else {            PhotoDecision::Keep        };    };    let phone_moved = Some(raw_sha) != prior.photo_sha.as_deref();    let cotton_moved = person.avatar_key != prior.avatar_key;    if phone_moved && !cotton_moved {        PhotoDecision::Adopt    } else {        PhotoDecision::Keep    }}/// §3 — the snapshot after this pass: what the phone showed, and which key (if/// any) Cotton minted from its photo. `adopted_key` is the key written this/// pass, or `None` to carry the prior one forward.pub fn next_snapshot(    contact: &DeviceContact,    raw_sha: Option<&str>,    prior: Option<&DeviceContactSnapshot>,    adopted_key: Option<&str>,) -> DeviceContactSnapshot {    let fields = contact_fields(contact);    DeviceContactSnapshot {        v: 1,        full_name: fields.full_name,        phones: fields.phones,        emails: fields.emails,        org: fields.org,        role_title: fields.role_title,        city: fields.city,        birthday: fields.birthday,        photo_sha: raw_sha.map(str::to_string),        avatar_key: adopted_key            .map(str::to_string)            .or_else(|| prior.and_then(|prior| prior.avatar_key.clone())),    }}/// The snapshot in one key order, so equality is byte equality.pub fn canonical_snapshot(snapshot: &DeviceContactSnapshot) -> DeviceContactSnapshot {    let fields = snapshot_fields(snapshot);    DeviceContactSnapshot {        v: 1,        full_name: fields.full_name,        phones: fields.phones,        emails: fields.emails,        org: fields.org,        role_title: fields.role_title,        city: fields.city,        birthday: fields.birthday,        photo_sha: snapshot.photo_sha.clone(),        avatar_key: snapshot.avatar_key.clone(),    }}/// Byte-stable equality — what makes "unchanged phone → no write" a rule,/// rather than a hope.////// The TypeScript compares two `JSON.stringify` strings; here the canonical/// form is a struct and the comparison is structural, which is the same/// judgement because the struct's field order IS the serialised order.pub fn snapshots_equal(    a: Option<&DeviceContactSnapshot>,    b: Option<&DeviceContactSnapshot>,) -> bool {    match (a, b) {        // `== null` on both sides in the TypeScript: two absent snapshots are        // equal, absent and present are not.        (None, None) => true,        (None, Some(_)) | (Some(_), None) => false,        (Some(a), Some(b)) => canonical_snapshot(a) == canonical_snapshot(b),    }}/// A live, linked person paired with the phone's contact and their plan.#[derive(Debug, Clone, PartialEq)]pub struct LinkedPerson<'a> {    pub person: &'a ContactPerson,    pub contact: &'a DeviceContact,    /// §4.1 for this pair — empty when nothing changes.    pub patch: ContactFieldPatch,}/// What `pair_linked_people` answers.#[derive(Debug, Clone, PartialEq)]pub struct PairedPeople<'a> {    pub linked: Vec<LinkedPerson<'a>>,    pub missing: Vec<&'a ContactPerson>,}/// Pair every live, linked person with the phone's contact and plan their/// fields. A person the read did not contain — deleted on the phone, or/// outside an iOS 18 limited-access grant — is REPORTED and never touched/// (§4.2); archived and hand-made people are skipped outright (§4.5).////// It BORROWS: the TypeScript hands back the same person objects it was given,/// and a Rust caller keeps its rows rather than paying for a copy of each.pub fn pair_linked_people<'a>(    people: &'a [ContactPerson],    contacts: &'a [DeviceContact],) -> PairedPeople<'a> {    let mut linked = Vec::new();    let mut missing = Vec::new();    for person in people {        if person.archived_at.is_some() {            continue;        }        let Some(device_contact_id) = person.device_contact_id.as_deref() else {            continue;        };        // A `Map` built from the contacts keeps the LAST of any duplicate id,        // which is what a `new Map(entries)` does; the lookup below reproduces        // that with `rev().find`.        let contact = contacts            .iter()            .rev()            .find(|contact| contact.device_contact_id == device_contact_id);        match contact {            None => missing.push(person),            Some(contact) => linked.push(LinkedPerson {                person,                contact,                patch: plan_fields(person, contact),            }),        }    }    PairedPeople { linked, missing }}#[cfg(test)]#[path = "contact_sync_tests.rs"]mod tests;