/** * The pull beside Days' writes (src/google_calendar.ts, CONTRACT ยง16): each * event's guests and their answers in `guest_responses`, sealed like the * title, a guest's answer arriving on its own; a row changed on a phone and * not yet at Google (`sync_state` pending, binned or not, and an insert of * Days' own before the phone wrote Google's id on it) left as it is, never * doubled; events written from Days in two time zones and a series with one * occurrence moved, as the pull brings them back; and a calendar of two * thousand events with guests, at size. Google is test/google.ts's * FakeCalendar, a fake modelled on Google's documented behaviour (its header * says what it models). Every address, title and id is made up. */ import { env, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test"; import { afterEach, describe, expect, it, vi } from "vitest"; import { macRowId, PAGE_SIZE } from "../src/google_calendar.ts"; import { gcalIdOf } from "../src/google_write.ts"; import { bodyAad } from "../src/seal.ts"; import { Store, type StoredRow } from "../src/store.ts"; import { openArrivalRow } from "./arrival_keys.ts"; import { connectAccount, EMAIL, FakeCalendar, google, primary, quiet, revoked, tokens } from "./google.ts"; import { ADMIN, DATABASE_ID, EVENTS_OPEN, http, personalObject } from "./personal.ts"; import { holdsWord } from "./clear-word.ts"; vi.setConfig({ testTimeout: 600_000 }); afterEach(() => { google(tokens, primary, quiet, revoked); }); const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug)); const bearer = (token: string): Record => ({ authorization: `Bearer ${token}` }); type Cal = { phase: string; eventCount: number; pulled: { created: number; updated: number; binned: number } }; async function calendar(slug: string, owner: string): Promise { return (await http<{ accounts: { calendar: Cal }[] }>(slug, "GET", "/v1/google/status", undefined, bearer(owner))).body.accounts[0]!.calendar; } /** The object's alarm run until the pass has landed whole and `asked` holds. */ async function settle(slug: string, owner: string, asked: () => boolean = () => true): Promise { for (let i = 0; i < 20; i++) { await runDurableObjectAlarm(stub(slug)); const c = await calendar(slug, owner); if (c.phase === "synced" && asked()) return c; } throw new Error(`the pass never settled: ${JSON.stringify(await calendar(slug, owner))}`); } async function rows(slug: string): Promise { return runInDurableObject(stub(slug), (_i, state) => [...new Store(state.storage.sql, () => new Date()).scan("event")]); } async function opened(row: StoredRow): Promise> { const aad = bodyAad(DATABASE_ID, "event", row.id); const out = await openArrivalRow(row.data, aad, "event", row.id); for (const p of (row.data.arrival_patches as Record[] | undefined) ?? []) Object.assign(out, await openArrivalRow(p, aad, "event", row.id)); return out; } async function put(slug: string, id: string, data: Record): Promise { const res = await http(slug, "POST", "/v1/admin/import", { rows: [{ verb: "put", table: "event", id, data }] }, ADMIN); expect(res.status, JSON.stringify(res.body)).toBe(200); } const UID = (id: string) => `${id}@google.com`; describe("the pull beside Days' writes", () => { it("brings each event's guests and their answers into guest_responses, sealed like the title, and a guest's answer alone reaches it", async () => { const slug = "gbguests"; const { owner } = await personalObject(slug, { arrival: true }); const cal = new FakeCalendar(); cal.put({ id: "dinner", iCalUID: UID("dinner"), summary: "Dinner", start: { dateTime: "2026-12-05T14:00:00Z" }, end: { dateTime: "2026-12-05T15:30:00Z" }, organizer: { email: EMAIL, self: true }, attendees: [{ email: EMAIL, self: true, organizer: true, responseStatus: "accepted" }, { email: "priya@example.test", displayName: "Priya", responseStatus: "needsAction" }] }); cal.put({ id: "alone", iCalUID: UID("alone"), summary: "Alone", start: { dateTime: "2026-12-06T14:00:00Z" }, end: { dateTime: "2026-12-06T15:00:00Z" } }); google(tokens, cal.route, revoked); await connectAccount(slug, owner); await settle(slug, owner); const id = await macRowId("calendar", UID("dinner")); const first = (await rows(slug)).find((r) => r.id === id)!; expect(first.data).not.toHaveProperty("guest_responses"); expect(JSON.parse(String((await opened(first)).guest_responses))).toEqual([ { email: EMAIL, answer: "accepted", self: true, organizer: true }, { email: "priya@example.test", name: "Priya", answer: "needsAction" }, ]); const alone = (await rows(slug)).find((r) => r.id !== id)!; expect((await opened(alone)).guest_responses).toBe("[]"); // Priya answers in her own calendar: only the etag and her answer change. const asked = cal.asked.length; cal.answer("dinner", "priya@example.test", "tentative"); const c = await settle(slug, owner, () => cal.asked.length > asked); expect(c.pulled.updated).toBeGreaterThanOrEqual(1); const later = (await rows(slug)).find((r) => r.id === id)!; expect(JSON.parse(String((await opened(later)).guest_responses))[1]).toEqual({ email: "priya@example.test", name: "Priya", answer: "tentative" }); const kept = await runInDurableObject(stub(slug), (_i, state) => JSON.stringify([state.storage.sql.exec("SELECT data FROM rows WHERE table_id = 'event'").toArray(), state.storage.sql.exec("SELECT before, after FROM change WHERE table_id = 'event'").toArray()])); for (const w of ["priya@example.test", "Priya", "tentative"]) expect(holdsWord(kept, w), w).toBe(false); }); it("leaves a row waiting for Google as it is, binned or not, and never makes a second row beside it, nor beside an insert of Days' own", async () => { const slug = "gbpending"; const { owner } = await personalObject(slug, EVENTS_OPEN); const cal = new FakeCalendar(); cal.put({ id: "massage", iCalUID: UID("massage"), summary: "Massage, Google's", start: { dateTime: "2026-12-06T10:00:00Z" }, end: { dateTime: "2026-12-06T11:00:00Z" } }); cal.put({ id: "dentist", iCalUID: UID("dentist"), summary: "Dentist", start: { dateTime: "2026-12-07T10:00:00Z" }, end: { dateTime: "2026-12-07T11:00:00Z" } }); const OWN = "5a4b3c2d-1e0f-4a9b-8c7d-6e5f4a3b2c1d"; cal.put({ id: gcalIdOf(OWN), iCalUID: UID(gcalIdOf(OWN)), summary: "Lunch, at Google", start: { dateTime: "2026-12-08T07:00:00Z" }, end: { dateTime: "2026-12-08T08:00:00Z" } }); const massage = await macRowId("calendar", UID("massage")); const dentist = await macRowId("calendar", UID("dentist")); await put(slug, massage, { title: "Massage, as typed", starts_at: "2026-12-06T09:30:00.000Z", gcal_id: "massage", gcal_etag: '"old"', account: EMAIL, sync_state: "pending", on_google: true }); await put(slug, dentist, { title: "Dentist", starts_at: "2026-12-07T10:00:00.000Z", gcal_id: "dentist", gcal_etag: '"old"', account: EMAIL, sync_state: "pending", on_google: true, trashed_at: "2026-11-22T10:00:00.000Z" }); // Days' own event, inserted at Google a moment ago; the phone has not written Google's id on it yet. await put(slug, OWN, { title: "Lunch", starts_at: "2026-12-08T07:00:00.000Z", account: EMAIL, sync_state: "pending", on_google: true }); google(tokens, cal.route, revoked); await connectAccount(slug, owner); await settle(slug, owner); const all = await rows(slug); expect(all.map((r) => r.id).sort()).toEqual([massage, dentist, OWN].sort()); const by = new Map(all.map((r) => [r.id, r.data])); expect(by.get(massage)).toMatchObject({ title: "Massage, as typed", starts_at: "2026-12-06T09:30:00.000Z", sync_state: "pending" }); expect(by.get(dentist)).toMatchObject({ trashed_at: "2026-11-22T10:00:00.000Z", sync_state: "pending" }); expect(by.get(OWN)).toMatchObject({ title: "Lunch", sync_state: "pending" }); expect(by.get(OWN)).not.toHaveProperty("gcal_id"); // The phone's write lands and it marks the row synced: Google's next change comes in again. await put(slug, massage, { ...by.get(massage), sync_state: "synced", gcal_etag: cal.events.get("massage")!.event.etag }); const asked = cal.asked.length; cal.put({ ...cal.events.get("massage")!.event, summary: "Massage, moved at Google", start: { dateTime: "2026-12-06T12:00:00Z" } }); await settle(slug, owner, () => cal.asked.length > asked); expect((await rows(slug)).find((r) => r.id === massage)!.data).toMatchObject({ title: "Massage, moved at Google", starts_at: "2026-12-06T12:00:00.000Z", sync_state: "synced" }); // A whole listing's reconcile bins no waiting row either. cal.gone.add(`v${cal.version}`); cal.purge("dentist"); cal.purge(gcalIdOf(OWN)); const again = cal.asked.length; await settle(slug, owner, () => cal.asked.slice(again).some((u) => u.searchParams.has("timeMin"))); const after = new Map((await rows(slug)).map((r) => [r.id, r.data])); expect(after.get(OWN)!.trashed_at ?? null).toBeNull(); }); it("brings back what Days wrote in two time zones, and a series with one occurrence moved, as Google holds them", async () => { const slug = "gbzones"; const { owner } = await personalObject(slug, EVENTS_OPEN); const cal = new FakeCalendar(); google(tokens, cal.route, revoked); await connectAccount(slug, owner); await settle(slug, owner); const write = (body: Record) => http>(slug, "POST", "/v1/google/events", body, bearer(owner)); const K = "1a1a1a1a-1111-4111-8111-111111111111"; const N = "2b2b2b2b-2222-4222-8222-222222222222"; const S = "3c3c3c3c-3333-4333-8333-333333333333"; const at = (day: string, clock: string, zone: string) => ({ dateTime: `${day}T${clock}:00`, timeZone: zone }); expect((await write({ op: "insert", id: K, event: { summary: "Tea in Kolkata", start: at("2026-12-10", "10:00", "Asia/Kolkata"), end: at("2026-12-10", "11:00", "Asia/Kolkata") }, notify: "none" })).status).toBe(200); expect((await write({ op: "insert", id: N, event: { summary: "Call to New York", start: at("2026-12-10", "10:00", "America/New_York"), end: at("2026-12-10", "10:30", "America/New_York") }, notify: "none" })).status).toBe(200); expect((await write({ op: "insert", id: S, event: { summary: "Standup", start: at("2026-12-01", "09:00", "America/New_York"), end: at("2026-12-01", "09:15", "America/New_York"), recurrence: ["RRULE:FREQ=WEEKLY;BYDAY=TU"] }, notify: "none" })).status).toBe(200); // 8 Dec 09:00 in New York is 14:00Z; it moves to 11:00 there. const one = `${gcalIdOf(S)}_20261208T140000Z`; expect((await write({ op: "patch", gcalId: one, event: { start: at("2026-12-08", "11:00", "America/New_York"), end: at("2026-12-08", "11:15", "America/New_York") }, notify: "none" })).status).toBe(200); const asked = cal.asked.length; await settle(slug, owner, () => cal.asked.length > asked); const all = await rows(slug); const of = (gcal: string) => all.find((r) => r.data.gcal_id === gcal)!.data; expect(of(gcalIdOf(K))).toMatchObject({ starts_at: "2026-12-10T04:30:00.000Z", ends_at: "2026-12-10T05:30:00.000Z", title: "Tea in Kolkata" }); expect(of(gcalIdOf(N))).toMatchObject({ starts_at: "2026-12-10T15:00:00.000Z", ends_at: "2026-12-10T15:30:00.000Z" }); const series = all.find((r) => r.data.gcal_id === gcalIdOf(S))!; expect(series.data).toMatchObject({ rrule: "FREQ=WEEKLY;BYDAY=TU", starts_at: "2026-12-01T14:00:00.000Z" }); expect(of(one)).toMatchObject({ series_id: series.id, original_starts_at: "2026-12-08T14:00:00.000Z", starts_at: "2026-12-08T16:00:00.000Z", rrule: null }); expect(all).toHaveLength(4); }); it("pulls two thousand events with guests at size, sealed, and a later answer to ten of them changes those ten alone", async () => { const slug = "gbsize"; const { owner } = await personalObject(slug, { arrival: true }); const cal = new FakeCalendar(); cal.pageSize = PAGE_SIZE; const N = 2000; const now = Date.now(); for (let i = 0; i < N; i++) { const start = new Date(now + ((i % 300) - 60) * 86_400_000 + (i % 24) * 3_600_000).toISOString().replace(/\.\d{3}Z$/, "Z"); const end = new Date(Date.parse(start) + 3_600_000).toISOString().replace(/\.\d{3}Z$/, "Z"); cal.put({ id: `ev${i}`, iCalUID: UID(`ev${i}`), summary: `Invented event ${i}`, start: { dateTime: start }, end: { dateTime: end }, organizer: { email: EMAIL, self: true }, attendees: [{ email: EMAIL, self: true, organizer: true, responseStatus: "accepted" }, { email: `guest${i % 40}@example.test`, displayName: `Guest ${i % 40}`, responseStatus: "needsAction" }, { email: `other${i % 7}@example.test`, responseStatus: "declined" }] }); } google(tokens, cal.route, revoked); const began = Date.now(); await connectAccount(slug, owner); const c = await settle(slug, owner); const took = Date.now() - began; expect(c.eventCount).toBe(N); console.log(`gbsize: ${N} events with guests pulled sealed in ${took} ms over ${cal.asked.length} pages`); const sample = (await rows(slug)).find((r) => r.data.gcal_id === "ev1234")!; expect(JSON.parse(String((await opened(sample)).guest_responses))).toEqual([ { email: EMAIL, answer: "accepted", self: true, organizer: true }, { email: "guest34@example.test", name: "Guest 34", answer: "needsAction" }, { email: "other2@example.test", answer: "declined" }, ]); const asked = cal.asked.length; for (let i = 0; i < 10; i++) cal.answer(`ev${i * 100}`, `guest${(i * 100) % 40}@example.test`, "accepted"); const d = await settle(slug, owner, () => cal.asked.length > asked); expect(d.pulled).toEqual({ created: 0, updated: 10, binned: 0 }); const answered = (await rows(slug)).find((r) => r.data.gcal_id === "ev300")!; expect(JSON.parse(String((await opened(answered)).guest_responses))[1]).toMatchObject({ answer: "accepted" }); }); });