iterate.com / cloud

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

cloud / internal-packages / dummy-petshop / src / shop-day.test.tsmain at aacbc74

/**
 * Things happen in the shop by themselves, on a clock (shop-day.ts): a day of happenings for one
 * account, which a model, a person or a client that starts to watch begins, and which always ends.
 */
import { expect, test, vi } from "vitest";
import { handleMcpRequest, type McpToolContext } from "./mcp.ts";
import { memoryPetshop } from "./memory-state.ts";
import { adoptPet, petsOf, postPetEvents } from "./pet-events.ts";
import { seedPets } from "./pets.ts";
import { nextShopDayAt, runShopDays, shopDayStep, takeDeliveries } from "./shop-day.ts";
import { handleWalkIn } from "./walk-in.ts";

const ada = "ada@example.com";
const T0 = Date.parse("2026-11-25T12:00:00Z");
const day = { happenings: 3, everyMs: 20_000, auto: false };

test("a day: a pet comes in, a visitor adopts it, it comes back, and then the day is over", async () => {
  const { state } = memoryPetshop();
  expect(await state.startShopDay(ada, day, T0)).toMatchObject({ left: 3, nextAt: T0 + 20_000 });
  expect(nextShopDayAt(await state.getState())).toBe(T0 + 20_000);

  // nothing is due before the first 20 seconds are over
  expect(await runShopDays(state, seedPets(), T0 + 19_000)).toEqual([]);

  const [arrived] = await runShopDays(state, seedPets(), T0 + 20_000);
  expect(arrived).toMatchObject({
    what: "arrive",
    event: { name: "pet.created", data: { id: "pet-a1", name: "Mochi", species: "cat" } },
  });
  // the same clock tick again does nothing: the next is due 20 seconds later
  expect(await runShopDays(state, seedPets(), T0 + 20_000)).toEqual([]);

  const [adopted] = await runShopDays(state, seedPets(), T0 + 40_000);
  // the visitor takes the newcomer, so the shop's own pets stay for the person
  expect(adopted).toMatchObject({
    what: "adopt",
    event: { name: "pet.adopted", data: { name: "Mochi", by: "walk-in visitor" } },
  });
  expect(await petsOf(state, ada, seedPets())).toEqual([
    { id: "pet-1", name: "Biscuit", species: "beagle" },
    { id: "pet-2", name: "Goldie", species: "goldfish" },
    { id: "pet-a1", name: "Mochi", species: "cat", adopted: true },
  ]);

  const [returned] = await runShopDays(state, seedPets(), T0 + 60_000);
  expect(returned).toMatchObject({
    what: "return",
    event: { name: "pet.returned", data: { id: "pet-a1", name: "Mochi", species: "cat" } },
  });

  // three happened: the day is over, and no clock is wanted
  expect(await runShopDays(state, seedPets(), T0 + 600_000)).toEqual([]);
  expect(nextShopDayAt(await state.getState())).toBeNull();
  // another account saw none of it
  expect(await petsOf(state, "bo@example.com", seedPets())).toEqual(seedPets());
  expect(await state.petEventsAfter("bo@example.com", 0)).toMatchObject({ events: [] });
});

test("a day is bounded: at most ten happenings, five seconds to five minutes apart", async () => {
  const { state } = memoryPetshop();
  expect(
    await state.startShopDay(ada, { happenings: 500, everyMs: 1, auto: false }, T0),
  ).toMatchObject({ left: 10, everyMs: 5000 });
  expect(
    await state.startShopDay(ada, { happenings: 2, everyMs: 86_400_000, auto: false }, T0),
  ).toMatchObject({ left: 2, everyMs: 300_000 });

  // ten happenings, each counted once, and the shop keeps at most six arrived pets
  await state.startShopDay(ada, { happenings: 10, everyMs: 5000, auto: false }, T0);
  const names = [];
  for (let at = T0 + 5000; at <= T0 + 100_000; at += 5000)
    for (const { event } of await runShopDays(state, seedPets(), at)) names.push(event.name);
  expect(names).toHaveLength(10);
  expect(names.slice(0, 4)).toEqual(["pet.created", "pet.adopted", "pet.returned", "pet.created"]);
  expect((await state.getState()).arrivedPets![ada]!.length).toBeLessThanOrEqual(6);

  // no happenings: the shop is quiet at once
  await state.startShopDay(ada, day, T0);
  expect(
    await state.startShopDay(ada, { happenings: 0, everyMs: 0, auto: false }, T0),
  ).toMatchObject({ left: 0 });
  expect(await shopDayStep(state, ada, seedPets(), T0 + 600_000)).toBeNull();
});

test("an automatic day begins once an hour for an account, and never over a day that runs", async () => {
  const { state } = memoryPetshop();
  const auto = { ...day, auto: true };
  expect(await state.startShopDay(ada, auto, T0)).toMatchObject({ left: 3, auto: true });
  // it runs
  expect(await state.startShopDay(ada, auto, T0 + 1000)).toBeNull();
  for (const at of [20_000, 40_000, 60_000]) await runShopDays(state, seedPets(), T0 + at);
  // it is over, but the hour is not
  expect(await state.startShopDay(ada, auto, T0 + 59 * 60_000)).toBeNull();
  // another account has its own hour
  expect(await state.startShopDay("bo@example.com", auto, T0 + 1000)).toMatchObject({ left: 3 });
  expect(await state.startShopDay(ada, auto, T0 + 61 * 60_000)).toMatchObject({ left: 3 });
  // a day that somebody asks for begins whenever
  expect(await state.startShopDay(ada, day, T0 + 62 * 60_000)).toMatchObject({ auto: false });
});

test("a model begins a day with simulate_shop_activity, and a watch of a quiet shop begins one", async () => {
  const context: McpToolContext = {
    ...memoryPetshop(),
    owner: ada,
    pets: seedPets(),
    origin: "https://petshop.example",
  };
  const begun = await tool(context, "simulate_shop_activity", { happenings: 2, everySeconds: 5 });
  expect(begun.structuredContent).toMatchObject({
    owner: ada,
    day: { happeningsLeft: 2, everySeconds: 5, startedBy: "a request" },
  });
  expect(await tool(context, "simulate_shop_activity", { happenings: 11 })).toMatchObject({
    isError: true,
  });
  const quiet = await tool(context, "simulate_shop_activity", { happenings: 0 });
  expect(quiet.structuredContent.day).toMatchObject({ happeningsLeft: 0, nextAt: null });

  // a model adopts a pet that came in by itself, by its name
  await context.state.startShopDay(ada, day, T0);
  await runShopDays(context.state, context.pets, T0 + 20_000);
  const adopted = await tool(context, "adopt_pet", { name: "mochi" });
  expect(adopted.structuredContent.pet).toMatchObject({ id: "pet-a1", adopted: true });

  // another account's wait begins that account's own automatic day
  const bo = { ...context, owner: "bo@example.com" };
  await tool(bo, "wait_for_pet_event", { waitSeconds: 0 });
  expect((await context.state.getState()).shopDays!["bo@example.com"]).toMatchObject({
    auto: true,
    left: 3,
    everyMs: 20_000,
  });
});

test("the walk-in page's controls begin and end a day, for an account that the shop knows", async () => {
  const deps = { ...memoryPetshop(), pets: seedPets() };
  const control = async (body?: Record<string, unknown>) =>
    (await handleWalkIn(
      new Request(`https://petshop.example/__test-controls/pets?account=${ada}`, {
        method: body ? "POST" : "GET",
        body: body && JSON.stringify({ account: ada, ...body }),
      }),
      deps,
    ))!;
  expect(await (await control()).json()).toMatchObject({ day: null });
  // the controls take no sign-in: a name that the shop does not know gets no day and no record
  expect(await control({ action: "day" })).toMatchObject({ status: 400 });
  expect(await control({ action: "quiet" })).toMatchObject({ status: 400 });
  expect(await deps.state.getState()).not.toHaveProperty("shopDays");

  // a visitor's press is no sign of the account's client: this page makes those for any name
  await control({ action: "adopt", name: "Goldie" });
  expect(await control({ action: "day" })).toMatchObject({ status: 400 });
  expect(await deps.state.getState()).not.toHaveProperty("shopDays");

  // the account's signed-in client subscribed to an event: the shop knows it
  await deps.state.setMcpEventSubscription("sub_ada", {
    owner: ada,
    name: "pet.adopted",
    arguments: {},
    url: "https://hooks.example/ada",
    secret: "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw",
    expiresAt: Date.now() + 3_600_000,
  });
  expect(await (await control({ action: "day" })).json()).toMatchObject({
    day: { happeningsLeft: 3, everySeconds: 20, startedBy: "a request" },
  });
  expect(await (await control()).json()).toMatchObject({ day: { happeningsLeft: 3 } });
  expect(await control({ action: "day", happenings: 11 })).toMatchObject({ status: 400 });
  expect(await (await control({ action: "quiet" })).json()).toMatchObject({
    day: { happeningsLeft: 0, nextAt: null },
  });
});

test("a new account's day never takes the place of a day that runs or of an hour that is not over", async () => {
  const { state } = memoryPetshop();
  // an account that never had a day gets no record for the end of one
  expect(await state.startShopDay(ada, { happenings: 0, everyMs: 0, auto: false }, T0)).toBeNull();
  expect(await state.getState()).not.toHaveProperty("shopDays");

  // 200 accounts: one whose day ran its hour out, and 199 whose days run
  await state.startShopDay("old@example.com", { ...day, happenings: 1 }, T0 - 2 * 3_600_000);
  await runShopDays(state, seedPets(), T0 - 2 * 3_600_000 + 20_000);
  for (let n = 0; n < 199; n++) await state.startShopDay(`busy-${n}@example.com`, day, T0);

  // the newcomer takes the place of the one that is long over, and of no other
  expect(await state.startShopDay(ada, day, T0 + 1000)).toMatchObject({ left: 3 });
  const kept = (await state.getState()).shopDays!;
  expect(Object.keys(kept)).toHaveLength(200);
  expect(kept).not.toHaveProperty(["old@example.com"]);
  expect(kept["busy-0@example.com"]).toMatchObject({ left: 3 });

  // now every day runs: one more account's day does not begin, and nothing is given up
  expect(await state.startShopDay("late@example.com", day, T0 + 2000)).toBeNull();
  expect(
    await state.startShopDay("late@example.com", { ...day, auto: true }, T0 + 2000),
  ).toBeNull();
  expect(Object.keys((await state.getState()).shopDays!)).toHaveLength(200);
  // an account that has a day begins its next one whenever
  expect(await state.startShopDay(ada, day, T0 + 3000)).toMatchObject({ left: 3 });
});

test("a day brings back only a pet that a visitor holds, never the account's own adoption", async () => {
  const { state } = memoryPetshop();
  // a visitor of a day adopts Mochi and brings it back
  await state.startShopDay(ada, { ...day, happenings: 4 }, T0);
  for (const at of [20_000, 40_000, 60_000]) await runShopDays(state, seedPets(), T0 + at);
  // then the account adopts Mochi itself
  const mochi = (await petsOf(state, ada, seedPets())).find((pet) => pet.name === "Mochi")!;
  expect(await adoptPet(state, ada, mochi, "account")).toMatchObject({
    event: { name: "pet.adopted", data: { by: "account" } },
  });
  // the day's fourth happening is a new arrival; the fifth, of a new day, a visitor's adoption
  await runShopDays(state, seedPets(), T0 + 80_000);
  await state.startShopDay(ada, { ...day, happenings: 3 }, T0 + 100_000);
  const names = [];
  for (const at of [120_000, 140_000, 160_000])
    for (const { what, pet } of await runShopDays(state, seedPets(), T0 + at))
      names.push(`${what} ${pet.name}`);
  // the visitor took Kiwi and brought Kiwi back: Mochi stays with the account
  expect(names).toEqual(["arrive Kiwi", "adopt Kiwi", "return Kiwi"]);
  expect((await petsOf(state, ada, seedPets())).filter((pet) => pet.adopted)).toMatchObject([
    { name: "Mochi" },
  ]);
  // with no pet out, a return has nothing to bring back
  expect(await state.returnVisitorPet(ada)).toBeNull();
});

test("a tick keeps every account's event with no webhook sent, then sends twenty, and the rest at the next tick", async () => {
  const { state } = memoryPetshop();
  const posts: string[] = [];
  vi.stubGlobal("fetch", async (url: string) => {
    posts.push(url);
    return new Response(null, { status: 204 });
  });
  try {
    // ada has 25 subscribers to pet.created, bo has one
    const subscription = {
      name: "pet.created" as const,
      arguments: {},
      secret: "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw",
      expiresAt: Date.now() + 3_600_000,
    };
    for (let n = 0; n < 25; n++)
      await state.setMcpEventSubscription(`sub_ada_${n}`, {
        ...subscription,
        owner: ada,
        url: `https://hooks.example/ada/${n}`,
      });
    await state.setMcpEventSubscription("sub_bo", {
      ...subscription,
      owner: "bo@example.com",
      url: "https://hooks.example/bo",
    });
    await state.startShopDay(ada, { ...day, happenings: 1 }, T0);
    await state.startShopDay("bo@example.com", { ...day, happenings: 1 }, T0);

    const happened = await runShopDays(state, seedPets(), T0 + 20_000);
    // both accounts' events are kept, and a poll reads them, before any callback is asked
    expect(happened.map(({ event }) => event.name)).toEqual(["pet.created", "pet.created"]);
    expect(await state.petEventsAfter("bo@example.com", 0)).toMatchObject({
      events: [{ name: "pet.created" }],
    });
    expect(posts).toEqual([]);

    // 26 POSTs are due: this tick sends 20, and 6 wait, for which the clock is wanted again
    expect(await postPetEvents(state, await takeDeliveries(state, happened))).toHaveLength(20);
    expect(posts).toHaveLength(20);
    expect((await state.getState()).petDeliveries).toHaveLength(6);
    expect(nextShopDayAt(await state.getState(), T0 + 21_000)).toBe(T0 + 26_000);

    // the next tick has no happening and sends the 6, bo's last: nobody's event is lost
    expect(await postPetEvents(state, await takeDeliveries(state, []))).toHaveLength(6);
    expect(posts).toHaveLength(26);
    expect(posts.at(-1)).toBe("https://hooks.example/bo");
    expect(new Set(posts)).toHaveProperty("size", 26);
    expect(nextShopDayAt(await state.getState(), T0 + 27_000)).toBeNull();
    expect(await takeDeliveries(state, [])).toEqual([]);

    // the shop keeps what each callback answered, and the control shows an account's own
    const shown = await handleWalkIn(
      new Request("https://petshop.example/__test-controls/pets?account=bo@example.com"),
      { state, pets: seedPets() },
    );
    expect(await shown!.json()).toMatchObject({
      webhookAnswers: [{ name: "pet.created", id: "sub_bo", status: 204 }],
    });
    expect((await state.getState()).webhookAnswers).toHaveLength(26);
    // a subscription that was removed takes its answers out of what the control shows
    await state.setMcpEventSubscription("sub_bo", null);
    const after = await handleWalkIn(
      new Request("https://petshop.example/__test-controls/pets?account=bo@example.com"),
      { state, pets: seedPets() },
    );
    expect(await after!.json()).toMatchObject({ webhookAnswers: [], subscriptions: [] });
  } finally {
    vi.unstubAllGlobals();
  }
});

/** One tool call of a 2026-07-28 client that follows no MCP tasks: the tool's answer. */
async function tool(context: McpToolContext, name: string, args: Record<string, unknown>) {
  const response = await handleMcpRequest(
    new Request("https://petshop.example/mcp", {
      method: "POST",
      headers: {
        "content-type": "application/json",
        accept: "application/json, text/event-stream",
        "mcp-protocol-version": "2026-07-28",
        "mcp-method": "tools/call",
        "mcp-name": name,
      },
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: 1,
        method: "tools/call",
        params: {
          name,
          arguments: args,
          _meta: {
            "io.modelcontextprotocol/protocolVersion": "2026-07-28",
            "io.modelcontextprotocol/clientCapabilities": {},
          },
        },
      }),
    }),
    context,
  );
  const text = await response.text();
  const message = JSON.parse(
    text.startsWith("{")
      ? text
      : text
          .split("\n")
          .find((line) => line.startsWith("data: "))!
          .slice(6),
  );
  return message.result as { isError?: boolean; structuredContent: any };
}