iterate.com / cloud

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

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

// shop-day.ts: THINGS HAPPEN IN THE SHOP BY THEMSELVES, ON A CLOCK. A day is a short run of
// happenings for one account, one every few seconds: a pet comes into the shop, a visitor walks in
// and adopts a pet, that pet comes back, and round again. Each is a pet event (pet-events.ts), so
// it reaches whoever watches the account, in the way that client has: a webhook, a held poll or
// stream, a finished MCP task, the gallery's own connection.
//
// The walk-in page (walk-in.ts) is one press for one happening. A day needs no press after its
// start, which is what a person wants who asked a client "tell me when a pet is adopted" and then
// waits. A day begins in three ways:
//
//   - a model calls `simulate_shop_activity` (mcp.ts), or a person presses the gallery's button
//   - the walk-in page, or `POST /__test-controls/pets {account, action: "day"}`
//   - by itself (`AUTO_DAY`), when a client starts to watch a shop: a new webhook subscription,
//     an `events/stream`, a `wait_for_pet_event` call. At most once an hour for an account
//     (state.ts `startShopDay`), so a client that watches again after each event ends the run.
//
// The clock is the Durable Object's alarm (durable-object.ts), which calls `runShopDays`. A day
// has at most `SHOP_DAY_MOST_HAPPENINGS` happenings, and each is counted before it is done, so
// nothing happens twice and a day always ends. A tick keeps every account's event first
// (`runShopDays`), and sends the events to the webhook subscribers after that (`takeDeliveries`,
// pet-events.ts `postPetEvents`): a slow callback delays no account's event, and a tick sends a bounded
// number of POSTs, the rest at the next.
import { type DuePost, petsOf, subscribersOf } from "./pet-events.ts";
import type { Pet } from "./pets.ts";
import {
  ARRIVED_PETS_KEPT,
  SHOP_DAY_LEAST_EVERY_MS,
  type PetEvent,
  type PetshopState,
  type ShopDay,
  type ShopDeps,
} from "./state.ts";

/** The day that begins by itself when a client starts to watch a quiet shop. */
export const AUTO_DAY = { happenings: 3, everyMs: 20_000, auto: true };

/** The day that begins when somebody asks for one and says no more. */
export const ASKED_DAY = { happenings: 3, everySeconds: 20 };

/** The pets that come into the shop, in the order they come: the first whose name the account
 *  does not have. More than an account keeps (`ARRIVED_PETS_KEPT`), so one is always free. */
const NEWCOMERS = [
  { name: "Mochi", species: "cat" },
  { name: "Pickle", species: "tortoise" },
  { name: "Kiwi", species: "parakeet" },
  { name: "Waffles", species: "rabbit" },
  { name: "Nacho", species: "hamster" },
  { name: "Pepper", species: "cat" },
  { name: "Olive", species: "beagle" },
  { name: "Bubbles", species: "goldfish" },
];

/** What a day does at each count of its happenings, and what it does instead when that cannot
 *  be: no room for one more pet, no pet left to adopt, no pet out with a visitor. */
const ORDER = [
  ["arrive", "adopt", "return"],
  ["adopt", "return", "arrive"],
  ["return", "adopt", "arrive"],
] as const;

/** One happening: what it was, and the event that the shop keeps of it. */
type Happening = { what: "arrive" | "adopt" | "return"; pet: Pet; event: PetEvent };

/** The most webhook POSTs that one tick of the clock makes, for every account together. */
const SHOP_DAY_MOST_DELIVERIES = 20;

/**
 * The next happening of `owner`'s day, when it is due: the shop's state changes and the event is
 * kept, which every held read answers at once. Answers the happening, or null when nothing is
 * due or nothing can happen. No webhook is sent here (`takeDeliveries`). `catalogue` is the
 * shop's own pets (pets.ts), to which the account's arrived pets are added.
 */
export async function shopDayStep(
  state: ShopDeps["state"],
  owner: string,
  catalogue: Pet[],
  now = Date.now(),
): Promise<Happening | null> {
  const step = await state.takeShopDayStep(owner, now);
  if (step === null) return null;
  const pets = await petsOf(state, owner, catalogue);
  const arrived = (await state.getState()).arrivedPets?.[owner] || [];
  // a visitor takes the newest arrival first, so the shop's own pets stay for the person
  const arrivedIds = new Set(arrived.map((pet) => pet.id));
  const up = pets.filter((pet) => !pet.adopted);
  const wanted = up.findLast((pet) => arrivedIds.has(pet.id)) ?? up[0];

  for (const what of ORDER[step % ORDER.length]!) {
    if (what === "arrive" && arrived.length < ARRIVED_PETS_KEPT) {
      const names = new Set(pets.map((pet) => pet.name));
      const newcomer = NEWCOMERS.find((pet) => !names.has(pet.name));
      if (!newcomer) continue;
      const pet = await state.arrivePet(owner, newcomer);
      return { what, pet, event: await state.recordPetEvent(owner, "pet.created", pet) };
    }
    if (what === "adopt" && wanted) {
      const { id, name, species } = wanted;
      await state.adoptPet(owner, id, "walk-in visitor");
      const by = "walk-in visitor" as const;
      const event = await state.recordPetEvent(owner, "pet.adopted", { id, name, species, by });
      return { what, pet: wanted, event };
    }
    if (what === "return") {
      // only a pet that a visitor holds: the account's own adoption is never undone
      const id = await state.returnVisitorPet(owner);
      const pet = pets.find((candidate) => candidate.id === id);
      if (!pet) continue;
      const { name, species } = pet;
      const event = await state.recordPetEvent(owner, "pet.returned", {
        id: pet.id,
        name,
        species,
      });
      return { what, pet, event };
    }
  }
  return null;
}

/** When the clock is wanted next (epoch ms): for the next happening of any account's day, or
 *  soon when webhook POSTs wait for a tick. Null when every day is over and nothing waits. */
export const nextShopDayAt = (
  { shopDays = {}, petDeliveries = [] }: PetshopState,
  now = Date.now(),
): number | null => {
  const due = Object.values(shopDays)
    .filter((day) => day.left > 0)
    .map((day) => day.nextAt);
  if (petDeliveries.length > 0) due.push(now + SHOP_DAY_LEAST_EVERY_MS);
  return due.length > 0 ? Math.min(...due) : null;
};

/**
 * Every account's happening that is due now: the first half of the alarm's work. Each is kept
 * before the next account's turn, and no webhook is sent, so one account never waits for
 * another's callback. One account's failure does not stop another's, and it is logged, with no
 * account's name. Answers what happened.
 */
export async function runShopDays(
  state: ShopDeps["state"],
  catalogue: Pet[],
  now = Date.now(),
): Promise<Happening[]> {
  const { shopDays = {} } = await state.getState();
  const happened: Happening[] = [];
  for (const [owner, day] of Object.entries(shopDays)) {
    if (day.left <= 0 || day.nextAt > now) continue;
    try {
      const happening = await shopDayStep(state, owner, catalogue, now);
      if (happening) happened.push(happening);
    } catch (error) {
      console.error({ event: "petshop.shop-day-failed", message: String(error) });
    }
  }
  return happened;
}

/**
 * The second half of the alarm's work, its first step: the kept events of one tick are queued
 * for their webhook subscribers behind the POSTs that wait already (state.ts `petDeliveries`),
 * and the `SHOP_DAY_MOST_DELIVERIES` that wait longest are taken, for every account together.
 * The rest wait for the next tick, which `nextShopDayAt` asks for. Answers the taken POSTs whose
 * event is still kept and whose subscription is still live. The second step is
 * pet-events.ts `postPetEvents`: they go out all at once, each ends after ten seconds, and what
 * each callback answered is kept.
 */
export async function takeDeliveries(
  state: ShopDeps["state"],
  happened: Happening[],
): Promise<DuePost[]> {
  const kept = await state.getState();
  const fresh = happened.flatMap(({ event }) =>
    subscribersOf(kept, event).map(([id]) => ({ seq: event.seq, id })),
  );
  if (fresh.length === 0 && !kept.petDeliveries?.length) return [];
  const { taken, waiting, dropped } = await state.exchangePetDeliveries(
    fresh,
    SHOP_DAY_MOST_DELIVERIES,
  );
  const due = taken.flatMap(({ seq, id }) => {
    const event = kept.petEvents?.find((candidate) => candidate.seq === seq);
    const subscription = kept.mcpEventSubscriptions?.[id];
    if (!event || !subscription || subscription.expiresAt <= Date.now()) return [];
    return [{ event, subscriber: [id, subscription] } satisfies DuePost];
  });
  console.log({
    event: "petshop.shop-day-tick",
    happened: happened.map(({ event }) => event.name),
    webhooks: due.length,
    waiting,
    dropped: dropped + taken.length - due.length,
  });
  return due;
}

/** A day as a person or a model reads it. */
export const dayOf = (day: ShopDay | null | undefined) =>
  day
    ? {
        happeningsLeft: day.left,
        happened: day.step,
        everySeconds: day.everyMs / 1000,
        nextAt: day.left > 0 ? new Date(day.nextAt).toISOString() : null,
        startedAt: new Date(day.startedAt).toISOString(),
        startedBy: day.auto ? "a client that began to watch" : "a request",
      }
    : null;