171 lines · 12.1 KB · TypeScriptRaw
/** * Days' writes to Google Calendar through the object (src/google_write.ts, * CONTRACT §16): an insert with guests mailed once, a patch and a delete with * Google's etag, Google changing the event first (412 → 200 changed with * Google's copy), an event Google no longer holds, one occurrence of a series, * a read-only grant, a grant Google no longer honours, and an outage. Google * is test/google.ts's FakeCalendar: a fake modelled on Google's documented * behaviour (its header says what it models), never Google itself. Every * address, title and id is made up. */import { afterEach, describe, expect, it, vi } from "vitest";import { gcalIdOf } from "../src/google_write.ts";import { connectAccount, EMAIL, FakeCalendar, google, GRANTED_READONLY, primary, quiet, reply, revoked, tokens, tokensWith } from "./google.ts";import { http, personalObject } from "./personal.ts";import { holdsWord } from "./clear-word.ts";vi.setConfig({ testTimeout: 180_000 });afterEach(() => { google(tokens, primary, quiet, revoked);});const bearer = (token: string): Record<string, string> => ({ authorization: `Bearer ${token}` });type Body = Record<string, unknown>;async function connected(slug: string, cal: FakeCalendar, scope?: string): Promise<(body: Body) => Promise<{ status: number; body: Body }>> { const { owner } = await personalObject(slug); google(scope ? tokensWith(scope) : tokens, cal.route, revoked); const done = await connectAccount(slug, owner); expect(done.status, done.text).toBe(200); return (body) => http<Body>(slug, "POST", "/v1/google/events", body, bearer(owner));}const ROW = "0b6f2a1e-3c4d-4e5f-8a9b-0c1d2e3f4a5b";const dinner = { summary: "Dinner at the Brass Spoon", location: "Ferrous lane", start: { dateTime: "2026-12-05T19:30:00", timeZone: "Asia/Kolkata" }, end: { dateTime: "2026-12-05T21:00:00", timeZone: "Asia/Kolkata" }, attendees: [{ email: "priya@example.test", displayName: "Priya" }, { email: "akash@example.test" }],};describe("writing to Google Calendar", () => { it("inserts an event with its guests under the id the Days row names, mails them once, and an insert asked again is the same event", async () => { const cal = new FakeCalendar(); const write = await connected("gwinsert", cal); const made = await write({ op: "insert", id: ROW, event: dinner, notify: "all" }); expect(made.status, JSON.stringify(made.body)).toBe(200); expect(made.body).toEqual({ account: EMAIL, gcalId: gcalIdOf(ROW), etag: expect.any(String), attendees: [ { email: "priya@example.test", displayName: "Priya", responseStatus: "needsAction" }, { email: "akash@example.test", responseStatus: "needsAction" }, ], }); const held = cal.events.get(gcalIdOf(ROW))!.event; expect(held).toMatchObject({ summary: "Dinner at the Brass Spoon", start: { dateTime: "2026-12-05T19:30:00+05:30", timeZone: "Asia/Kolkata" }, organizer: { email: EMAIL, self: true } }); // The answer was lost; the core asks again: Google holds it by the id, nobody is mailed twice. const again = await write({ op: "insert", id: ROW, event: dinner, notify: "all" }); expect(again.status).toBe(200); expect(again.body).toMatchObject({ gcalId: gcalIdOf(ROW), etag: made.body.etag }); expect(cal.written.filter((w) => w.method === "POST" && w.status === 200)).toEqual([expect.objectContaining({ sendUpdates: "all", id: gcalIdOf(ROW) })]); expect([...cal.events.keys()]).toEqual([gcalIdOf(ROW)]); }); it("patches and deletes with Google's etag; Google's change first is answered with Google's copy; a deleted event is gone", async () => { const cal = new FakeCalendar(); cal.put({ id: "massage", iCalUID: "massage@google.com", summary: "Massage", start: { dateTime: "2026-12-06T10:00:00Z" }, end: { dateTime: "2026-12-06T11:00:00Z" }, organizer: { email: EMAIL, self: true } }); const write = await connected("gwpatch", cal); const etag = String(cal.events.get("massage")!.event.etag); const moved = await write({ op: "patch", gcalId: "massage", etag, event: { start: { dateTime: "2026-12-06T15:30:00+05:30" }, end: { dateTime: "2026-12-06T16:30:00+05:30" } }, notify: "none" }); expect(moved.status, JSON.stringify(moved.body)).toBe(200); expect(moved.body).toMatchObject({ account: EMAIL, gcalId: "massage", attendees: [] }); expect(moved.body.etag).not.toBe(etag); expect(cal.events.get("massage")!.event).toMatchObject({ summary: "Massage", start: { dateTime: "2026-12-06T15:30:00+05:30" } }); expect(cal.written.at(-1)).toMatchObject({ method: "PATCH", ifMatch: etag, sendUpdates: "none" }); // Someone changes it in Google Calendar; Days still holds the etag before. cal.put({ ...cal.events.get("massage")!.event, summary: "Massage, Google's" }); const late = await write({ op: "patch", gcalId: "massage", etag: moved.body.etag, event: { summary: "Massage, Days'" }, notify: "none" }); // Answered 200, not a refusal: the phone's transport keeps no refusal's body, and the core needs Google's copy. expect(late.status).toBe(200); expect(late.body).toMatchObject({ account: EMAIL, changed: true, event: { id: "massage", summary: "Massage, Google's", etag: cal.events.get("massage")!.event.etag } }); expect(cal.events.get("massage")!.event.summary).toBe("Massage, Google's"); expect(await write({ op: "delete", gcalId: "massage", etag: moved.body.etag, notify: "none" })).toMatchObject({ status: 200, body: { changed: true, event: { id: "massage" } } }); const gone = await write({ op: "delete", gcalId: "massage", etag: String(cal.events.get("massage")!.event.etag), notify: "all" }); expect(gone.status).toBe(200); expect(gone.body).toEqual({ account: EMAIL, gcalId: "massage", deleted: true }); expect(cal.events.get("massage")!.event.status).toBe("cancelled"); expect(await write({ op: "patch", gcalId: "massage", event: { summary: "Too late" }, notify: "none" })).toEqual({ status: 200, body: { account: EMAIL, gone: true } }); expect((await write({ op: "delete", gcalId: "massage", notify: "none" })).body).toEqual({ account: EMAIL, gone: true }); expect(await write({ op: "patch", gcalId: "neverheld", event: { summary: "x" }, notify: "none" })).toEqual({ status: 200, body: { account: EMAIL, gone: true } }); // A stale etag on an event Google has since deleted is gone too, not changed. expect(await write({ op: "patch", gcalId: "massage", etag: '"stale"', event: { summary: "x" }, notify: "none" })).toEqual({ status: 200, body: { account: EMAIL, gone: true } }); }); it("changes one occurrence of a series by its occurrence id, and leaves the series", async () => { const cal = new FakeCalendar(); const write = await connected("gwseries", cal); const SERIES = "7d0c5b1a-2e3f-4a5b-9c6d-7e8f9a0b1c2d"; const made = await write({ op: "insert", id: SERIES, event: { summary: "Yoga", start: { dateTime: "2026-12-01T07:00:00", timeZone: "Asia/Kolkata" }, end: { dateTime: "2026-12-01T08:00:00", timeZone: "Asia/Kolkata" }, recurrence: ["RRULE:FREQ=WEEKLY;BYDAY=TU"] }, notify: "none" }); expect(made.status, JSON.stringify(made.body)).toBe(200); const master = gcalIdOf(SERIES); const one = `${master}_20261208T013000Z`; const moved = await write({ op: "patch", gcalId: one, event: { start: { dateTime: "2026-12-08T08:00:00", timeZone: "Asia/Kolkata" }, end: { dateTime: "2026-12-08T09:00:00", timeZone: "Asia/Kolkata" } }, notify: "none" }); expect(moved.status, JSON.stringify(moved.body)).toBe(200); expect(moved.body.gcalId).toBe(one); expect(cal.events.get(one)!.event).toMatchObject({ recurringEventId: master, originalStartTime: { dateTime: "2026-12-08T01:30:00Z" }, start: { dateTime: "2026-12-08T08:00:00+05:30" }, summary: "Yoga" }); expect(cal.events.get(master)!.event).toMatchObject({ recurrence: ["RRULE:FREQ=WEEKLY;BYDAY=TU"], start: { dateTime: "2026-12-01T07:00:00+05:30" } }); const skipped = await write({ op: "delete", gcalId: `${master}_20261215T013000Z`, notify: "none" }); expect(skipped.status).toBe(200); expect(cal.events.get(`${master}_20261215T013000Z`)!.event).toMatchObject({ status: "cancelled", recurringEventId: master }); }); it("refuses a read-only grant before Google is asked, and marks an account Google says cannot write", async () => { const cal = new FakeCalendar(); const write = await connected("gwreadonly", cal, GRANTED_READONLY); const asked = cal.written.length; expect(await write({ op: "insert", event: dinner, notify: "all" })).toMatchObject({ status: 403, body: { code: "google_needs_write", message: expect.any(String) } }); expect(await write({ op: "insert", account: EMAIL, event: dinner, notify: "all" })).toMatchObject({ status: 403, body: { code: "google_needs_write", message: expect.any(String) } }); expect(cal.written.length).toBe(asked); const cal2 = new FakeCalendar(); const write2 = await connected("gwscope", cal2); cal2.writable = false; expect(await write2({ op: "insert", event: dinner, notify: "all" })).toMatchObject({ status: 403, body: { code: "google_needs_write", message: expect.any(String) } }); google(tokens, cal2.route, revoked); }); it("sends the account to reconnect when Google no longer honours the grant, and asks Google nothing more", async () => { const cal = new FakeCalendar(); const { owner } = await personalObject("gwrevoked"); google(tokens, cal.route, revoked); await connectAccount("gwrevoked", owner); const calls = google((call) => (call.form.grant_type === "refresh_token" ? reply(400, { error: "invalid_grant", error_description: "Token has been expired or revoked." }) : null), cal.route); const write = (body: Body) => http<Body>("gwrevoked", "POST", "/v1/google/events", body, bearer(owner)); expect(await write({ op: "insert", event: dinner, notify: "all" })).toMatchObject({ status: 403, body: { code: "reconnect_required", message: expect.any(String) } }); const s = await http<{ accounts: { calendar: { phase: string } }[] }>("gwrevoked", "GET", "/v1/google/status", undefined, bearer(owner)); expect(s.body.accounts[0]!.calendar.phase).toBe("reconnect"); const before = calls.length; expect(await write({ op: "insert", event: dinner, notify: "all" })).toMatchObject({ status: 403, body: { code: "reconnect_required", message: expect.any(String) } }); expect(calls.length).toBe(before); expect(cal.written).toEqual([]); }); it("answers google_unavailable when Google is down, refuses a malformed write by name, and keeps none of the event's words", async () => { const cal = new FakeCalendar(); const write = await connected("gwdown", cal); cal.writable = "down"; expect(await write({ op: "insert", event: dinner, notify: "all" })).toMatchObject({ status: 503, body: { code: "google_unavailable", message: expect.any(String) } }); cal.writable = true; expect((await write({ op: "rename", notify: "all" })).status).toBe(400); expect((await write({ op: "patch", event: { summary: "x" }, notify: "all" })).status).toBe(400); expect((await write({ op: "insert", event: { summary: "No time" }, notify: "all" })).status).toBe(400); expect((await write({ op: "insert", event: dinner, notify: "loud" })).status).toBe(400); expect((await write({ op: "insert", event: { ...dinner, attendees: [{ email: "not an address" }] }, notify: "all" })).status).toBe(400); expect((await write({ op: "insert", account: "someone@example.test", event: dinner, notify: "all" })).status).toBe(404); expect((await http("gwdown", "POST", "/v1/google/events", { op: "insert", event: dinner })).status).toBe(403); const ok = await write({ op: "insert", event: dinner, notify: "none" }); expect(ok.status).toBe(200); const { runInDurableObject, env } = await import("cloudflare:test"); const kept = await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName("gwdown")), (_i, state) => JSON.stringify([state.storage.sql.exec("SELECT * FROM rows").toArray(), state.storage.sql.exec("SELECT * FROM change").toArray(), state.storage.sql.exec("SELECT * FROM meta").toArray()])); for (const w of ["Brass Spoon", "Ferrous", "priya@example.test"]) expect(holdsWord(kept, w), w).toBe(false); });});