Cotton code
801 lines · 24.6 KB · RustRaw
//! Every row of the spec's tables (§4), pinned.//!//! The engine decides and never touches a store, so each rule is a plain//! function call: a person as Cotton holds them, what the phone shows now, and//! what the phone showed last time (the snapshot).use super::*;const SHA_A: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";const SHA_B: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";const KEY_FROM_PHONE: &str = "ws/people/p1/phone.jpg";const KEY_OWN: &str = "ws/people/p1/own.jpg";fn person() -> ContactPerson {    ContactPerson {        id: "p1".to_string(),        full_name: "Asha Rao".to_string(),        phones: vec!["+91 98850 00001".to_string()],        emails: vec!["asha@example.com".to_string()],        org: Some("Acme".to_string()),        role_title: None,        city: Some("Hyderabad".to_string()),        birthday: None,        device_contact_id: Some("dev-1".to_string()),        device_contact_snapshot: None,        archived_at: None,        avatar_key: None,    }}fn contact() -> DeviceContact {    DeviceContact {        device_contact_id: "dev-1".to_string(),        full_name: "Asha Rao".to_string(),        phones: Some(vec!["+91 98850 00001".to_string()]),        emails: Some(vec!["asha@example.com".to_string()]),        org: Some("Acme".to_string()),        role_title: None,        city: Some("Hyderabad".to_string()),        birthday: None,        image_available: Some(false),    }}/// The snapshot of `contact()` as the phone showed it — Cotton and phone agree.fn agreed() -> DeviceContactSnapshot {    DeviceContactSnapshot {        v: 1,        full_name: "Asha Rao".to_string(),        phones: vec!["+91 98850 00001".to_string()],        emails: vec!["asha@example.com".to_string()],        org: Some("Acme".to_string()),        role_title: None,        city: Some("Hyderabad".to_string()),        birthday: None,        photo_sha: None,        avatar_key: None,    }}fn strings(values: &[&str]) -> Vec<String> {    values.iter().map(|value| (*value).to_string()).collect()}// ── contactFields — canonical form ───────────────────────────────────────────#[test]fn trims_de_duplicates_and_reads_empty_as_null() {    let fields = contact_fields(&DeviceContact {        full_name: "  Asha Rao ".to_string(),        phones: Some(strings(&[" +91 1 ", "+91 1", ""])),        emails: None,        org: Some("  ".to_string()),        city: None,        birthday: Some(PersonBirthday {            month: 3,            day: 14,            year: None,        }),        ..contact()    });    assert_eq!(        fields,        ContactFields {            full_name: "Asha Rao".to_string(),            phones: strings(&["+91 1"]),            emails: vec![],            org: None,            role_title: None,            city: None,            birthday: Some(PersonBirthday {                month: 3,                day: 14,                year: None            }),        }    );}/// Ten whitespace probes read out of Node. Two of them are the whole reason/// this module trims with `is_js_whitespace` rather than `str::trim`: a BOM is/// whitespace to JavaScript and not to Rust, and U+0085 (NEL) is whitespace to/// Rust and not to JavaScript. A field that is only a BOM is EMPTY — which is/// the field the pull is allowed to fill — and a field that is only a NEL is/// not.#[test]fn the_trim_is_javascripts_whitespace_class_not_rusts() {    // (value, canonical full_name, canonical org, canonical phones)    let cases: &[(&str, &str, Option<&str>, &[&str])] = &[        ("\u{feff}Asha", "Asha", Some("Asha"), &["Asha", "x"]),        ("Asha\u{feff}", "Asha", Some("Asha"), &["Asha", "x"]),        ("\u{feff}", "", None, &["x"]),        (            "\u{85}Asha",            "\u{85}Asha",            Some("\u{85}Asha"),            &["\u{85}Asha", "x"],        ),        ("\u{85}", "\u{85}", Some("\u{85}"), &["\u{85}", "x"]),        ("\u{a0}", "", None, &["x"]),        ("\u{2028}", "", None, &["x"]),        ("\u{b}", "", None, &["x"]),        ("\t\nAsha\r\n", "Asha", Some("Asha"), &["Asha", "x"]),        // U+180E stopped being whitespace in Unicode 6.3 and neither runtime        // trims it — the control case that says the other nine mean something.        ("\u{180e}", "\u{180e}", Some("\u{180e}"), &["\u{180e}", "x"]),    ];    for (value, name, org, phones) in cases {        let fields = contact_fields(&DeviceContact {            full_name: (*value).to_string(),            ..contact()        });        assert_eq!(fields.full_name, *name, "fullName of {value:?}");        let fields = contact_fields(&DeviceContact {            org: Some((*value).to_string()),            ..contact()        });        assert_eq!(fields.org.as_deref(), *org, "org of {value:?}");        let fields = contact_fields(&DeviceContact {            phones: Some(strings(&[value, "x"])),            ..contact()        });        assert_eq!(fields.phones, strings(phones), "phones of {value:?}");    }}// ── planFields — no snapshot yet (imported before v8) ────────────────────────#[test]fn fills_empty_fields_only_never_overwriting_what_cotton_has() {    let p = ContactPerson {        org: None,        city: Some("Chennai".to_string()),        phones: vec![],        birthday: None,        ..person()    };    let c = DeviceContact {        org: Some("Acme".to_string()),        city: Some("Hyderabad".to_string()),        phones: Some(strings(&["+91 2"])),        birthday: Some(PersonBirthday {            month: 8,            day: 25,            year: None,        }),        ..contact()    };    assert_eq!(        plan_fields(&p, &c),        ContactFieldPatch {            phones: Some(strings(&["+91 2"])),            org: Some(Some("Acme".to_string())),            birthday: Some(Some(PersonBirthday {                month: 8,                day: 25,                year: None            })),            ..ContactFieldPatch::default()        }    );}#[test]fn is_empty_when_the_phone_has_nothing_cotton_lacks() {    let c = DeviceContact {        org: None,        city: None,        ..contact()    };    assert!(plan_fields(&person(), &c).is_empty());}// ── planFields — with a snapshot ─────────────────────────────────────────────#[test]fn does_nothing_when_the_phone_is_unchanged_even_if_cotton_moved_on() {    let p = ContactPerson {        org: Some("Acme Ltd".to_string()),        device_contact_snapshot: Some(agreed()),        ..person()    };    assert!(plan_fields(&p, &contact()).is_empty());}#[test]fn adopts_a_phone_change_when_cotton_is_still_at_the_snapshot() {    let p = ContactPerson {        device_contact_snapshot: Some(agreed()),        ..person()    };    let c = DeviceContact {        org: Some("Acme Ltd".to_string()),        city: None,        ..contact()    };    assert_eq!(        plan_fields(&p, &c),        ContactFieldPatch {            org: Some(Some("Acme Ltd".to_string())),            // An EMPTIER value flows in: `Some(None)` is the explicit clear.            city: Some(None),            ..ContactFieldPatch::default()        }    );}#[test]fn replaces_a_list_whole_a_number_removed_on_the_phone_is_removed_here() {    let p = ContactPerson {        phones: strings(&["+91 1", "+91 2"]),        device_contact_snapshot: Some(DeviceContactSnapshot {            phones: strings(&["+91 1", "+91 2"]),            ..agreed()        }),        ..person()    };    let c = DeviceContact {        phones: Some(strings(&["+91 2"])),        ..contact()    };    assert_eq!(        plan_fields(&p, &c),        ContactFieldPatch {            phones: Some(strings(&["+91 2"])),            ..ContactFieldPatch::default()        }    );}#[test]fn lets_cotton_win_when_both_moved() {    let p = ContactPerson {        org: Some("Acme Ltd".to_string()),        device_contact_snapshot: Some(agreed()),        ..person()    };    let c = DeviceContact {        org: Some("Acme Inc".to_string()),        ..contact()    };    assert!(plan_fields(&p, &c).is_empty());}/// Cotton renamed; the phone changed the city. Only the city flows in.#[test]fn decides_field_by_field() {    let p = ContactPerson {        full_name: "Asha R.".to_string(),        device_contact_snapshot: Some(agreed()),        ..person()    };    let c = DeviceContact {        full_name: "Asha Rao Iyer".to_string(),        city: Some("Pune".to_string()),        ..contact()    };    assert_eq!(        plan_fields(&p, &c),        ContactFieldPatch {            city: Some(Some("Pune".to_string())),            ..ContactFieldPatch::default()        }    );}#[test]fn adopts_a_birthday_the_phone_added() {    let p = ContactPerson {        device_contact_snapshot: Some(agreed()),        ..person()    };    let c = DeviceContact {        birthday: Some(PersonBirthday {            month: 3,            day: 14,            year: Some(1990),        }),        ..contact()    };    assert_eq!(        plan_fields(&p, &c),        ContactFieldPatch {            birthday: Some(Some(PersonBirthday {                month: 3,                day: 14,                year: Some(1990)            })),            ..ContactFieldPatch::default()        }    );}#[test]fn treats_whitespace_and_duplicates_as_no_change() {    let p = ContactPerson {        device_contact_snapshot: Some(agreed()),        ..person()    };    let c = DeviceContact {        full_name: " Asha Rao ".to_string(),        phones: Some(strings(&[" +91 98850 00001 ", "+91 98850 00001"])),        ..contact()    };    assert!(plan_fields(&p, &c).is_empty());}/// ORDER IS CONTENT: 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.#[test]fn adopts_a_reordered_list() {    let p = ContactPerson {        phones: strings(&["+91 1", "+91 2"]),        device_contact_snapshot: Some(DeviceContactSnapshot {            phones: strings(&["+91 1", "+91 2"]),            ..agreed()        }),        ..person()    };    let c = DeviceContact {        phones: Some(strings(&["+91 2", "+91 1"])),        ..contact()    };    assert_eq!(        plan_fields(&p, &c),        ContactFieldPatch {            phones: Some(strings(&["+91 2", "+91 1"])),            ..ContactFieldPatch::default()        }    );}/// `parseDeviceContactSnapshot` checks only `v === 1` and casts, so a row/// written by another version could reach the rules missing a list. A STORED/// snapshot goes through the same canonicaliser as the phone and Cotton, so/// this DECIDES rather than throwing — or, worse, comparing against/// `undefined`. In Rust the missing list deserialises to an empty one/// (`#[serde(default)]`), which is the same canonical value.#[test]fn reads_a_snapshot_stored_without_its_lists_as_an_empty_one() {    let stored: DeviceContactSnapshot = serde_json::from_str(        r#"{"v":1,"fullName":"Asha Rao","emails":["asha@example.com"],"org":"Acme","roleTitle":null,"city":"Hyderabad","birthday":null,"photoSha":null,"avatarKey":null}"#,    )    .expect("a snapshot missing its phone list still parses");    assert_eq!(stored.phones, Vec::<String>::new());    let p = ContactPerson {        device_contact_snapshot: Some(stored.clone()),        ..person()    };    assert!(plan_fields(&p, &contact()).is_empty());    // …and the rule still runs on it: Cotton sits at that empty list, the    // phone has a number, so the number flows in.    let p = ContactPerson {        phones: vec![],        device_contact_snapshot: Some(stored),        ..person()    };    assert_eq!(        plan_fields(&p, &contact()),        ContactFieldPatch {            phones: Some(strings(&["+91 98850 00001"])),            ..ContactFieldPatch::default()        }    );}// ── planFields — fullName is never adopted as empty (§4.1) ───────────────────/// The asymmetry worth seeing: an emptier org or city DOES flow in, but a/// nameless contact never renames anyone. The app's mapper drops nameless/// contacts, so this is belt-and-braces rather than a path anyone walks.#[test]fn holds_the_name_when_the_phone_shows_nothing_but_whitespace() {    let c = DeviceContact {        full_name: "   ".to_string(),        ..contact()    };    assert!(plan_fields(&person(), &c).is_empty());    let p = ContactPerson {        device_contact_snapshot: Some(agreed()),        ..person()    };    assert!(plan_fields(&p, &c).is_empty());}#[test]fn still_adopts_the_other_fields_the_phone_moved_in_the_same_pass() {    let p = ContactPerson {        device_contact_snapshot: Some(agreed()),        ..person()    };    let c = DeviceContact {        full_name: "   ".to_string(),        city: Some("Pune".to_string()),        ..contact()    };    assert_eq!(        plan_fields(&p, &c),        ContactFieldPatch {            city: Some(Some("Pune".to_string())),            ..ContactFieldPatch::default()        }    );}/// The patch's KEY ORDER, read off `Object.keys` in Node: it is/// `ContactFieldName::ALL`'s order, which is the order the loop walks. A/// patch becomes a sync op's patch and an op's patch is stored as TEXT, so the/// order is observable.#[test]fn the_patch_serialises_in_the_typescripts_key_order() {    let p = ContactPerson {        device_contact_snapshot: Some(agreed()),        ..person()    };    let c = DeviceContact {        full_name: "Asha R Rao".to_string(),        phones: Some(strings(&["+91 2"])),        emails: Some(strings(&["a@b.c"])),        org: Some("Beta".to_string()),        role_title: Some("CTO".to_string()),        city: Some("Pune".to_string()),        birthday: Some(PersonBirthday {            month: 3,            day: 14,            year: Some(1990),        }),        ..contact()    };    let patch = plan_fields(&p, &c);    assert_eq!(        patch.keys(),        vec![            ContactFieldName::FullName,            ContactFieldName::Phones,            ContactFieldName::Emails,            ContactFieldName::Org,            ContactFieldName::RoleTitle,            ContactFieldName::City,            ContactFieldName::Birthday,        ]    );    assert_eq!(        serde_json::to_string(&patch).unwrap(),        r#"{"fullName":"Asha R Rao","phones":["+91 2"],"emails":["a@b.c"],"org":"Beta","roleTitle":"CTO","city":"Pune","birthday":{"month":3,"day":14,"year":1990}}"#    );}// ── decidePhoto ──────────────────────────────────────────────────────────────#[test]fn keeps_whatever_cotton_has_when_the_phone_has_no_photo() {    assert_eq!(decide_photo(&person(), None), PhotoDecision::Keep);    assert_eq!(        decide_photo(            &ContactPerson {                avatar_key: Some(KEY_OWN.to_string()),                ..person()            },            None        ),        PhotoDecision::Keep    );    assert_eq!(        decide_photo(            &ContactPerson {                avatar_key: Some(KEY_FROM_PHONE.to_string()),                device_contact_snapshot: Some(DeviceContactSnapshot {                    photo_sha: Some(SHA_A.to_string()),                    avatar_key: Some(KEY_FROM_PHONE.to_string()),                    ..agreed()                }),                ..person()            },            None        ),        PhotoDecision::Keep    );}#[test]fn with_no_snapshot_adopts_into_a_person_with_no_photo() {    assert_eq!(decide_photo(&person(), Some(SHA_A)), PhotoDecision::Adopt);}#[test]fn with_no_snapshot_keeps_a_photo_chosen_in_the_editor() {    assert_eq!(        decide_photo(            &ContactPerson {                avatar_key: Some(KEY_OWN.to_string()),                ..person()            },            Some(SHA_A)        ),        PhotoDecision::Keep    );}fn from_phone() -> DeviceContactSnapshot {    DeviceContactSnapshot {        photo_sha: Some(SHA_A.to_string()),        avatar_key: Some(KEY_FROM_PHONE.to_string()),        ..agreed()    }}#[test]fn does_nothing_when_the_phones_photo_is_unchanged() {    assert_eq!(        decide_photo(            &ContactPerson {                avatar_key: Some(KEY_FROM_PHONE.to_string()),                device_contact_snapshot: Some(from_phone()),                ..person()            },            Some(SHA_A)        ),        PhotoDecision::Keep    );}#[test]fn does_not_re_adopt_a_photo_the_owner_removed_in_cotton() {    assert_eq!(        decide_photo(            &ContactPerson {                avatar_key: None,                device_contact_snapshot: Some(from_phone()),                ..person()            },            Some(SHA_A)        ),        PhotoDecision::Keep    );}#[test]fn adopts_a_new_phone_photo_over_the_one_that_came_from_the_phone() {    assert_eq!(        decide_photo(            &ContactPerson {                avatar_key: Some(KEY_FROM_PHONE.to_string()),                device_contact_snapshot: Some(from_phone()),                ..person()            },            Some(SHA_B)        ),        PhotoDecision::Adopt    );}#[test]fn adopts_the_phones_first_photo_into_a_person_who_never_had_one() {    assert_eq!(        decide_photo(            &ContactPerson {                device_contact_snapshot: Some(agreed()),                ..person()            },            Some(SHA_A)        ),        PhotoDecision::Adopt    );}#[test]fn never_replaces_a_photo_the_owner_picked_themselves() {    assert_eq!(        decide_photo(            &ContactPerson {                avatar_key: Some(KEY_OWN.to_string()),                device_contact_snapshot: Some(from_phone()),                ..person()            },            Some(SHA_B)        ),        PhotoDecision::Keep    );}#[test]fn lets_cotton_win_when_the_owner_removed_the_photo_and_the_phone_changed_it() {    assert_eq!(        decide_photo(            &ContactPerson {                avatar_key: None,                device_contact_snapshot: Some(from_phone()),                ..person()            },            Some(SHA_B)        ),        PhotoDecision::Keep    );}/// The whole grid, in the order Node printed it.// ── nextSnapshot / snapshotsEqual ────────────────────────────────────────────#[test]fn records_what_the_phone_showed_and_the_key_minted_from_its_photo() {    assert_eq!(        next_snapshot(&contact(), Some(SHA_A), None, Some(KEY_FROM_PHONE)),        DeviceContactSnapshot {            photo_sha: Some(SHA_A.to_string()),            avatar_key: Some(KEY_FROM_PHONE.to_string()),            ..agreed()        }    );}#[test]fn keeps_the_prior_phone_minted_key_when_nothing_new_was_adopted() {    let prior = DeviceContactSnapshot {        photo_sha: Some(SHA_A.to_string()),        avatar_key: Some(KEY_FROM_PHONE.to_string()),        ..agreed()    };    assert_eq!(        next_snapshot(&contact(), None, Some(&prior), None),        DeviceContactSnapshot {            photo_sha: None,            avatar_key: Some(KEY_FROM_PHONE.to_string()),            ..agreed()        }    );}#[test]fn is_byte_stable_so_an_unchanged_phone_means_no_write() {    let a = next_snapshot(&contact(), None, None, None);    let b = next_snapshot(        &DeviceContact {            phones: Some(strings(&[" +91 98850 00001 "])),            ..contact()        },        None,        Some(&agreed()),        None,    );    assert!(snapshots_equal(Some(&a), Some(&b)));    assert!(!snapshots_equal(        Some(&a),        Some(&DeviceContactSnapshot {            city: Some("Pune".to_string()),            ..agreed()        })    ));    assert!(snapshots_equal(None, None));    assert!(!snapshots_equal(Some(&a), None));}/// The TypeScript compares two `JSON.stringify` strings and its test proves/// key order does not matter by shuffling the object literal. Here the/// canonical form is a struct, so the shuffle is a DESERIALISATION — which is/// the same claim about the same bytes.#[test]fn ignores_key_order_when_comparing() {    let shuffled: DeviceContactSnapshot = serde_json::from_str(        r#"{"avatarKey":null,"photoSha":null,"birthday":null,"city":"Hyderabad","roleTitle":null,"org":"Acme","emails":["asha@example.com"],"phones":["+91 98850 00001"],"fullName":"Asha Rao","v":1}"#,    )    .expect("a shuffled snapshot parses");    assert!(snapshots_equal(Some(&agreed()), Some(&shuffled)));}/// Three whole snapshots, byte for byte as Node printed them — the field/// ORDER included, which is what makes `snapshots_equal` a byte comparison on/// both sides.#[test]fn next_snapshot_matches_the_typescript_byte_for_byte() {    let goldens: [(DeviceContactSnapshot, &str); 3] = [        (            next_snapshot(&contact(), Some(SHA_A), None, Some("ws/people/p1/x.jpg")),            r#"{"v":1,"fullName":"Asha Rao","phones":["+91 98850 00001"],"emails":["asha@example.com"],"org":"Acme","roleTitle":null,"city":"Hyderabad","birthday":null,"photoSha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","avatarKey":"ws/people/p1/x.jpg"}"#,        ),        (            next_snapshot(                &contact(),                None,                Some(&DeviceContactSnapshot {                    photo_sha: Some(SHA_A.to_string()),                    avatar_key: Some("k".to_string()),                    ..agreed()                }),                None,            ),            r#"{"v":1,"fullName":"Asha Rao","phones":["+91 98850 00001"],"emails":["asha@example.com"],"org":"Acme","roleTitle":null,"city":"Hyderabad","birthday":null,"photoSha":null,"avatarKey":"k"}"#,        ),        (            next_snapshot(                &DeviceContact {                    phones: Some(strings(&[" +91 1 ", "+91 1"])),                    ..contact()                },                None,                None,                None,            ),            r#"{"v":1,"fullName":"Asha Rao","phones":["+91 1"],"emails":["asha@example.com"],"org":"Acme","roleTitle":null,"city":"Hyderabad","birthday":null,"photoSha":null,"avatarKey":null}"#,        ),    ];    for (snapshot, expected) in goldens {        assert_eq!(serde_json::to_string(&snapshot).unwrap(), expected);    }}// ── pairLinkedPeople ─────────────────────────────────────────────────────────#[test]fn pairs_each_live_linked_person_with_the_phones_contact_and_plans_their_fields() {    let people = vec![        person(),        ContactPerson {            id: "p2".to_string(),            device_contact_id: Some("dev-2".to_string()),            org: None,            ..person()        },    ];    let contacts = vec![        contact(),        DeviceContact {            device_contact_id: "dev-2".to_string(),            org: Some("Beta".to_string()),            ..contact()        },    ];    let paired = pair_linked_people(&people, &contacts);    assert_eq!(paired.linked.len(), 2);    assert_eq!(        paired            .linked            .iter()            .map(|l| l.person.id.as_str())            .collect::<Vec<_>>(),        vec!["p1", "p2"]    );    assert_eq!(        paired.linked[1].patch,        ContactFieldPatch {            org: Some(Some("Beta".to_string())),            ..ContactFieldPatch::default()        }    );    assert!(paired.missing.is_empty());}#[test]fn reports_never_touches_a_person_the_read_did_not_contain() {    let people = vec![person()];    let paired = pair_linked_people(&people, &[]);    assert!(paired.linked.is_empty());    assert_eq!(        paired            .missing            .iter()            .map(|p| p.id.as_str())            .collect::<Vec<_>>(),        vec!["p1"]    );}#[test]fn skips_archived_and_hand_made_people_entirely() {    let people = vec![        ContactPerson {            archived_at: Some("2026-08-01T00:00:00.000Z".to_string()),            ..person()        },        ContactPerson {            id: "p3".to_string(),            device_contact_id: None,            ..person()        },    ];    let contacts = vec![contact()];    let paired = pair_linked_people(&people, &contacts);    assert!(paired.linked.is_empty());    assert!(paired.missing.is_empty());}