Cotton code
233 lines · 12.9 KB · RustRaw
//! The vCard and iCalendar readers: what each file becomes, and that it//! imports through the package path like any other package — merging into//! what the database holds, never duplicating it.use cotton_store::actor::{Actor, JobName};use cotton_store::cottonpkg::{import, Imported, MediaSink, Package};use cotton_store::file_identity::read_file_identity;use cotton_store::meta::Meta;use cotton_store::mint::{first_author, mint, Act, AuthorReason, Change, Clock, Held, History, IdSource};use cotton_store::protocol::derived_id::person_handle_id;use serde_json::{json, Map, Value};use cotton_store::test_template::create_workspace_in_memory_for_test;use cotton_store::Driver;use rusqlite::types::Value as SqlValue;use super::{package_from_ics, package_from_vcards, package_of_file, Holdings};const NOW: &str = "2026-10-22T09:00:00.000Z";const FILE: &str = "22222222-2222-4222-8222-222222222222";const CONTACTS: &str = "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:card-asha\r\nFN:Asha Rao\r\nN:Rao;Asha;;;\r\nORG:Harbour Bank;Retail\r\nTITLE:Branch manager\r\nTEL;TYPE=CELL:+91 98765 43210\r\nEMAIL:Asha@Example.com\r\nBDAY:1990-01-15\r\nNOTE:Met at the\\, harbour\r\nEND:VCARD\r\nBEGIN:VCARD\r\nVERSION:3.0\r\nFN:Ravi\r\nBDAY:--0704\r\nTEL:+44 20 7946 0000\r\nEND:VCARD\r\nBEGIN:VCARD\r\nVERSION:3.0\r\nEND:VCARD\r\n";const CALENDAR: &str = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:standup\r\nSUMMARY:Standup\r\nDTSTART;TZID=Asia/Kolkata:20261020T093000\r\nDURATION:PT15M\r\nRRULE:FREQ=DAILY\r\nEXDATE;TZID=Asia/Kolkata:20261021T093000\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:standup\r\nRECURRENCE-ID;TZID=Asia/Kolkata:20261022T093000\r\nSTATUS:CANCELLED\r\nDTSTART;TZID=Asia/Kolkata:20261022T093000\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:holiday\r\nDTSTART;VALUE=DATE:20261102\r\nDTEND;VALUE=DATE:20261104\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n";/// RULE: A contacts file is one person per card with a name, keyed by its UID, with each phone and email a handle and its note a person note; a card with nothing to call its person by is left out, and a birthday with no year keeps its month and day.#[test]fn a_contacts_file_is_people_with_their_handles() {    let db = database();    let holdings = Holdings::of(&db).expect("holdings");    let package = package_from_vcards(CONTACTS, &holdings, None, NOW);    let tables: Vec<(&str, usize)> = package.records.iter().map(|(table, rows)| (table.as_str(), rows.len())).collect();    assert_eq!(tables, [("cotton_people", 2), ("cotton_person_handles", 3), ("cotton_person_notes", 1)]);    let asha = &package.records[0].1[0];    assert_eq!(asha["full_name"], "Asha Rao");    assert_eq!(asha["org"], "Harbour Bank \u{b7} Retail");    assert_eq!(asha["role_title"], "Branch manager");    assert_eq!((asha["birth_year"].clone(), asha["birth_month"].clone(), asha["birth_day"].clone()), (1990.into(), 1.into(), 15.into()));    let ravi = &package.records[0].1[1];    assert_eq!((ravi["birth_year"].clone(), ravi["birth_month"].clone()), (serde_json::Value::Null, 7.into()));    let email = package.records[1].1.iter().find(|row| row["kind"] == "email").expect("an email handle");    assert_eq!(email["normalised"], "asha@example.com");    assert_eq!(package.records[2].1[0]["body"], "Met at the, harbour");    // The same file, read again, names the same records.    assert_eq!(package_from_vcards(CONTACTS, &holdings, None, "2027-01-01T00:00:00.000Z").records[0].1[0]["id"], asha["id"]);}/// RULE: A calendar file is one calendar of its events, each timed one read in its own zone, an all-day one stored to 23:59:59.999 of its last day, a series with its rule and the instants it skips — its own EXDATEs and its cancelled occurrences — and a cancelled occurrence never a record of its own.#[test]fn a_calendar_file_is_a_calendar_of_events() {    let db = database();    let package = package_from_ics(CALENDAR, &Holdings::of(&db).expect("holdings"), "Work", "Europe/London", NOW);    assert_eq!(package.records[0].1[0]["name"], "Work");    let events = &package.records[1].1;    assert_eq!(events.len(), 2, "{events:?}");    let standup = &events[0];    assert_eq!(standup["starts_at"], "2026-10-20T04:00:00.000Z");    assert_eq!(standup["ends_at"], "2026-10-20T04:15:00.000Z");    assert_eq!(standup["rrule"], "FREQ=DAILY");    assert_eq!(standup["exdates"], serde_json::json!(["2026-10-21T04:00:00.000Z", "2026-10-22T04:00:00.000Z"]));    assert_eq!(standup["timezone"], "Asia/Kolkata");    let holiday = &events[1];    assert_eq!(holiday["all_day"], true);    assert_eq!(holiday["title"], "(no title)");    assert_eq!(holiday["starts_at"], "2026-11-02T00:00:00.000Z");    assert_eq!(holiday["ends_at"], "2026-11-03T23:59:59.999Z");}/// RULE: Only a .cottonpkg, a .vcf or an .ics is a file Cotton imports; anything else is refused by name.#[test]fn a_file_is_read_by_its_extension() {    let db = database();    assert!(package_of_file("people.VCF", CONTACTS.as_bytes(), &db, None, "UTC", NOW).is_ok());    let calendar = package_of_file("Family.ics", CALENDAR.as_bytes(), &db, None, "UTC", NOW).expect("a calendar");    assert_eq!(calendar.records[0].1[0]["name"], "Family");    assert!(package_of_file("notes.txt", b"hello", &db, None, "UTC", NOW).unwrap_err().contains("notes.txt"));}struct Ids(u32);impl IdSource for Ids {    fn next_op_id(&mut self, _now_ms: i64) -> cotton_store::Result<String> {        self.0 += 1;        Ok(format!("op-{:05}", self.0))    }}struct NoMedia;impl MediaSink for NoMedia {    fn write(&mut self, key: &str, _bytes: &[u8]) -> cotton_store::Result<()> {        panic!("a contacts or calendar file carries no media, and {key} was written");    }}fn database() -> Driver {    let db = create_workspace_in_memory_for_test(&Meta {        workspace_id: FILE.to_string(),        owner_id: "owner-1".to_string(),        device_id: "device:test".to_string(),        last_server_seq: 0,        last_hlc: None,    })    .expect("a file");    db.run(        "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?, 'Mine', 'owner-1', ?)",        &[SqlValue::Text(FILE.to_string()), SqlValue::Text(NOW.to_string())],    )    .expect("the file's own row");    first_author(&db, "key", Some("Test"), AuthorReason::First, &Clock::wall(1), &mut Ids(90_000), Held::Served)        .expect("an author");    db}fn job() -> Actor {    Actor::job(JobName::named("test").expect("a job"))}/// Import one file's package at `at` ms, as a reader made it from what the/// database holds at that moment.fn import_at(db: &Driver, package: &Package, at: i64) -> Imported {    let imported = import(db, package, &job(), &Clock::wall(at), &mut Ids((at % 4_000_000) as u32 * 1_000), Held::Served, &mut NoMedia).expect("imports");    assert!(imported.refused.is_empty(), "{:?}", imported.refused);    imported}fn iso(at: i64) -> String {    cotton_store::protocol::js::to_iso_string(at).expect("an instant")}fn object(value: Value) -> Map<String, Value> {    value.as_object().expect("an object").clone()}fn count(db: &Driver, sql: &str) -> i64 {    db.get(sql, &[]).expect("reads").and_then(|row| row.int("n")).unwrap_or(0)}fn answer(db: &Driver, sql: &str) -> Option<String> {    db.get(sql, &[]).expect("reads").and_then(|row| row.text("answer").map(str::to_string))}/// Everything a reader's import could have touched, as the file holds it.fn snapshot(db: &Driver) -> Vec<String> {    ["cotton_people", "cotton_person_handles", "cotton_person_notes", "cotton_collections", "cotton_events", "_writes"]        .iter()        .flat_map(|table| {            db.all(&format!("SELECT * FROM {table} ORDER BY rowid"), &[]).expect("reads").into_iter().map(move |row| format!("{table} {:?}", row.columns()))        })        .collect()}/// RULE: A contacts file and a calendar file import through the package path into the importer's own database — every record minted, the reader's source rewritten to the database's id — and importing the same file again, hours later, leaves the database exactly as it was: no record, no change and no receipt.#[test]fn importing_the_same_file_twice_changes_nothing() {    let db = database();    let read = |at: i64| {        let holdings = Holdings::of(&db).expect("holdings");        [package_from_vcards(CONTACTS, &holdings, None, &iso(at)), package_from_ics(CALENDAR, &holdings, "Work", "UTC", &iso(at))]    };    for (step, package) in read(1_000).iter().enumerate() {        import_at(&db, package, 1_000 + step as i64);    }    assert_eq!(count(&db, &format!("SELECT count(*) AS n FROM cotton_people WHERE workspace_id = '{FILE}'")), 2);    assert_eq!(count(&db, "SELECT count(*) AS n FROM cotton_person_handles"), 3);    assert_eq!(count(&db, "SELECT count(*) AS n FROM cotton_events"), 2);    let before = snapshot(&db);    // Three hours later, the same two files.    for (step, package) in read(10_801_000).iter().enumerate() {        let again = import_at(&db, package, 10_801_000 + step as i64);        assert!(again.created.is_empty() && again.changed.is_empty(), "{again:?}");    }    assert_eq!(snapshot(&db), before, "the database is as it was");}/// RULE: A card whose phone or email already names a person merges into that person: no second person, the person keeps what they already say and gains only what they lacked, and the card's new handles join them under the id the Contacts import gives a handle.#[test]fn a_card_merges_into_the_person_its_handle_names() {    let db = database();    let namespace = read_file_identity(&db).expect("reads").expect("an identity").namespace().clone();    let phone = cotton_store::protocol::person_handles::normalise_handle_in(        cotton_store::protocol::person_handles::HandleKind::Phone,        "+91 98765 43210",        None,    )    .expect("a phone");    let phone = phone.as_str();    let held_phone = person_handle_id(&namespace, "phone", phone);    write(&db, vec![        Change::create("cotton_people", "asha-here", object(json!({            "id": "asha-here", "workspace_id": FILE, "full_name": "Asha", "contact_source": "manual",            "created_at": NOW, "updated_at": NOW,        }))),        Change::create("cotton_person_handles", &held_phone, object(json!({            "id": held_phone, "workspace_id": FILE, "person_id": "asha-here", "kind": "phone", "value": "+91 98765 43210",            "normalised": phone, "source": "manual", "position": 0, "created_at": NOW, "updated_at": NOW,        }))),    ]);    let package = package_from_vcards(CONTACTS, &Holdings::of(&db).expect("holdings"), None, &iso(5_000));    import_at(&db, &package, 5_000);    assert_eq!(count(&db, "SELECT count(*) AS n FROM cotton_people WHERE full_name LIKE 'Asha%'"), 1, "no second Asha");    assert_eq!(answer(&db, "SELECT full_name AS answer FROM cotton_people WHERE id = 'asha-here'").as_deref(), Some("Asha"), "what she already says stays");    assert_eq!(answer(&db, "SELECT org AS answer FROM cotton_people WHERE id = 'asha-here'").as_deref(), Some("Harbour Bank \u{b7} Retail"));    let email = person_handle_id(&namespace, "email", "asha@example.com");    assert_eq!(answer(&db, &format!("SELECT person_id AS answer FROM cotton_person_handles WHERE id = '{email}'")).as_deref(), Some("asha-here"));    assert_eq!(count(&db, "SELECT count(*) AS n FROM cotton_person_handles WHERE person_id = 'asha-here'"), 2);    assert_eq!(answer(&db, "SELECT source AS answer FROM cotton_person_handles WHERE kind = 'phone' AND person_id = 'asha-here'").as_deref(), Some("manual"), "a handle she had is left as it was");}/// RULE: An event whose UID the database already holds is that event: the file updates it where it is, in its own calendar, and no second event is made.#[test]fn an_event_with_a_held_uid_is_updated_not_duplicated() {    let db = database();    write(&db, vec![        Change::create("cotton_collections", "home", object(json!({            "id": "home", "workspace_id": FILE, "kind": "calendar", "name": "Home", "created_at": NOW,        }))),        Change::create("cotton_events", "standup-here", object(json!({            "id": "standup-here", "collection_id": "home", "title": "Old standup", "starts_at": "2026-10-20T04:00:00.000Z",            "ical_uid": "standup", "created_at": NOW, "updated_at": NOW,        }))),    ]);    let package = package_from_ics(CALENDAR, &Holdings::of(&db).expect("holdings"), "Work", "UTC", &iso(5_000));    import_at(&db, &package, 5_000);    assert_eq!(count(&db, "SELECT count(*) AS n FROM cotton_events WHERE ical_uid = 'standup'"), 1, "no second standup");    assert_eq!(answer(&db, "SELECT title AS answer FROM cotton_events WHERE id = 'standup-here'").as_deref(), Some("Standup"));    assert_eq!(answer(&db, "SELECT collection_id AS answer FROM cotton_events WHERE id = 'standup-here'").as_deref(), Some("home"));}fn write(db: &Driver, changes: Vec<Change>) {    mint(db, &Act { actor: job(), verb: "seed".to_string(), history: History::None, changes }, &Clock::wall(500), &mut Ids(800_000), Held::Served)        .expect("seeded");}