iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / dummy-petshop / src / google-calendar.tsmain at aacbc74

/**
 * The Google fake's Calendar (google.ts hands it the requests under `/calendar/v3/`, once the
 * bearer is an account's own): the account's primary calendar, at Google's own paths.
 *
 *   GET  /calendar/v3/calendars/primary                 the calendar: its id is the account's
 *                                                       address
 *   POST /calendar/v3/calendars/primary/events/watch    { id, type: "web_hook", address, token?,
 *                                                       expiration? } → a notification channel,
 *                                                       as `events.watch` answers one; it lives
 *                                                       as long as it asks for, a week at most
 *   POST /calendar/v3/channels/stop                     { id, resourceId } → the channel gets no
 *                                                       more pushes
 *   GET  /calendar/v3/calendars/primary/events          `events.list`: every event that is not
 *                                                       cancelled and a `nextSyncToken`; with
 *                                                       `syncToken`, what changed since (a
 *                                                       cancelled event as its id and status);
 *                                                       `maxResults` and `pageToken` page it, and
 *                                                       `fields` names the top-level fields to
 *                                                       answer. 410 for a token that is gone
 *
 * Every route needs a grant with a calendar scope, as Google's do. A calendar changes when a test
 * says so (`handleCalendarTestControls`), and each live channel then gets Google's push: a POST
 * with no body, whose headers say which channel and that its calendar changed.
 */
import { z } from "zod";
import type { CalendarEvent } from "./google-records.ts";
import { fakeUserIdOf, type ShopDeps } from "./state.ts";

/** How long Google keeps a channel at most, and one that names no end. */
const CHANNEL_MS = 7 * 24 * 60 * 60_000;

/** An error of Google's APIs, as their JSON answers it. */
export const googleApiError = (code: number, status: string, message: string) =>
  Response.json({ error: { code, message, status } }, { status: code });

/** A POST the fake makes to a receiver that a test or a channel named, and what came of it: the
 *  receiver's status and its answer (its JSON, or its text when it is not JSON). Status 0, and
 *  why, when the POST itself failed. */
export async function delivered(url: string, init: { headers: HeadersInit; body?: string }) {
  return fetch(url, { ...init, method: "POST", signal: AbortSignal.timeout(10_000) }).then(
    async (response) => ({
      status: response.status,
      body: await response
        .clone()
        .json()
        .catch(() => response.text().catch(() => "")),
    }),
    (cause: unknown) => ({
      status: 0,
      error: cause instanceof Error ? String(cause.cause ?? cause) : String(cause),
    }),
  );
}

/** A sync token names the calendar's version it was given at. */
const syncTokenOf = (version: number) => btoa(`petshop-sync:${version}`);

/** The version a sync token names; NaN for a text that is no token of the fake's. */
function versionOf(syncToken: string): number {
  try {
    return Number(/^petshop-sync:(\d+)$/.exec(atob(syncToken))?.[1] ?? Number.NaN);
  } catch {
    // not base64: no token of the fake's
    return Number.NaN;
  }
}

/** An event as `events.list` answers it. A cancelled one is its id and its status. */
function eventOf(event: CalendarEvent, origin: string, email: string) {
  if (event.status === "cancelled") return { id: event.id, status: event.status };
  return {
    id: event.id,
    status: event.status,
    summary: event.summary,
    start: { dateTime: event.start },
    end: { dateTime: event.end },
    updated: event.updated,
    htmlLink: `${origin}/calendar/event?eid=${event.id}`,
    organizer: { email },
  };
}

const resourceOf = (origin: string, email: string) => ({
  resourceId: `calendar-${fakeUserIdOf(email)}`,
  resourceUri: `${origin}/calendar/v3/calendars/${email}/events?alt=json`,
});

/** A request under `/calendar/v3/` (`path` is what follows), as the account of `grant`. */
export async function calendarAnswer(
  request: Request,
  deps: ShopDeps,
  grant: { email: string; scope: string },
  path: string,
): Promise<Response> {
  const url = new URL(request.url);
  const email = grant.email.toLowerCase();
  const scopes = grant.scope.split(" ");
  if (!scopes.some((scope) => scope.startsWith("https://www.googleapis.com/auth/calendar")))
    return googleApiError(
      403,
      "PERMISSION_DENIED",
      "Request had insufficient authentication scopes.",
    );
  const route = `${request.method} ${path}`;
  if (route === "GET calendars/primary")
    return Response.json({ kind: "calendar#calendar", id: email, summary: email });
  if (route === "POST calendars/primary/events/watch") {
    const input = Channel.safeParse(await request.json().catch(() => null));
    if (!input.success)
      return googleApiError(
        400,
        "INVALID_ARGUMENT",
        "A channel names its id, the type web_hook and an https address.",
      );
    const { id, address, token } = input.data;
    const latest = Date.now() + CHANNEL_MS;
    const asked = Number(input.data.expiration);
    const expiration = asked > Date.now() && asked < latest ? asked : latest;
    const resource = resourceOf(url.origin, email);
    await deps.state.changeGoogleCalendar(email, {
      watch: { id, resourceId: resource.resourceId, address, token, expiration },
    });
    return Response.json({
      kind: "api#channel",
      id,
      ...resource,
      token,
      expiration: String(expiration),
    });
  }
  if (route === "POST channels/stop") {
    const { id } = ((await request.json().catch(() => null)) || {}) as { id?: unknown };
    const stopped = await deps.state.changeGoogleCalendar(email, { stop: String(id) });
    return stopped.refused
      ? googleApiError(404, "NOT_FOUND", `Channel '${String(id)}' not found for project`)
      : new Response(null, { status: 204 });
  }
  if (route !== "GET calendars/primary/events")
    return googleApiError(404, "NOT_FOUND", "Not Found");
  const calendar = (await deps.state.googleCalendar(email)) || {
    version: 0,
    syncFrom: 0,
    events: [],
  };
  // with no token it is a first read: every event that is not cancelled
  const syncToken = url.searchParams.get("syncToken");
  const since = syncToken ? versionOf(syncToken) : -1;
  // a token names a version the calendar still answers from; NaN is within no range
  if (syncToken && !(since >= calendar.syncFrom && since <= calendar.version))
    return googleApiError(410, "GONE", "Sync token is no longer valid, a full sync is required.");
  const listed = calendar.events.filter((event) =>
    syncToken ? event.version > since : event.status === "confirmed",
  );
  const from = Number(url.searchParams.get("pageToken")) || 0;
  const to = from + Math.min(Math.max(Number(url.searchParams.get("maxResults")) || 250, 1), 2500);
  const answer: Record<string, unknown> = {
    kind: "calendar#events",
    items: listed.slice(from, to).map((event) => eventOf(event, url.origin, email)),
    // the token comes with the last page alone
    ...(to < listed.length
      ? { nextPageToken: String(to) }
      : { nextSyncToken: syncTokenOf(calendar.version) }),
  };
  const fields = url.searchParams.get("fields")?.split(",");
  return Response.json(
    fields
      ? Object.fromEntries(Object.entries(answer).filter(([name]) => fields.includes(name)))
      : answer,
  );
}

/**
 * The Calendar fake's test controls:
 *
 *   POST /__test-controls/google/calendar-change        { email, summary?, cancel? } → that
 *        account's calendar gets a new event (or the event of the id `cancel` is cancelled),
 *        and each live channel of it gets Google's push: a POST to the channel's `address` with
 *        no body and the headers `X-Goog-Channel-ID`, `X-Goog-Channel-Token` (when the channel
 *        has one), `X-Goog-Channel-Expiration`, `X-Goog-Resource-ID`, `X-Goog-Resource-URI`,
 *        `X-Goog-Resource-State: exists` and `X-Goog-Message-Number`, which rises on each
 *        channel from 2 (number 1 is Google's `sync` message, which the fake does not send).
 *        Answers the event and what each receiver answered. 409 when the calendar has no live
 *        channel: Google pushes only to a channel `events.watch` made.
 *   POST /__test-controls/google/calendar-forget-sync   { email } → every sync token given for
 *        that calendar so far answers 410, as one that Google let expire.
 */
export async function handleCalendarTestControls(
  request: Request,
  deps: ShopDeps,
): Promise<Response | null> {
  const url = new URL(request.url);
  const key = `${request.method} ${url.pathname}`;
  const invalid = (error_description: string) =>
    Response.json({ error: "invalid_request", error_description }, { status: 400 });
  if (key === "POST /__test-controls/google/calendar-forget-sync") {
    const input = Account.safeParse(await request.json().catch(() => null));
    if (!input.success) return invalid("email is required");
    const email = input.data.email.toLowerCase();
    await deps.state.changeGoogleCalendar(email, { forget: true });
    return Response.json({ email });
  }
  if (key !== "POST /__test-controls/google/calendar-change") return null;
  const input = CalendarChange.safeParse(await request.json().catch(() => null));
  if (!input.success) return invalid("email is required; summary and cancel are texts");
  const email = input.data.email.toLowerCase();
  const now = Date.now();
  const at = new Date(now).toISOString();
  const changed = await deps.state.changeGoogleCalendar(
    email,
    input.data.cancel
      ? { cancel: input.data.cancel, at }
      : {
          add: {
            id: [...crypto.getRandomValues(new Uint8Array(13))]
              .map((byte) => byte.toString(16).padStart(2, "0"))
              .join(""),
            summary: input.data.summary || "An event from the pet shop",
            start: new Date(now + 60 * 60_000).toISOString(),
            end: new Date(now + 2 * 60 * 60_000).toISOString(),
          },
          at,
        },
  );
  if (changed.refused === "not_watched")
    return Response.json(
      { error: "not_watched", error_description: `no live channel watches ${email}'s calendar` },
      { status: 409 },
    );
  if (!changed.event || !changed.channels)
    return invalid(`${email}'s calendar has no event ${input.data.cancel} to cancel`);
  const resource = resourceOf(url.origin, email);
  const pushed = [];
  for (const channel of changed.channels) {
    const headers = new Headers({
      "user-agent": "APIs-Google; (+https://developers.google.com/webmasters/APIs-Google.html)",
      "x-goog-channel-id": channel.id,
      "x-goog-channel-expiration": new Date(channel.expiration).toUTCString(),
      "x-goog-resource-id": resource.resourceId,
      "x-goog-resource-uri": resource.resourceUri,
      "x-goog-resource-state": "exists",
      "x-goog-message-number": String(channel.messageNumber),
    });
    // a channel that was made with no token sends no such header
    if (channel.token) headers.set("x-goog-channel-token", channel.token);
    pushed.push({
      channelId: channel.id,
      url: channel.address,
      ...(await delivered(channel.address, { headers })),
    });
  }
  return Response.json({ email, event: eventOf(changed.event, url.origin, email), pushed });
}

const Account = z.object({ email: z.string().min(3) });
const CalendarChange = Account.extend({
  summary: z.string().min(1).max(200).optional(),
  cancel: z.string().min(1).optional(),
});
/** What `events.watch` takes: Google names the type `web_hook`, and takes `webhook` too. */
const Channel = z.object({
  id: z.string().min(1).max(64),
  type: z.enum(["web_hook", "webhook"]),
  address: z.url({ protocol: /^https$/ }).max(512),
  token: z.string().max(256).optional(),
  expiration: z.union([z.string(), z.number()]).optional(),
});