205 lines · 13.6 KB · TypeScriptRaw
/** * The Google Calendar pull on the object's alarm (src/google_calendar.ts): * a whole first listing over pages, a delta by sync token, a cancelled event * and a cancelled occurrence, the old server's rows found in place, a * forgotten sync token's whole listing and its reconcile, a pass stopped at * its bound, and a grant Google no longer honours. Google is a fake that * answers the calendar as it stands, so the object's own alarm may ask at * any moment without changing what a test sees. */import { env, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test";import { afterEach, describe, expect, it } from "vitest";import { macRowId, PAGES_PER_PASS, PULL_EVERY_MS } from "../src/google_calendar.ts";import { Store, type StoredRow } from "../src/store.ts";import { connectAccount, EMAIL, FakeCalendar, google, primary, quiet, reply, revoked, tokens, type Call } from "./google.ts";import { EVENTS_OPEN, http, personalObject } from "./personal.ts";afterEach(() => { google(tokens, primary, quiet, revoked);});const bearer = (token: string): Record<string, string> => ({ authorization: `Bearer ${token}` });interface Status { account: string; phase: string; syncing: boolean; lastError: string | null; events: number;}/** The first account's calendar block, as `/v1/google/status` answers it. */async function status(slug: string, owner: string): Promise<Status> { const res = await http<{ accounts: { googleEmail: string; calendar: { phase: string; syncing: boolean; lastError: string | null; eventCount: number } }[] }>(slug, "GET", "/v1/google/status", undefined, bearer(owner)); expect(res.status).toBe(200); const a = res.body.accounts[0]!; return { account: a.googleEmail, phase: a.calendar.phase, syncing: a.calendar.syncing, lastError: a.calendar.lastError, events: a.calendar.eventCount };}const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));/** Runs the object's alarm until the account's pass has landed whole (the object's own alarm may have run it already). */async function settle(slug: string, owner: string, until: (s: Status) => boolean = (s) => s.phase === "synced"): Promise<Status> { for (let i = 0; i < 12; i++) { await runDurableObjectAlarm(stub(slug)); const s = await status(slug, owner); if (until(s)) return s; } throw new Error(`the pass never settled: ${JSON.stringify(await status(slug, owner))}`);}/** Every event row of the object, live ones only, keyed by id. */async function events(slug: string): Promise<Map<string, StoredRow>> { return runInDurableObject(stub(slug), (_instance, state) => { const store = new Store(state.storage.sql, () => new Date()); return new Map([...store.scan("event")].map((r) => [r.id, r])); });}const UID = (id: string) => `${id}@google.com`;describe("the Google Calendar pull", () => { it("lists the whole window over pages first, writing each event's columns as the old pull did, under the Mac's ids", async () => { const { owner } = await personalObject("gcfirst", EVENTS_OPEN); const cal = new FakeCalendar(); cal.put({ id: "standup", iCalUID: UID("standup"), summary: " Standup ", description: "notes", location: "Office", start: { dateTime: "2026-10-28T10:00:00+05:30" }, end: { dateTime: "2026-10-28T10:15:00+05:30" }, organizer: { email: EMAIL, self: true } }); cal.put({ id: "holiday", iCalUID: UID("holiday"), summary: "Diwali", start: { date: "2026-11-08" }, end: { date: "2026-11-10" }, organizer: { email: "calendar@group.v.calendar.google.com" } }); cal.put({ id: "weekly", iCalUID: UID("weekly"), summary: "Weekly sync", start: { dateTime: "2026-10-05T12:30:00+05:30", timeZone: "Asia/Kolkata" }, end: { dateTime: "2026-10-05T13:00:00+05:30" }, recurrence: ["RRULE:FREQ=WEEKLY;BYDAY=MO", "EXDATE;TZID=Asia/Kolkata:20261012T123000"], organizer: { email: "boss@example.com" }, attendees: [{ email: EMAIL, self: true, responseStatus: "needsAction" }, { email: "boss@example.com", responseStatus: "accepted" }], }); cal.put({ id: "weekly_20261019T070000Z", iCalUID: UID("weekly"), recurringEventId: "weekly", originalStartTime: { dateTime: "2026-10-19T12:30:00+05:30" }, summary: "Weekly sync (moved)", start: { dateTime: "2026-10-19T15:00:00+05:30" }, end: { dateTime: "2026-10-19T15:30:00+05:30" }, organizer: { email: "boss@example.com" } }); cal.put({ id: "lunch", iCalUID: UID("lunch"), summary: "Lunch", start: { dateTime: "2026-10-30T13:00:00+05:30" }, end: { dateTime: "2026-10-30T14:00:00+05:30" } }); google(tokens, primary, cal.route, revoked); await connectAccount("gcfirst", owner); const s = await settle("gcfirst", owner); expect(s).toMatchObject({ account: EMAIL, phase: "synced", lastError: null, events: 5 }); // Five events at two to a page: three pages, the first with no sync token and a window. expect(cal.asked[0]!.searchParams.has("syncToken")).toBe(false); const rows = await events("gcfirst"); const standup = rows.get(await macRowId("calendar", UID("standup")))!; expect(standup.data).toMatchObject({ title: "Standup", notes: "notes", location: "Office", starts_at: "2026-10-28T04:30:00.000Z", ends_at: "2026-10-28T04:45:00.000Z", all_day: false, rrule: null, exdates: null, organizer_is_self: true, invited: null, my_response: null, gcal_id: "standup", gcal_etag: '"1"', ical_uid: UID("standup"), sync_state: "synced", account: EMAIL, on_google: true, series_id: null, original_starts_at: null }); const holiday = rows.get(await macRowId("calendar", UID("holiday")))!; // Google's end day is exclusive: the 8th and the 9th, midnight to the last millisecond, in the calendar's zone. expect(holiday.data).toMatchObject({ all_day: true, starts_at: "2026-11-07T18:30:00.000Z", ends_at: "2026-11-09T18:29:59.999Z", organizer_is_self: false, invited: "invited" }); const weekly = rows.get(await macRowId("calendar", UID("weekly")))!; expect(weekly.data).toMatchObject({ rrule: "FREQ=WEEKLY;BYDAY=MO", exdates: ["2026-10-12T07:00:00.000Z"], my_response: "needs_action", organizer_is_self: false }); const moved = rows.get(await macRowId("calendar", `${UID("weekly")}|2026-10-19T07:00:00.000Z`))!; expect(moved.data).toMatchObject({ title: "Weekly sync (moved)", series_id: weekly.id, original_starts_at: "2026-10-19T07:00:00.000Z", rrule: null, exdates: null, gcal_id: "weekly_20261019T070000Z", starts_at: "2026-10-19T09:30:00.000Z" }); }); it("takes only what changed by the sync token: a change, a new event, a cancelled occurrence into the series' exdates, a cancelled event binned with its occurrences", async () => { const { owner } = await personalObject("gcdelta", EVENTS_OPEN); const cal = new FakeCalendar(); cal.put({ id: "a", iCalUID: UID("a"), summary: "A", start: { dateTime: "2026-10-28T10:00:00Z" }, end: { dateTime: "2026-10-28T11:00:00Z" } }); cal.put({ id: "series", iCalUID: UID("series"), summary: "Series", start: { dateTime: "2026-10-05T07:00:00Z" }, end: { dateTime: "2026-10-05T08:00:00Z" }, recurrence: ["RRULE:FREQ=WEEKLY"] }); cal.put({ id: "gone", iCalUID: UID("gone"), summary: "Gone", start: { dateTime: "2026-10-29T10:00:00Z" }, end: { dateTime: "2026-10-29T11:00:00Z" }, recurrence: ["RRULE:FREQ=DAILY;COUNT=3"] }); cal.put({ id: "gone_20261030T100000Z", iCalUID: UID("gone"), recurringEventId: "gone", originalStartTime: { dateTime: "2026-10-30T10:00:00Z" }, summary: "Gone, moved", start: { dateTime: "2026-10-30T12:00:00Z" }, end: { dateTime: "2026-10-30T13:00:00Z" } }); google(tokens, primary, cal.route, revoked); await connectAccount("gcdelta", owner); await settle("gcdelta", owner); const asked = cal.asked.length; cal.put({ id: "a", iCalUID: UID("a"), summary: "A, renamed", start: { dateTime: "2026-10-28T10:30:00Z" }, end: { dateTime: "2026-10-28T11:00:00Z" } }); cal.put({ id: "b", iCalUID: UID("b"), summary: "B", start: { dateTime: "2026-11-02T10:00:00Z" }, end: { dateTime: "2026-11-02T11:00:00Z" } }); // Google says a cancelled occurrence by its id alone. cal.events.set("series_20261019T070000Z", { event: { id: "series_20261019T070000Z", status: "cancelled" }, version: ++cal.version }); cal.cancel("gone"); const s = await settle("gcdelta", owner, (x) => x.phase === "synced" && cal.asked.length > asked); expect(cal.asked.slice(asked).every((u) => u.searchParams.has("syncToken") || u.searchParams.has("pageToken"))).toBe(true); expect(s.events).toBe(3); const rows = await events("gcdelta"); expect(rows.get(await macRowId("calendar", UID("a")))!.data).toMatchObject({ title: "A, renamed", starts_at: "2026-10-28T10:30:00.000Z" }); expect(rows.get(await macRowId("calendar", UID("b")))!.data.title).toBe("B"); expect(rows.get(await macRowId("calendar", UID("series")))!.data.exdates).toEqual(["2026-10-19T07:00:00.000Z"]); expect(rows.has(await macRowId("calendar", UID("gone")))).toBe(false); expect(rows.has(await macRowId("calendar", `${UID("gone")}|2026-10-30T10:00:00.000Z`))).toBe(false); }); it("lands on the rows the old server made (a random id, the account and Google's id), never beside them", async () => { const { owner } = await personalObject("gclegacy", EVENTS_OPEN); const legacy = "b8b33d3e-0c77-47d3-823d-53ed48443d5f"; const made = await http("gclegacy", "POST", "/v1/admin/import", { rows: [{ verb: "put", table: "event", id: legacy, data: { title: "Call", starts_at: "2026-10-28T09:00:00.000Z", gcal_id: "m4rbf", gcal_etag: '"old"', sync_state: "synced", ical_uid: UID("m4rbf"), account: EMAIL, on_google: false } }] }, { authorization: "Bearer test-admin-token" }); expect(made.status, JSON.stringify(made.body)).toBe(200); const cal = new FakeCalendar(); cal.put({ id: "m4rbf", iCalUID: UID("m4rbf"), summary: "Call with Bella", start: { dateTime: "2026-10-28T09:00:00Z" }, end: { dateTime: "2026-10-28T10:00:00Z" } }); google(tokens, primary, cal.route, revoked); await connectAccount("gclegacy", owner); await settle("gclegacy", owner); const rows = [...(await events("gclegacy")).values()]; expect(rows.map((r) => r.id)).toEqual([legacy]); expect(rows[0]!.data).toMatchObject({ title: "Call with Bella", gcal_etag: '"1"', on_google: true }); }); it("lists the whole window again when Google forgets the sync token, and bins what it no longer holds", async () => { const { owner } = await personalObject("gcgone", EVENTS_OPEN); const cal = new FakeCalendar(); cal.put({ id: "keep", iCalUID: UID("keep"), summary: "Keep", start: { dateTime: "2026-10-28T10:00:00Z" }, end: { dateTime: "2026-10-28T11:00:00Z" } }); cal.put({ id: "lost", iCalUID: UID("lost"), summary: "Lost", start: { dateTime: "2026-10-29T10:00:00Z" }, end: { dateTime: "2026-10-29T11:00:00Z" } }); google(tokens, primary, cal.route, revoked); await connectAccount("gcgone", owner); await settle("gcgone", owner); expect((await events("gcgone")).size).toBe(2); cal.gone.add(`v${cal.version}`); cal.purge("lost"); const asked = cal.asked.length; const s = await settle("gcgone", owner, (x) => x.phase === "synced" && cal.asked.slice(asked).some((u) => u.searchParams.has("timeMin"))); expect(s.events).toBe(1); const rows = await events("gcgone"); expect([...rows.values()].map((r) => r.data.gcal_id)).toEqual(["keep"]); }); it("stops a pass at its bound and carries on at the next alarm, soon", async () => { const { owner } = await personalObject("gcbound", EVENTS_OPEN); const cal = new FakeCalendar(); const total = cal.pageSize * PAGES_PER_PASS + 3; for (let i = 0; i < total; i++) cal.put({ id: `e${i}`, iCalUID: UID(`e${i}`), summary: `E${i}`, start: { dateTime: `2026-11-${String((i % 28) + 1).padStart(2, "0")}T10:00:00Z` } }); google(tokens, primary, cal.route, revoked); await connectAccount("gcbound", owner); const part = await settle("gcbound", owner, (x) => x.phase === "syncing" || x.phase === "synced"); if (part.phase === "syncing") { expect(part.events).toBe(cal.pageSize * PAGES_PER_PASS); const alarm = await runInDurableObject(stub("gcbound"), (_i, state) => state.storage.getAlarm()); expect(alarm! - Date.now()).toBeLessThanOrEqual(30_000); } expect((await settle("gcbound", owner)).events).toBe(total); }); it("stops asking when Google no longer honours the grant: the phase says reconnect, and no later alarm calls Google", async () => { const { owner } = await personalObject("gcrevoked", EVENTS_OPEN); const cal = new FakeCalendar(); const calls: Call[] = google( (call) => (call.form.grant_type === "refresh_token" ? reply(400, { error: "invalid_grant", error_description: "Token has been expired or revoked." }) : null), tokens, primary, cal.route, ); await connectAccount("gcrevoked", owner); const s = await settle("gcrevoked", owner, (x) => x.phase === "reconnect"); expect(s.lastError).toBe("reconnect_required"); const before = calls.length; await runDurableObjectAlarm(stub("gcrevoked")); await runDurableObjectAlarm(stub("gcrevoked")); expect(calls.length).toBe(before); expect(cal.asked).toEqual([]); const { alarm, indexing } = await runInDurableObject(stub("gcrevoked"), async (_i, state) => ({ alarm: await state.storage.getAlarm(), indexing: state.storage.sql.exec("SELECT 1 FROM meta WHERE key = 'order_indexes_wanted'").toArray().length > 0, })); // READ COST (7274fe1d24): an index the alarm still owes (a lookup a request asked for) brings the alarm round soon, // for itself; Google is still not called (`calls` above). Without one, nothing is due before the next pull. if (!indexing) expect(alarm === null || alarm - Date.now() > PULL_EVERY_MS).toBe(true); });});