Cotton code
280 lines · 20.3 KB · RustRaw
//! Days' changes to Google Calendar (CONTRACT.md section 16) against a//! scripted object: what each waiting event asks of Google, and what the//! object's answer leaves on the row. Nobody here is real.use std::sync::Arc;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange, Seen};use serde_json::{json, Value};use tempfile::TempDir;use crate::handle::CottonHandle;use crate::phone::days::tests::{ask, lines, phone, refused, span, sql, zone, TODAY, ZONE};use crate::phone::days_people::Heard;use crate::phone::personal_object::ObjectDoor;const CREDENTIAL: &str = "ctd_11111111-1111-4111-8111-111111111111_test-credential";const GOOGLE_EVENT: &str = "00000000-0000-4000-8000-0000000000c1";fn with_door(handle: &CottonHandle, replies: impl IntoIterator<Item = Reply>) -> Arc<ScriptedExchange> {    let exchange = ScriptedExchange::new(replies);    let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: exchange.clone(), credential: CREDENTIAL.to_string() };    handle.client().set_object_door(Some(Arc::new(door)));    exchange}fn status(can_write: bool) -> Value {    json!({ "available": true, "keep": false, "accounts": [{ "googleEmail": "walk@example.test", "canWrite": can_write, "calendar": { "phase": "synced", "eventCount": 1 } }] })}fn body(seen: &Seen) -> Value {    serde_json::from_slice(&seen.body).expect("a JSON body")}fn one(handle: &CottonHandle, statement: &str) -> Option<String> {    let mut out = None;    handle        .client()        .with_writer(|replica| {            out = replica.driver.get(statement, &[]).map_err(|e| e.to_string())?.and_then(|row| row.text("v").map(str::to_string));            Ok(())        })        .expect("read");    out}fn add(handle: &CottonHandle, words: &str) -> String {    ask(handle, "days.add", json!({ "words": words, "timezone": ZONE, "today": TODAY, "where": "days" }))["id"].as_str().expect("an id").to_string()}fn sheet(handle: &CottonHandle, id: &str) -> Value {    ask(handle, "days.item", json!({ "table": "event", "id": id, "timezone": ZONE, "today": TODAY }))}fn google_event(handle: &CottonHandle) {    sql(handle, "INSERT INTO cotton_events (id, title, notes, starts_at, ends_at, all_day, gcal_id, gcal_etag, sync_state, account, on_google, created_at, updated_at) VALUES        ('00000000-0000-4000-8000-0000000000c1', 'Massage', NULL, '2026-11-21T15:30:00.000Z', '2026-11-21T16:30:00.000Z', 0, 'g-invented-1', '\"e1\"', 'synced', 'walk@example.test', 1, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')");}/// RULE (CONTRACT §15, §16): someone added by email to an event of the person's own, while a writable Google calendar stands, is told before Save that Google emails them; the event is then put on Google with them as a guest (sendUpdates all), in its own zone; Google's id lands on the row and their answer shows once Google brings it.#[test]fn a_guest_by_email_puts_the_event_on_google_and_google_invites_them() {    let dir = TempDir::new().unwrap();    let handle = phone(&dir);    zone(&handle);    Heard::google(&handle.client(), &status(true));    let id = add(&handle, "Dinner Saturday 7pm to 9pm");    let people = json!([{ "email": "priya@example.test", "name": "Priya" }]);    let told = ask(&handle, "days.tell", json!({ "table": "event", "id": id, "people": people }));    assert_eq!(told["lines"], json!(["Priya gets an invitation by email from Google Calendar."]));    let changed = ask(&handle, "days.change", json!({ "table": "event", "id": id, "people": people, "timezone": ZONE }));    assert_eq!(changed["google"], json!("waiting"));    let rows = &sheet(&handle, &id)["people"]["rows"];    assert_eq!((rows[0]["name"].clone(), rows[0]["via"].clone(), rows[0]["answer"].clone()), (json!("Priya"), json!("google"), Value::Null));    let exchange = with_door(&handle, [        Reply::ok(&status(true).to_string()),        Reply::ok(&json!({ "account": "walk@example.test", "gcalId": "g-new-1", "etag": "\"n1\"", "attendees": [{ "email": "priya@example.test", "displayName": "Priya", "responseStatus": "needsAction" }, { "email": "walk@example.test", "self": true, "organizer": true, "responseStatus": "accepted" }] }).to_string()),    ]);    let sent = ask(&handle, "days.send_to_google", json!({ "timezone": ZONE }));    assert_eq!((sent["sent"].clone(), sent["reconnect"].clone()), (json!(1), Value::Null));    let seen = exchange.seen();    assert_eq!((seen[1].method.as_str(), seen[1].path.as_str()), ("POST", "/v1/google/events"));    let asked = body(&seen[1]);    assert_eq!((asked["op"].clone(), asked["notify"].clone()), (json!("insert"), json!("all")));    assert_eq!(asked["event"]["summary"], json!("Dinner"));    assert_eq!(asked["event"]["start"], json!({ "dateTime": "2026-11-21T19:00:00.000Z", "timeZone": "Europe/London" }));    assert_eq!(asked["event"]["end"], json!({ "dateTime": "2026-11-21T21:00:00.000Z", "timeZone": "Europe/London" }));    assert_eq!(asked["event"]["attendees"], json!([{ "email": "priya@example.test", "displayName": "Priya" }]));    assert_eq!(one(&handle, &format!("SELECT gcal_id || ' ' || sync_state AS v FROM cotton_events WHERE id = '{id}'")).as_deref(), Some("g-new-1 synced"));    assert_eq!(sheet(&handle, &id)["people"]["rows"][0]["answerWords"], json!("No answer"));    // Priya answers in Google; the pull brings it in guest_responses.    sql(&handle, &format!("UPDATE cotton_events SET guest_responses = '[{{\"email\":\"priya@example.test\",\"answer\":\"accepted\"}}]' WHERE id = '{id}'"));    assert_eq!(sheet(&handle, &id)["people"]["rows"][0]["answerWords"], json!("Coming"));    // Nothing more waits: the next pass asks the status only.    let exchange = with_door(&handle, [Reply::ok(&status(true).to_string())]);    assert_eq!(ask(&handle, "days.send_to_google", json!({ "timezone": ZONE }))["sent"], json!(0));    assert_eq!(exchange.seen().len(), 1);}/// RULE (CONTRACT §15): taking someone off says so before Save, and the patch Google gets no longer names them.#[test]fn taking_a_guest_off_tells_them_through_google() {    let dir = TempDir::new().unwrap();    let handle = phone(&dir);    zone(&handle);    Heard::google(&handle.client(), &status(true));    let id = add(&handle, "Dinner Saturday 7pm");    ask(&handle, "days.change", json!({ "table": "event", "id": id, "people": [{ "email": "priya@example.test", "name": "Priya" }, { "email": "akash@example.test", "name": "Akash" }], "timezone": ZONE }));    sql(&handle, &format!("UPDATE cotton_events SET gcal_id = 'g-2', gcal_etag = '\"a\"', sync_state = 'synced' WHERE id = '{id}'"));    assert_eq!(sheet(&handle, &id)["deleteTells"], json!("Priya and Akash are told it is off."));    let told = ask(&handle, "days.tell", json!({ "table": "event", "id": id, "people": [{ "email": "akash@example.test" }] }));    assert_eq!(told["lines"], json!(["Priya is told by email from Google Calendar that they are off the list."]));    ask(&handle, "days.change", json!({ "table": "event", "id": id, "people": [{ "email": "akash@example.test" }], "timezone": ZONE }));    let exchange = with_door(&handle, [Reply::ok(&status(true).to_string()), Reply::ok(r#"{"account":"walk@example.test","gcalId":"g-2","etag":"\"b\"","attendees":[]}"#)]);    ask(&handle, "days.send_to_google", json!({ "timezone": ZONE }));    let asked = body(&exchange.seen()[1]);    assert_eq!((asked["op"].clone(), asked["gcalId"].clone(), asked["notify"].clone()), (json!("patch"), json!("g-2"), json!("all")));    assert_eq!(asked["event"]["attendees"], json!([{ "email": "akash@example.test", "displayName": "Akash" }]));}/// RULE (CONTRACT §15): with no writable Google calendar, someone by email waits, and the sheet says to connect, with Connect.#[test]fn without_google_an_email_guest_waits_and_the_sheet_says_connect() {    let dir = TempDir::new().unwrap();    let handle = phone(&dir);    zone(&handle);    Heard::google(&handle.client(), &json!({ "available": true, "accounts": [] }));    let id = add(&handle, "Dinner Saturday 7pm");    let told = ask(&handle, "days.tell", json!({ "table": "event", "id": id, "people": [{ "email": "priya@example.test", "name": "Priya" }] }));    assert_eq!(told["lines"], json!(["Priya is told once Google Calendar is connected."]));    assert_eq!(told["blocked"]["line"], json!("Connect Google Calendar to send invitations by email."));    assert_eq!(told["blocked"]["connect"]["id"], json!("google_connect"));    ask(&handle, "days.change", json!({ "table": "event", "id": id, "people": [{ "email": "priya@example.test", "name": "Priya" }], "timezone": ZONE }));    let people = &sheet(&handle, &id)["people"];    assert_eq!(people["rows"][0]["via"], json!("none"));    assert_eq!(people["blocked"]["connect"]["notice"]["go"], json!("Continue to Google"));    // The send pass asks to connect.    with_door(&handle, [Reply::ok(r#"{"available":true,"accounts":[]}"#)]);    let sent = ask(&handle, "days.send_to_google", json!({ "timezone": ZONE }));    assert_eq!(sent["reconnect"]["line"], json!("Connect Google Calendar to send invitations by email."));}/// RULE (CONTRACT §15): a phone with no server copy (signed out) promises nobody Google's email: someone by email/// waits, the sheet says so, and no Connect is offered that cannot work yet (the emulator walk, 22 Nov 2026).#[test]fn signed_out_an_email_guest_waits_and_no_connect_is_offered() {    let dir = TempDir::new().unwrap();    let handle = phone(&dir);    zone(&handle);    let id = add(&handle, "Dinner Saturday 7pm");    let people = json!([{ "email": "ivy@example.test" }]);    let told = ask(&handle, "days.tell", json!({ "table": "event", "id": id, "people": people }));    assert_eq!(told["lines"], json!(["ivy@example.test is told once Google Calendar is connected."]));    assert_eq!(told["blocked"]["line"], json!("Connect Google Calendar to send invitations by email."));    assert_eq!(told["blocked"]["connect"], Value::Null);    ask(&handle, "days.change", json!({ "table": "event", "id": id, "people": people, "timezone": ZONE }));    assert_eq!(sheet(&handle, &id)["deleteTells"], Value::Null, "nobody was told of it, so nobody is told it is off");}/// RULE (CONTRACT §16): a Google event changed in Days goes to Google with its etag; when Google changed it first, Google's copy wins on the row and what the person typed is kept in their own note, said once.#[test]fn google_changed_first_keeps_googles_copy_and_what_was_typed() {    let dir = TempDir::new().unwrap();    let handle = phone(&dir);    zone(&handle);    google_event(&handle);    Heard::google(&handle.client(), &status(true));    let changed = ask(&handle, "days.change", json!({ "table": "event", "id": GOOGLE_EVENT, "title": "Long massage", "length": 90, "timezone": ZONE }));    assert_eq!(changed["google"], json!("waiting"));    assert_eq!(one(&handle, &format!("SELECT sync_state AS v FROM cotton_events WHERE id = '{GOOGLE_EVENT}'")).as_deref(), Some("pending"));    let google = json!({ "id": "g-invented-1", "etag": "\"e2\"", "summary": "Massage (moved)", "start": { "dateTime": "2026-11-21T17:00:00Z" }, "end": { "dateTime": "2026-11-21T18:00:00Z" } });    let exchange = with_door(&handle, [Reply::ok(&status(true).to_string()), Reply::ok(&json!({ "account": "walk@example.test", "changed": true, "event": google }).to_string())]);    let sent = ask(&handle, "days.send_to_google", json!({ "timezone": ZONE }));    let asked = body(&exchange.seen()[1]);    assert_eq!((asked["op"].clone(), asked["gcalId"].clone(), asked["etag"].clone()), (json!("patch"), json!("g-invented-1"), json!("\"e1\"")));    assert!(asked["event"].get("attendees").is_none(), "a Google event whose people were never touched keeps Google's list");    assert_eq!(sent["said"], json!(["Google Calendar changed “Long massage” first, so Days kept Google's. What you typed is in its note."]));    assert_eq!(lines(&span(&handle, "2026-11-21", "2026-11-21")), ["2026-11-21: 17:00 · Massage (moved) to 18:00"]);    let note = sheet(&handle, GOOGLE_EVENT)["note"].clone();    assert_eq!(note, json!("Not saved to Google Calendar, which had changed first: Long massage, 15:30 to 17:00."));    assert_eq!(one(&handle, &format!("SELECT sync_state || ' ' || gcal_etag AS v FROM cotton_events WHERE id = '{GOOGLE_EVENT}'")).as_deref(), Some("synced \"e2\""));}/// RULE (CONTRACT §16): a Google event deleted in Days is deleted at Google and stays in the bin without its Google id; a change to one Google no longer holds bins it here and says so.#[test]fn deleting_goes_to_google_and_one_deleted_there_is_said() {    let dir = TempDir::new().unwrap();    let handle = phone(&dir);    zone(&handle);    google_event(&handle);    Heard::google(&handle.client(), &status(true));    assert_eq!(ask(&handle, "days.delete", json!({ "table": "event", "id": GOOGLE_EVENT }))["google"], json!("waiting"));    let exchange = with_door(&handle, [Reply::ok(&status(true).to_string()), Reply::ok(r#"{"account":"walk@example.test","ok":true}"#)]);    ask(&handle, "days.send_to_google", json!({ "timezone": ZONE }));    let asked = body(&exchange.seen()[1]);    assert_eq!((asked["op"].clone(), asked["gcalId"].clone(), asked["etag"].clone()), (json!("delete"), json!("g-invented-1"), json!("\"e1\"")));    assert_eq!(one(&handle, &format!("SELECT COALESCE(gcal_id, 'none') || ' ' || COALESCE(sync_state, 'none') || ' ' || (trashed_at IS NOT NULL) AS v FROM cotton_events WHERE id = '{GOOGLE_EVENT}'")).as_deref(), Some("none none 1"));    sql(&handle, "INSERT INTO cotton_events (id, title, starts_at, ends_at, all_day, gcal_id, gcal_etag, sync_state, account, on_google, created_at, updated_at) VALUES ('00000000-0000-4000-8000-0000000000c2', 'Call', '2026-11-22T10:00:00.000Z', '2026-11-22T10:30:00.000Z', 0, 'g-2', '\"x\"', 'synced', 'walk@example.test', 1, '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')");    ask(&handle, "days.change", json!({ "table": "event", "id": "00000000-0000-4000-8000-0000000000c2", "time": "11:00", "timezone": ZONE }));    with_door(&handle, [Reply::ok(&status(true).to_string()), Reply::ok(r#"{"account":"walk@example.test","gone":true}"#)]);    let sent = ask(&handle, "days.send_to_google", json!({ "timezone": ZONE }));    assert_eq!(sent["said"], json!(["“Call” was deleted in Google Calendar."]));    assert_eq!(one(&handle, "SELECT (trashed_at IS NOT NULL) || ' ' || COALESCE(gcal_id, 'none') AS v FROM cotton_events WHERE id = '00000000-0000-4000-8000-0000000000c2'").as_deref(), Some("1 none"));}/// RULE (CONTRACT §16): a grant that cannot write, or one Google stopped honouring, stops the pass with the line and Connect; nothing is lost, the change waits.#[test]fn a_read_only_or_revoked_grant_asks_to_connect_and_the_change_waits() {    let dir = TempDir::new().unwrap();    let handle = phone(&dir);    zone(&handle);    google_event(&handle);    Heard::google(&handle.client(), &status(true));    ask(&handle, "days.change", json!({ "table": "event", "id": GOOGLE_EVENT, "title": "Long massage", "timezone": ZONE }));    with_door(&handle, [Reply::ok(&status(false).to_string())]);    let sent = ask(&handle, "days.send_to_google", json!({ "timezone": ZONE }));    assert_eq!(sent["reconnect"]["line"], json!("To save changes to Google Calendar, Days needs your permission once more."));    assert_eq!(sent["reconnect"]["connect"]["label"], json!("Connect again"));    with_door(&handle, [Reply::ok(&status(true).to_string()), Reply::json(403, r#"{"code":"reconnect_required","message":"Google no longer honours this grant"}"#)]);    let sent = ask(&handle, "days.send_to_google", json!({ "timezone": ZONE }));    assert_eq!(sent["reconnect"]["line"], json!("Google stopped letting Days change your calendar. Connect it again to send your changes."));    assert_eq!(one(&handle, &format!("SELECT title || ' ' || sync_state AS v FROM cotton_events WHERE id = '{GOOGLE_EVENT}'")).as_deref(), Some("Long massage pending"));    // Read-only heard before Save: refused before anything is saved.    Heard::google(&handle.client(), &status(false));    handle.client().set_object_door(None);    let (code, _) = refused(&handle, "days.change", json!({ "table": "event", "id": GOOGLE_EVENT, "title": "Other", "timezone": ZONE }));    assert_eq!(code, "google_needs_write");}/// RULE (CONTRACT §16): one occurrence of a Google series moved in Days is sent as Google's instance id, in UTC; an all-day event goes as dates, Google's end the day after.#[test]fn an_occurrence_goes_as_its_instance_and_a_whole_day_as_dates() {    let dir = TempDir::new().unwrap();    let handle = phone(&dir);    zone(&handle);    Heard::google(&handle.client(), &status(true));    sql(&handle, "INSERT INTO cotton_events (id, title, starts_at, ends_at, all_day, rrule, gcal_id, gcal_etag, sync_state, account, on_google, timezone, created_at, updated_at) VALUES ('00000000-0000-4000-8000-0000000000d1', 'Standup', '2026-11-16T04:00:00.000Z', '2026-11-16T04:15:00.000Z', 0, 'FREQ=DAILY', 'g-series', '\"s\"', 'synced', 'walk@example.test', 1, 'Asia/Kolkata', '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')");    ask(&handle, "days.change", json!({ "table": "event", "id": "00000000-0000-4000-8000-0000000000d1", "occurrenceAt": "2026-11-23T04:00:00.000Z", "time": "10:00", "timezone": ZONE }));    let exchange = with_door(&handle, [        Reply::ok(&status(true).to_string()),        Reply::ok(r#"{"account":"walk@example.test","gcalId":"g-series_20261123T040000Z","etag":"\"i1\"","attendees":[]}"#),    ]);    let sent = ask(&handle, "days.send_to_google", json!({ "timezone": ZONE }));    let asked: Vec<Value> = exchange.seen().iter().skip(1).map(body).collect();    let ids: Vec<Value> = asked.iter().map(|a| a["gcalId"].clone()).collect();    assert!(ids.contains(&json!("g-series_20261123T040000Z")), "{ids:?}");    let instance = asked.iter().find(|a| a["gcalId"] == json!("g-series_20261123T040000Z")).unwrap();    assert!(instance["event"].get("recurrence").is_none());    sql(&handle, "INSERT INTO cotton_events (id, title, starts_at, ends_at, all_day, on_google, sync_state, created_at, updated_at) VALUES ('00000000-0000-4000-8000-0000000000d2', 'Rose in town', '2026-11-24T00:00:00.000Z', '2026-11-26T23:59:59.999Z', 1, 1, 'pending', '2026-11-01T00:00:00.000Z', '2026-11-01T00:00:00.000Z')");    let exchange = with_door(&handle, [Reply::ok(&status(true).to_string()), Reply::ok(r#"{"account":"walk@example.test","gcalId":"g-d2","etag":"\"d\"","attendees":[]}"#)]);    ask(&handle, "days.send_to_google", json!({ "timezone": ZONE }));    let asked = body(&exchange.seen()[1]);    assert_eq!((asked["event"]["start"].clone(), asked["event"]["end"].clone()), (json!({ "date": "2026-11-24" }), json!({ "date": "2026-11-27" })));    assert_eq!(asked["notify"], json!("none"));}/// RULE (CONTRACT §16, "Also keep my Days events in Google Calendar"): off by default; on, the person's own events from today go to Google, not those before, not an invitation received.#[test]fn keeping_days_events_in_google_sends_the_persons_own_from_today() {    let dir = TempDir::new().unwrap();    let handle = phone(&dir);    zone(&handle);    let soon = add(&handle, "Haircut tomorrow 9am");    sql(&handle, "INSERT INTO cotton_events (id, title, starts_at, ends_at, all_day, created_at, updated_at) VALUES ('00000000-0000-4000-8000-0000000000f1', 'Long ago', '2020-01-01T10:00:00.000Z', '2020-01-01T11:00:00.000Z', 0, '2020-01-01T00:00:00.000Z', '2020-01-01T00:00:00.000Z')");    let mut keep = status(true);    keep["keep"] = json!(true);    let exchange = with_door(&handle, [Reply::ok(&keep.to_string()), Reply::ok(r#"{"account":"walk@example.test","gcalId":"g-k","etag":"\"k\"","attendees":[]}"#)]);    let sent = ask(&handle, "days.send_to_google", json!({ "timezone": ZONE, "today": TODAY }));    assert_eq!(sent["sent"], json!(1));    assert_eq!(body(&exchange.seen()[1])["event"]["summary"], json!("Haircut"));    assert_eq!(one(&handle, &format!("SELECT gcal_id AS v FROM cotton_events WHERE id = '{soon}'")).as_deref(), Some("g-k"));    assert_eq!(one(&handle, "SELECT COALESCE(gcal_id, 'none') AS v FROM cotton_events WHERE id = '00000000-0000-4000-8000-0000000000f1'").as_deref(), Some("none"));    let settings = crate::phone::days_google::shape(Some(&keep), &crate::phone::days_google::At { zone: ZONE.into(), now_ms: 0 }).unwrap();    assert_eq!(settings["keep"], json!({ "label": "Also keep my Days events in Google Calendar", "line": "Your own events go to your Google calendar too, from today on.", "on": true }));}