iterate.com / cloud

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

cloud / internal-packages / dummy-petshop / src / walk-in.tsmain at aacbc74

// walk-in.ts: THE SHOP ACTS BY ITSELF: a visitor walks in and adopts one of an account's pets, the
// adopted pets come back, or a day of such things begins on a clock. No MCP client of the account called anything, so this is the test of
// what reaches a client that did not ask: each change is a pet event (pet-events.ts), which the
// held calls answer at once and the webhook subscriptions receive.
//
//   GET  /walk-in                              a page with a button for each: for a person's phone
//   GET  /__test-controls/pets?account=<a>     the account's pets, its kept events, its subscriptions,
//                                              and what its webhook callbacks answered last
//   POST /__test-controls/pets                 {account, action: "adopt", id? | name?} — a visitor
//                                              adopts that pet, or the first one left
//                                              {account, action: "return"} — every pet comes back
//                                              {account, action: "day", happenings?, everySeconds?}
//                                              — a day begins: things happen on a clock, with no
//                                              more presses (shop-day.ts)
//                                              {account, action: "quiet"} — the day ends
//
// Like the shop's other controls (test-controls.ts), it names the account it acts on. An MCP
// client that signed in with no `user` is the account "Demo User" (oauth-provider.ts).
import { z } from "zod";
import { adoptPet, emitPetEvent, occurrenceOf, petsOf } from "./pet-events.ts";
import type { Pet } from "./pets.ts";
import { ASKED_DAY, dayOf } from "./shop-day.ts";
import {
  SHOP_DAY_LEAST_EVERY_MS,
  SHOP_DAY_MOST_EVERY_MS,
  SHOP_DAY_MOST_HAPPENINGS,
  type ShopDeps,
} from "./state.ts";

/** How many webhook answers of an account the control shows. */
const WEBHOOK_ANSWERS_SHOWN = 10;

const Visit = z.discriminatedUnion("action", [
  z.object({
    account: z.string().min(1),
    action: z.literal("adopt"),
    id: z.string().optional(),
    name: z.string().optional(),
  }),
  z.object({ account: z.string().min(1), action: z.literal("return") }),
  z.object({
    account: z.string().min(1),
    action: z.literal("day"),
    happenings: z.int().min(1).max(SHOP_DAY_MOST_HAPPENINGS).default(ASKED_DAY.happenings),
    everySeconds: z
      .number()
      .min(SHOP_DAY_LEAST_EVERY_MS / 1000)
      .max(SHOP_DAY_MOST_EVERY_MS / 1000)
      .default(ASKED_DAY.everySeconds),
  }),
  z.object({ account: z.string().min(1), action: z.literal("quiet") }),
]);

/** A request of the walk-in page or its controls: the answer, or null for any other request. */
export async function handleWalkIn(
  request: Request,
  { state, pets }: { state: ShopDeps["state"]; pets: Pet[] },
): Promise<Response | null> {
  const url = new URL(request.url);
  const key = `${request.method} ${url.pathname}`;
  if (key === "GET /walk-in")
    return new Response(walkInPage, { headers: { "content-type": "text/html; charset=utf-8" } });

  if (key === "GET /__test-controls/pets") {
    const account = url.searchParams.get("account");
    if (!account) return invalid("account is required: whose pets");
    const { mcpEventSubscriptions = {}, shopDays, webhookAnswers = [] } = await state.getState();
    return Response.json({
      account,
      // the day of things that happen by themselves, or null when the account never had one
      day: dayOf(shopDays?.[account]),
      pets: await petsOf(state, account, pets),
      events: (await state.petEventsAfter(account, 0)).events.map(occurrenceOf),
      // What the webhook callbacks of the account's live subscriptions answered to its last
      // events, the newest first: status 0 could not be reached. This control takes no sign-in,
      // so it says nothing of a subscription that was removed or has lapsed.
      webhookAnswers: webhookAnswers
        .filter(
          ({ owner, id }) =>
            owner === account && (mcpEventSubscriptions[id]?.expiresAt ?? 0) > Date.now(),
        )
        .slice(-WEBHOOK_ANSWERS_SHOWN)
        .reverse()
        .map(({ at, name, id, status }) => ({ at, name, id, status })),
      // where the account's events are POSTed to, without the secrets they are signed with
      subscriptions: Object.entries(mcpEventSubscriptions)
        .filter(([, subscription]) => subscription.owner === account)
        .map(([id, { name = "pet.created", arguments: args, url: callback, expiresAt }]) => ({
          id,
          name,
          arguments: args,
          host: new URL(callback).host,
          live: expiresAt > Date.now(),
        })),
    });
  }

  if (key === "POST /__test-controls/pets") {
    const visit = Visit.safeParse(await request.json().catch(() => null));
    if (!visit.success)
      return invalid(
        'account and action ("adopt", "return", "day" or "quiet") are required, so a visit touches one account',
      );
    const { account } = visit.data;
    if (visit.data.action === "day" || visit.data.action === "quiet") {
      // These controls take no sign-in, so they keep nothing for a name whose client was never
      // here (`knows`).
      if (!(await knows(state, account)))
        return invalid(
          "the shop does not know this account: a day is for an account whose signed-in client subscribed to an event, waited for one or began a day",
        );
      const day = await state.startShopDay(
        account,
        visit.data.action === "day"
          ? {
              happenings: visit.data.happenings,
              everyMs: visit.data.everySeconds * 1000,
              auto: false,
            }
          : { happenings: 0, everyMs: 0, auto: false },
      );
      if (!day && visit.data.action === "day")
        return Response.json(
          { error: "temporarily_unavailable", error_description: "too many accounts have a day" },
          { status: 503 },
        );
      return Response.json({ account, day: dayOf(day), pets: await petsOf(state, account, pets) });
    }
    const listed = await petsOf(state, account, pets);
    const emitted = [];
    if (visit.data.action === "adopt") {
      const { id, name } = visit.data;
      const wanted = name?.trim().toLowerCase();
      const pet = listed.find((candidate) =>
        id
          ? candidate.id === id
          : wanted
            ? candidate.name.toLowerCase() === wanted
            : !candidate.adopted,
      );
      if (!pet || pet.adopted)
        return invalid(pet ? `${pet.name} is adopted already` : "no such pet is up for adoption");
      const adopted = await adoptPet(state, account, pet, "walk-in visitor");
      if (adopted) emitted.push(adopted);
    } else {
      const returned = new Set(await state.returnPets(account));
      for (const { id, name, species } of listed.filter((pet) => returned.has(pet.id)))
        emitted.push(await emitPetEvent(state, account, "pet.returned", { id, name, species }));
    }
    return Response.json({
      account,
      events: emitted.map(({ event }) => occurrenceOf(event)),
      // what each webhook subscriber answered; status 0 could not be reached
      deliveries: emitted.flatMap(({ deliveries }) =>
        deliveries.map(({ id, url: callback, status }) => ({
          id,
          host: new URL(callback).host,
          status,
        })),
      ),
      pets: await petsOf(state, account, pets),
    });
  }
  return null;
}

/**
 * Whether `account`'s own client was here, by what only a signed-in client leaves: a webhook
 * subscription (`events/subscribe`), or a day, which begins by a signed-in call or, by the control
 * above, for an account that had one already. An adoption or a pet event is no such sign: the
 * controls of this page make those for any name.
 */
async function knows(state: ShopDeps["state"], account: string) {
  const kept = await state.getState();
  return Boolean(
    kept.shopDays?.[account] ||
    Object.values(kept.mcpEventSubscriptions || {}).some(({ owner }) => owner === account),
  );
}

const invalid = (error_description: string) =>
  Response.json({ error: "invalid_request", error_description }, { status: 400 });

/** The page of `GET /walk-in`: a button for each pet that a visitor may adopt, and one that
 *  brings the adopted pets back. It calls the two controls above. */
const walkInPage = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>The pet shop's floor</title>
<style>
  :root { color-scheme: light dark; }
  body { margin: 0 auto; padding: 16px; max-width: 520px; font: 16px/1.45 system-ui, sans-serif; }
  h1 { font-size: 20px; margin: 0 0 4px; } p { margin: 6px 0 14px; opacity: .75; }
  label { display: block; font-size: 13px; opacity: .75; }
  input { font: inherit; width: 100%; box-sizing: border-box; padding: 8px; margin: 2px 0 14px; }
  button { font: inherit; display: block; width: 100%; padding: 12px; margin: 8px 0; border-radius: 10px;
    border: 1px solid #8886; background: ButtonFace; color: ButtonText; cursor: pointer; text-align: left; }
  button:disabled { opacity: .5; cursor: default; }
  pre { font-size: 12px; white-space: pre-wrap; word-break: break-word; opacity: .8; margin-top: 16px; }
</style>
</head>
<body>
<h1>🐾 The pet shop's floor</h1>
<p>Here the shop acts by itself. No MCP client calls a tool. Watch what the account's client shows.</p>
<label for="account">The account. A client that signed in with no name is "Demo User".</label>
<input id="account" value="Demo User">
<div id="pets"></div>
<button id="return">↩︎ Every adopted pet comes back</button>
<button id="day">🎬 A busy day: 3 things happen by themselves, one every 20 seconds</button>
<button id="quiet">🤫 The shop is quiet again</button>
<p id="clock"></p>
<pre id="log"></pre>
<script>
(() => {
  const account = document.getElementById("account");
  account.value = new URLSearchParams(location.search).get("account") || account.value;
  const log = (value) => { document.getElementById("log").textContent = JSON.stringify(value, null, 2); };
  const draw = (pets) => {
    const list = document.getElementById("pets");
    list.textContent = "";
    for (const pet of pets) {
      const button = document.createElement("button");
      button.disabled = Boolean(pet.adopted);
      button.textContent = pet.adopted ? pet.name + " the " + pet.species + " is adopted" : "🚶 A visitor walks in and adopts " + pet.name + " the " + pet.species;
      button.onclick = () => visit({ action: "adopt", id: pet.id });
      list.append(button);
    }
  };
  const visit = async (action) => {
    const response = await fetch("/__test-controls/pets", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ account: account.value, ...action }) });
    const answer = await response.json();
    log(answer);
    if (answer.pets) draw(answer.pets); else read();
  };
  const read = async () => {
    const answer = await (await fetch("/__test-controls/pets?account=" + encodeURIComponent(account.value))).json();
    if (answer.pets) draw(answer.pets);
    const day = answer.day;
    document.getElementById("clock").textContent = day && day.happeningsLeft > 0
      ? "A day runs: " + day.happeningsLeft + " more will happen, the next at " + new Date(day.nextAt).toLocaleTimeString() + "."
      : "The shop is quiet.";
    return answer;
  };
  document.getElementById("return").onclick = () => visit({ action: "return" });
  document.getElementById("day").onclick = () => visit({ action: "day" });
  document.getElementById("quiet").onclick = () => visit({ action: "quiet" });
  account.onchange = () => read().then(log);
  read().then(log);
  // another client of the account may adopt too
  setInterval(read, 3000);
})();
</script>
</body>
</html>`;