/** * The Google Calendar pull, on the object's own alarm (src/google.ts holds * the grant): each connected account's primary calendar into the `event` * table, through the object's writer, so the change log and the phones see * every row it makes, changes or bins. * * A PASS. `events.list` with `singleEvents=false` (a series is its master and * its moved occurrences, as the old server and the Mac's CalDAV read keep * it), 250 to a page, at most PAGES_PER_PASS pages; a pass that stops at its * bound keeps Google's `pageToken` and carries on at the next alarm. With a * `syncToken` only what changed comes; without one (the first pass, or after * Google answers 410 for a token it forgot) the whole window from 90 days * back to 400 ahead comes, and at its end every Google row of the account in * that window that no page carried is binned (Google leaves a deleted event * out of a whole listing rather than saying it was cancelled). The sync token * is kept only when the last page has landed. * * A ROW. An event Google made is found by (`account`, `gcal_id`), else by the * id the Mac's CalDAV read gives the same invite (`row_id("calendar", uid)`, * crates/cotton-mac/src/calendar/map.rs), so either reader lands on the one * row; a new row takes that id. Columns keep the old server's meanings * (crates/cotton-server google/map.rs before f1d43c110): ISO instants in UTC, * an all-day event from local midnight to 23:59:59.999 of its last day in the * calendar's zone, `rrule` the first RRULE line, `exdates` a JSON list of * instants, `sync_state` "synced". A moved occurrence is its own row under its * series (`series_id`, `original_starts_at`); a cancelled occurrence joins the * series' `exdates`; a cancelled event bins its row, and its occurrences'. * `guest_responses` is the event's guests and their answers, a JSON list * `[{ email, name?, answer, self?, organizer? }]` (`answer` Google's * responseStatus as Google says it; "[]" for none), sealed like the title. * Google gives an event a new etag when a guest answers, so an answer alone * reaches a sealed row too. * * DAYS' OWN CHANGES WAIT. A row whose `sync_state` is "pending" was changed * on a phone and is on its way to Google (src/google_write.ts): the pull * leaves it as it is, binned or not, and never makes a second row beside it. * An event Days inserted carries the Days row's id as its Google id * (`google_write.ts` `gcalIdOf`), so the pull finds that row even before the * phone has written Google's id on it. * * REFUSALS. A grant Google no longer honours (invalid_grant, a 401, a scope * taken back) sets the account's phase to `reconnect` and it is not asked * again until the person connects anew; a rate limit, a disabled API or a * Google outage is said in `last_error` and the next pass tries again at the * cadence. A pass never throws: an alarm that threw would be retried at once. */ import type { Env } from "./env.ts"; import type { Engine, Outcome } from "./engine.ts"; import { client, googleUrls, readAccounts, refreshTokenOf, saveAccount, GRANT_UNOPENED, type Account, type GoogleHost, type PassError } from "./google.ts"; import { equalSql } from "./mcp/tools/records/where.ts"; import { joinMoment } from "./mcp/tools/records/zone.ts"; import { addDays } from "./protocol.ts"; import type { Data } from "./mcp/context.ts"; import type { StoredRow } from "./store.ts"; import { rowIdOf } from "./google_write.ts"; export const PAGE_SIZE = 250; /** Pages one alarm reads: 1000 events, well inside a Durable Object's subrequest and CPU limits. */ export const PAGES_PER_PASS = 4; /** A whole listing's window, from now. */ export const WINDOW_BACK_DAYS = 90; export const WINDOW_AHEAD_DAYS = 400; /** How often a connected account is pulled, and how soon a pass that stopped at its bound carries on. */ export const PULL_EVERY_MS = 15 * 60 * 1000; export const CARRY_ON_MS = 30 * 1000; const EVENT = "event"; /** The Mac's CalDAV read names a calendar row by this source (crates/cotton-mac/src/ids.rs). */ const MAC_SOURCE = "calendar"; export const SEEN_SCHEMA = "CREATE TABLE IF NOT EXISTS google_seen (account TEXT NOT NULL, gcal_id TEXT NOT NULL, PRIMARY KEY (account, gcal_id))"; /** One Google Calendar event as `events.list` answers it, the fields read here. */ export interface GEvent { id: string; status?: string; etag?: string; summary?: string; description?: string; location?: string; start?: { date?: string; dateTime?: string; timeZone?: string }; end?: { date?: string; dateTime?: string; timeZone?: string }; recurrence?: string[]; recurringEventId?: string; originalStartTime?: { date?: string; dateTime?: string }; iCalUID?: string; organizer?: { email?: string; self?: boolean }; attendees?: { email?: string; displayName?: string; self?: boolean; organizer?: boolean; responseStatus?: string }[]; } interface Listing { items?: GEvent[]; /** The calendar's own zone, said with every listing: an account takes it from its first. */ timeZone?: string; nextPageToken?: string; nextSyncToken?: string; } /** A refusal from Google, as a pass records it (and a write answers it, src/google_write.ts). */ export class Stop extends Error { readonly code: string; readonly reconnect: boolean; constructor(code: string, message: string, reconnect = false) { super(message); this.code = code; this.reconnect = reconnect; } } /** * Every connected account pulled once, each by its own bound. Answers when * the next pass should come: soon when one stopped at its bound, at the * cadence while any account can be pulled, never (null) when none can. */ export async function pullAll(host: GoogleHost): Promise { let more = false; for (const account of readAccounts(host.store)) { if (account.phase === "reconnect") continue; more = (await pull(host, account)) || more; } if (more) return CARRY_ON_MS; return readAccounts(host.store).some((a) => a.phase !== "reconnect") ? PULL_EVERY_MS : null; } /** One account's pass; true when it stopped at its bound with pages left. */ export async function pull(host: GoogleHost, start: Account): Promise { host.sql.exec(SEEN_SCHEMA); let account: Account = { ...start, phase: "syncing", pulled: { created: 0, updated: 0, binned: 0 } }; const now = new Date(); try { const token = await accessToken(host, account); for (let n = 0; n < PAGES_PER_PASS; n++) { const whole = account.sync_token === null; if (whole && account.page_token === null) { // A whole listing begins: its window is fixed for every page, and nothing is seen yet. account.window = { from: new Date(now.getTime() - WINDOW_BACK_DAYS * 86_400_000).toISOString(), to: new Date(now.getTime() + WINDOW_AHEAD_DAYS * 86_400_000).toISOString() }; host.sql.exec("DELETE FROM google_seen WHERE account = ?", account.email); } const listing = await list(host.env, account, token); if (listing === "gone") { // Google forgot the sync token: the whole window again, then the reconcile. account = { ...account, sync_token: null, page_token: null, window: null }; continue; } const items = listing.items ?? []; if (listing.timeZone && account.timezone !== listing.timeZone) account = { ...account, timezone: listing.timeZone }; const prepared = await prepare(host, account, items); const zone = account.timezone ?? host.zone; // Sealed events take the pull's words sealed at arrival: a new one whole, a held one as an arrival patch (src/arrival_seam.ts). // The write may run twice, so it works on its own copy of the account and answers it. const before = account; account = await host.writeSealed((engine, version, outcome) => { const next: Account = { ...before, pulled: { ...before.pulled } }; for (const item of ordered(items)) apply(engine, version, outcome, next, prepared, item, zone); if (whole) for (const item of items) host.sql.exec("INSERT OR IGNORE INTO google_seen (account, gcal_id) VALUES (?, ?)", next.email, item.id); if (listing.nextPageToken) next.page_token = listing.nextPageToken; else { if (whole && next.window) reconcile(engine, version, outcome, next, next.window, host.sql); next.page_token = null; next.window = null; next.sync_token = listing.nextSyncToken ?? null; next.synced_at = new Date().toISOString(); } next.last_error = null; next.last_pass_at = new Date().toISOString(); next.phase = next.page_token ? "syncing" : "synced"; saveAccount(host.store, next); return next; }); if (!account.page_token) return false; } return true; } catch (error) { const stop = error instanceof Stop ? error : new Stop("sync_failed", error instanceof Error ? error.message : String(error)); if (!(error instanceof Stop)) console.error("cottondb: google calendar pass", stop.message); const said: PassError = { code: stop.code, message: stop.message, at: new Date().toISOString() }; host.write(() => saveAccount(host.store, { ...account, phase: stop.reconnect ? "reconnect" : account.sync_token ? "synced" : "waiting", last_error: said, last_pass_at: said.at })); return false; } } // ── Google ─────────────────────────────────────────────────────────────── /** A fresh access token from the account's refresh token, once a pass (and once a write). */ export async function accessToken(host: GoogleHost, account: Account): Promise { const refresh = await refreshTokenOf(host, account); if (!refresh) throw new Stop("reconnect_required", `${GRANT_UNOPENED}: connect Google again`, true); const c = client(host.env); const res = await fetch(googleUrls(host.env).token, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: refresh, client_id: c.id, client_secret: c.secret }).toString(), }); const body = (await res.json().catch(() => ({}))) as { access_token?: string; error?: string; error_description?: string }; if (res.ok && body.access_token) return body.access_token; if (body.error === "invalid_grant" || body.error === "unauthorized_client" || body.error === "invalid_client") { throw new Stop("reconnect_required", `Google no longer honours this grant (${body.error}): connect Google again`, true); } throw new Stop(res.status === 429 ? "rate_limited" : "sync_failed", `Google's token endpoint answered ${res.status}${body.error ? ` ${body.error}` : ""}`); } /** One page of the primary calendar, or "gone" when Google forgot the sync token. */ async function list(env: Env, account: Account, token: string): Promise { const params = new URLSearchParams({ maxResults: String(PAGE_SIZE), singleEvents: "false" }); if (account.page_token) params.set("pageToken", account.page_token); else if (account.sync_token) params.set("syncToken", account.sync_token); else if (account.window) { params.set("timeMin", account.window.from); params.set("timeMax", account.window.to); } const res = await fetch(`${googleUrls(env).calendar}/calendars/primary/events?${params.toString()}`, { headers: { authorization: `Bearer ${token}` } }); if (res.ok) return (await res.json()) as Listing; if (res.status === 410) return "gone"; const body = (await res.json().catch(() => ({}))) as { error?: { message?: string; errors?: { reason?: string }[] } }; const reason = body.error?.errors?.[0]?.reason ?? ""; const message = `Google Calendar answered ${res.status}${body.error?.message ? `: ${body.error.message}` : ""}`; if (res.status === 401 || reason === "insufficientPermissions" || reason === "forbidden") throw new Stop("reconnect_required", message, true); if (res.status === 429 || reason === "rateLimitExceeded" || reason === "userRateLimitExceeded") throw new Stop("rate_limited", message); if (reason === "accessNotConfigured") throw new Stop("api_disabled", message); throw new Stop("sync_failed", message); } // ── rows ───────────────────────────────────────────────────────────────── /** UUID v5 under RFC 4122's URL namespace over `cotton-mac::`: the Mac's `ids::row_id`. */ export async function macRowId(source: string, externalId: string): Promise { const ns = new Uint8Array([0x6b, 0xa7, 0xb8, 0x11, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8]); const name = new TextEncoder().encode(`cotton-mac:${source}:${externalId}`); const input = new Uint8Array(ns.length + name.length); input.set(ns, 0); input.set(name, ns.length); const bytes = new Uint8Array(await crypto.subtle.digest("SHA-1", input)).slice(0, 16); bytes[6] = (bytes[6]! & 0x0f) | 0x50; bytes[8] = (bytes[8]! & 0x3f) | 0x80; const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join(""); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`; } /** The ids a page's events take when new, worked out before the write (hashing is asynchronous, the write is not). */ type Prepared = Map; async function prepare(host: GoogleHost, account: Account, items: GEvent[]): Promise { const zone = account.timezone ?? host.zone; const ids: Prepared = new Map(); for (const item of items) { const original = item.recurringEventId || instanceOf(item.id) ? originalOf(item, zone) : null; ids.set(item.id, await newId(account, item, original)); // A moved occurrence's series may be new on this page too; it is found by the master's own id. const master = item.recurringEventId ?? instanceOf(item.id)?.master; if (master && item.iCalUID && !ids.has(master)) ids.set(master, await macRowId(MAC_SOURCE, item.iCalUID)); } return ids; } function newId(account: Account, item: GEvent, original: string | null): Promise { if (!item.iCalUID) return macRowId("google", `${account.email}|${item.id}`); return macRowId(MAC_SOURCE, original ? `${item.iCalUID}|${original}` : item.iCalUID); } /** Masters before their occurrences, so an occurrence finds its series on the same page. */ function ordered(items: GEvent[]): GEvent[] { return [...items.filter((i) => !i.recurringEventId), ...items.filter((i) => i.recurringEventId)]; } /** Google's id for one occurrence: `_` or `_`. */ function instanceOf(id: string): { master: string; at: string } | null { const m = /^(.+)_(\d{8})(T\d{6}Z)?$/.exec(id); return m ? { master: m[1]!, at: m[2]! + (m[3] ?? "") } : null; } /** The instant an occurrence was moved from, as ISO: `originalStartTime`, else the id's own suffix. */ function originalOf(item: GEvent, zone: string): string | null { const o = item.originalStartTime; if (o?.dateTime) return iso(o.dateTime); if (o?.date) return joinMoment(o.date, null, zone); const at = instanceOf(item.id)?.at; if (!at) return null; const day = `${at.slice(0, 4)}-${at.slice(4, 6)}-${at.slice(6, 8)}`; return at.length === 8 ? joinMoment(day, null, zone) : iso(`${day}T${at.slice(9, 11)}:${at.slice(11, 13)}:${at.slice(13, 15)}Z`); } function iso(value: string): string { return new Date(value).toISOString(); } /** * The account's row for a Google id, binned ones too: by (`account`, * `gcal_id`), else the Days row an insert of Days named (its id is the Google * id's), else by the id it would take. */ function rowOf(engine: Engine, account: Account, gcalId: string, id: string | undefined): StoredRow | null { const store = engine.store; const byGoogle = store.select(EVENT, [equalSql("account", account.email), equalSql("gcal_id", gcalId)], "created_at, id", 1)[0]; if (byGoogle) return byGoogle; const days = rowIdOf(gcalId); const named = days ? store.get(EVENT, days) : null; if (named && (named.data.account == null || named.data.account === account.email)) return named; return id ? store.get(EVENT, id) : null; } /** A row changed on a phone and not yet at Google: the pull leaves it as it is. */ function waiting(row: StoredRow | null): boolean { return row?.data.sync_state === "pending"; } /** An event's guests as Days keeps them: Google's answers as Google says them. */ export function guestsOf(item: GEvent): string { const guests = (item.attendees ?? []).flatMap((a) => a.email ? [{ email: a.email, ...(a.displayName ? { name: a.displayName } : {}), answer: a.responseStatus ?? "needsAction", ...(a.self ? { self: true } : {}), ...(a.organizer ? { organizer: true } : {}) }] : [], ); return JSON.stringify(guests); } /** An event's columns as the old pull wrote them, every one each time (an absent value is null). */ export function columnsOf(item: GEvent, account: Account, zone: string): Data | null { const span = spanOf(item, zone); if (!span) return null; const self = item.organizer ? item.organizer.self === true : true; const mine = item.attendees?.find((a) => a.self)?.responseStatus; const recurrence = item.recurrence ?? []; const rrule = recurrence.find((l) => l.startsWith("RRULE:"))?.slice("RRULE:".length) ?? null; const exdates = recurrence.filter((l) => l.startsWith("EXDATE")).flatMap((l) => exdatesOf(l, zone)); const data: Data = { title: item.summary?.trim() || "(no title)", notes: item.description?.trim() || null, location: item.location?.trim() || null, starts_at: span.starts, ends_at: span.ends, all_day: span.allDay, rrule, exdates: rrule && exdates.length ? exdates.sort() : null, organizer_is_self: self, invited: self ? null : "invited", my_response: mine === "needsAction" ? "needs_action" : mine === "accepted" || mine === "declined" || mine === "tentative" ? mine : null, guest_responses: guestsOf(item), gcal_id: item.id, gcal_etag: item.etag ?? null, sync_state: "synced", account: account.email, on_google: true, }; if (item.iCalUID) data.ical_uid = item.iCalUID; return data; } /** Start and end as ISO instants; an all-day event from its first day's midnight to its last day's 23:59:59.999, in `zone`. */ function spanOf(item: GEvent, zone: string): { starts: string; ends: string | null; allDay: boolean } | null { if (item.start?.date) { const starts = joinMoment(item.start.date, null, zone); const endDay = item.end?.date ?? addDays(item.start.date, 1); // Google's end date is exclusive: the last day is the one before it. const ends = new Date(Date.parse(joinMoment(endDay, null, zone)) - 1).toISOString(); return { starts, ends, allDay: true }; } if (item.start?.dateTime) return { starts: iso(item.start.dateTime), ends: item.end?.dateTime ? iso(item.end.dateTime) : null, allDay: false }; return null; } /** `EXDATE;TZID=Asia/Kolkata:20261019T123000,20261026T123000`, `EXDATE;VALUE=DATE:20261019`, `EXDATE:20261019T070000Z` → ISO instants. */ function exdatesOf(line: string, zone: string): string[] { const colon = line.indexOf(":"); if (colon < 0) return []; const tzid = /TZID=([^;:]+)/.exec(line.slice(0, colon))?.[1] ?? zone; return line .slice(colon + 1) .split(",") .map((v) => v.trim()) .flatMap((v) => { const m = /^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z)?)?$/.exec(v); if (!m) return []; const day = `${m[1]}-${m[2]}-${m[3]}`; if (!m[4]) return [joinMoment(day, null, tzid)]; if (m[7]) return [iso(`${day}T${m[4]}:${m[5]}:${m[6]}Z`)]; const at = joinMoment(day, `${m[4]}:${m[5]}`, tzid); return [new Date(Date.parse(at) + Number(m[6]) * 1000).toISOString()]; }); } function counted(account: Account, what: "created" | "updated" | "binned", n = 1): void { account.pulled[what] += n; } /** One event from a page, into its row: made, changed, binned, or folded into its series. */ function apply(engine: Engine, version: number, outcome: Outcome, account: Account, prepared: Prepared, item: GEvent, zone: string): void { const masterGcal = item.recurringEventId ?? (item.status === "cancelled" ? instanceOf(item.id)?.master : undefined); const master = masterGcal ? rowOf(engine, account, masterGcal, prepared.get(masterGcal)) : null; const original = masterGcal ? originalOf(item, zone) : null; const held = rowOf(engine, account, item.id, prepared.get(item.id)); if (waiting(held)) return; if (item.status === "cancelled") { if (master && original && !waiting(master)) { // A cancelled occurrence joins its series' exdates. const exdates = Array.isArray(master.data.exdates) ? (master.data.exdates as string[]) : []; if (!exdates.includes(original)) { engine.update(master, { exdates: [...exdates, original].sort() }, version, outcome); counted(account, "updated"); } } if (held) { for (const occurrence of engine.store.select(EVENT, [equalSql("series_id", held.id)], "created_at, id", 10_000)) engine.delete(occurrence, version, outcome); engine.delete(held, version, outcome); counted(account, "binned"); } return; } const data = columnsOf(item, account, zone); if (!data) return; if (masterGcal) { data.rrule = null; data.exdates = null; data.series_id = master?.id ?? null; data.original_starts_at = original; } else { data.series_id = null; data.original_starts_at = null; } if (held) { // A sealed event's words cannot be compared: Google's etag says whether the event changed. const sealedHeld = typeof held.data.sealed_enc === "string"; const changed = sealedHeld ? data.gcal_etag == null || data.gcal_etag !== held.data.gcal_etag : Object.keys(data).some((k) => JSON.stringify(data[k] ?? null) !== JSON.stringify(held.data[k] ?? null)); if (!changed) return; engine.update(held, data, version, outcome); counted(account, "updated"); return; } engine.create(EVENT, data, version, outcome, 0, { id: prepared.get(item.id)! }); counted(account, "created"); } /** After a whole listing: the account's Google rows in the window (a day in from each edge) that no page carried are binned. */ function reconcile(engine: Engine, version: number, outcome: Outcome, account: Account, window: { from: string; to: string }, sql: SqlStorage): void { const from = new Date(Date.parse(window.from) + 86_400_000).toISOString(); const to = new Date(Date.parse(window.to) - 86_400_000).toISOString(); const stale = engine.store.select( EVENT, [ equalSql("account", account.email), { sql: "json_extract(data, '$.gcal_id') IS NOT NULL AND json_extract(data, '$.series_id') IS NULL AND json_extract(data, '$.starts_at') >= ? AND json_extract(data, '$.starts_at') <= ?", args: [from, to] }, { sql: "NOT EXISTS (SELECT 1 FROM google_seen s WHERE s.account = ? AND s.gcal_id = json_extract(data, '$.gcal_id'))", args: [account.email] }, { sql: "json_extract(data, '$.sync_state') IS NOT 'pending'", args: [] }, ], "created_at, id", 100_000, ); for (const row of stale) { for (const occurrence of engine.store.select(EVENT, [equalSql("series_id", row.id)], "created_at, id", 10_000)) engine.delete(occurrence, version, outcome); engine.delete(row, version, outcome); counted(account, "binned"); } sql.exec("DELETE FROM google_seen WHERE account = ?", account.email); }