cloud / internal-packages / dummy-petshop / src / state.tsmain at aacbc74
import {
calendarChanged,
gmailChanged,
type CalendarAction,
type GmailAction,
type GmailMailbox,
type GoogleCalendar,
} from "./google-records.ts";
/**
* How long every access token the shop mints lives, a GraphQL session's too.
* Deliberately short so integration e2e hits real expiry (and therefore real
* refresh) without waiting an hour; long enough to outlive the gap between a
* token's mint and its first use, which a loaded e2e run stretches. A test
* forces its 401 through expire-tokens instead.
*/
export const ACCESS_TOKEN_TTL_SECONDS = 120;
/**
* The seeded OAuth client every environment starts with. Fixed, well-known
* values on purpose: this is a dummy service holding only fake data, and
* specs need credentials that exist before any test-control call.
*/
export const DEFAULT_CLIENT_ID = "petshop-default";
export const DEFAULT_CLIENT_SECRET = "petshop-default-secret";
/**
* The seeded GitHub-App installation every environment starts with.
* Well-known ids, like the OAuth client above — but the seed carries NO
* verifying key: petshop holds only PUBLIC keys, and the matching private key
* lives on the OS side, so the App JWT verifier is dead until a public key is
* registered via `POST /__test-controls/apps`. That is the point being proven, not a
* gap.
*/
export const DEFAULT_APP_ID = "petshop-app";
export const DEFAULT_INSTALLATION_ID = "petshop-installation";
/** One registered OAuth client. */
export interface OauthClient {
clientSecret: string;
/** RFC 7591 dynamically-registered redirect URIs. Empty for the seeded client and those minted
* by `POST /__test-controls/clients` (they accept any absolute redirect_uri); a DCR client is
* pinned to exactly what it registered. */
redirectUris?: string[];
/** A public client (token_endpoint_auth_method "none", the standard MCP shape)
* has no secret and authenticates at the token endpoint with PKCE + its
* client_id in the body instead of HTTP Basic. */
public?: boolean;
}
/**
* One registered GitHub App installation. petshop stores ONLY the app's PUBLIC
* key (RS256 SPKI PEM): the installation-token endpoint verifies a presented App
* JWT's signature against it, and the matching private key never leaves the OS
* side's secret. `webhookSecret` is the key its webhooks are signed with.
*/
export interface GithubApp {
appId: string;
/** RS256 SPKI PEM (`-----BEGIN PUBLIC KEY-----`); "" until one is registered. */
publicKeyPem: string;
installationId: string;
webhookSecret: string;
/** The GitHub fake's (github.ts) view of the installation: the App's URL handle
* (`/apps/<appSlug>/installations/new`), the account it is installed on, the users who reach it
* (`/user/installations`), the first of whom installs it by default, and the OAuth client they
* authorize. */
appSlug: string;
account: GithubAccount;
users: GithubInstallationUser[];
oauthClientId: string;
/** The App's Callback URL, where installing redirects; an installation registered without one
* has no install page. */
callbackUrl?: string;
}
/** The account (a user or an organization) a GitHub App installation is on. */
export interface GithubAccount {
login: string;
id: number;
type: "Organization" | "User";
}
/** A user who reaches a GitHub App installation, and their role on its account. */
export interface GithubInstallationUser {
login: string;
role: "admin" | "member";
}
/**
* The whole service's mutable state — one JSON blob in one Durable Object.
* Tokens are sealed AES-GCM blobs (seal.ts), so only the things that genuinely must be shared and
* mutable live here: the client registry, revocation facts, the fakes' records and scheduled
* token-endpoint failures.
*/
export interface PetshopState {
/** The revocation epochs of one account's tokens of one client, by `accountRevocationKey`. A
* token seals its account's epoch at mint and answers 401 once expire-tokens (test-controls.ts)
* moves that epoch on, so a test expires the tokens of the account it signed in as and no
* other: the one shop serves every concurrent CI run, and a preview's Google, GitHub and
* Cloudflare sign-ins all hold tokens of `petshop-default`. The `MINTED_RECORDS_KEPT` most
* recently revoked are kept; a minted client's go with the client. */
accessTokenEpochs: Record<string, number>;
/** The seeded client and the newest `MINTED_RECORDS_KEPT` minted ones, oldest first. */
clients: Record<string, OauthClient>;
/** `jti` values of revoked refresh tokens (authorization-server.ts; the Slack fake's bot tokens
* are refresh tokens). The newest `RECORDS_KEPT` are kept. */
revokedRefreshTokenIds: string[];
/** `jti` values of authorization codes already exchanged — codes are
* single-use (RFC 6749 §4.1.2), so a replayed code is rejected. The newest
* `MINTED_RECORDS_KEPT` are kept, far more than are exchanged while a code lives. */
usedAuthorizationCodeIds: string[];
/** Scheduled POST /oauth/token failures, scoped by OAuth client so one test's
* fault injection cannot break another concurrently running integration. */
tokenEndpointFailuresRemainingByClient: Record<string, number>;
/** Registered GitHub App installations, keyed by `installationId` (the path
* segment of `POST /app/installations/<id>/access_tokens`). Seeded with the
* well-known default; extended/replaced via `POST /__test-controls/apps`. */
apps: Record<string, GithubApp>;
/** Installation ids in registration order, oldest first — what the registry's cap drops from. */
installationOrder: string[];
/** What the Slack fake's (slack.ts) `chat.postMessage` recorded, per workspace, newest last. */
slackMessages: Record<string, SlackMessage[]>;
/** The GitHub fake's pull requests (their files) and the check runs posted to it, per
* installation, newest last. */
githubPulls: Record<string, GithubPull[]>;
githubCheckRuns: Record<string, GithubCheckRun[]>;
/** The RS256 key the Google and Cloudflare fakes sign ID tokens with (oidc.ts), minted on first
* use and kept, so every isolate's ID tokens verify against the one published JWKS. */
oidcSigningKey?: OidcSigningKey;
/** The MCP server's event subscriptions (mcp.ts), by id, the most recently subscribed last. The
* newest `RECORDS_KEPT` are kept. */
mcpEventSubscriptions?: Record<string, McpEventSubscription>;
/** The ids of the pets each account adopted (mcp.ts `adopt_pet`), by owner, the owner who
* adopted last at the end. Kept here and not in an isolate's memory, so that the model's call
* and the gallery's next read agree whichever isolate answers. The newest `RECORDS_KEPT`
* owners are kept. */
adoptedPets?: Record<string, string[]>;
/** What each webhook inbox got (webhook-inbox.ts), by the inbox's name, the inbox that got
* something last at the end. The newest `INBOX_DELIVERIES_KEPT` of an inbox and the newest
* `RECORDS_KEPT` inboxes are kept. */
webhookInboxes?: Record<string, InboxDelivery[]>;
/** What happened to the accounts' pets (pet-events.ts), every account's in one list, the newest
* last: what MCP Events' poll and push delivery, and the gallery's held call, read from. The
* newest `PET_EVENTS_KEPT` are kept. */
petEvents?: PetEvent[];
/** The `seq` of the newest pet event ever recorded: a cursor is one of these. */
petEventSeq?: number;
/** Of each account's adopted pets, the ids of those that a walk-in visitor holds and not the
* account: the pets that a day may bring back (shop-day.ts). An id leaves when the pet comes
* back. The newest `RECORDS_KEPT` owners are kept. */
visitorPets?: Record<string, string[]>;
/** The pets that came into the shop by themselves (shop-day.ts), by the account whose pets they
* are, the account that got one last at the end. Kept here and not in the isolate's catalogue
* (pets.ts), because the Durable Object's alarm adds them and every isolate must show them.
* The newest `ARRIVED_PETS_KEPT` of an account and the newest `RECORDS_KEPT` accounts are
* kept. */
arrivedPets?: Record<string, ArrivedPet[]>;
/** How many pets ever arrived: the number in the next one's id. */
arrivedPetSeq?: number;
/** What the webhook callbacks answered to the pet events POSTed to them (pet-events.ts), the
* newest last: how a person sees whether a client's receiver took an event. The newest
* `WEBHOOK_ANSWERS_KEPT` are kept, of every account together. */
webhookAnswers?: WebhookAnswer[];
/** The webhook POSTs of the days' events that wait for a tick of the clock (shop-day.ts): the
* event by its `seq` and the subscription by its id, the one that waits longest first. A tick
* sends a bounded number, and the rest wait here for the next. The newest
* `PET_DELIVERIES_KEPT` are kept. */
petDeliveries?: PetDelivery[];
/** Each account's day of things that happen by themselves (shop-day.ts), by owner, the account
* whose day started last at the end. A day that is over stays, so that the next automatic day
* knows when the last one began. At most `RECORDS_KEPT`: a new account's day takes the place
* of a day that is over for an hour, and never of one that runs (`startShopDay`). */
shopDays?: Record<string, ShopDay>;
/** The storage keys of the Google fake's mailboxes and calendars (google-records.ts), the most
* recently changed last. Each record is a stored value of its own, so this blob does not grow
* with a mailbox's history or a calendar's events. The newest `RECORDS_KEPT` are kept, and the
* value of a key that leaves the list is deleted. */
googleRecordKeys?: string[];
}
/** One MCP Events webhook subscription (mcp.ts): whose pets it hears, which event (`pet.created`
* when a subscription older than the other events names none), which species, where they are
* POSTed, the secret they are signed with, and when it lapses (epoch ms). */
export interface McpEventSubscription {
owner: string;
name?: PetEventName;
arguments: { species?: string };
url: string;
secret: string;
expiresAt: number;
}
export type PetEventName = "pet.created" | "pet.adopted" | "pet.returned";
/** A pet that came into the shop by itself for one account. */
interface ArrivedPet {
id: string;
name: string;
species: string;
}
/**
* One account's day in the shop (shop-day.ts): `left` things still happen, one every `everyMs`,
* the next at `nextAt` (epoch ms). `step` counts the things that happened. `auto` is a day that
* began because a client started to watch the shop, and not because somebody asked for one.
*/
export interface ShopDay {
startedAt: number;
auto: boolean;
everyMs: number;
left: number;
step: number;
nextAt: number;
}
/** What one webhook callback answered to one pet event: when, whose event and which, the
* subscription's id (never its address) and the HTTP status; 0 could not be reached. */
export interface WebhookAnswer {
at: string;
owner: string;
name: PetEventName;
id: string;
status: number;
}
/** How many webhook answers are kept. */
const WEBHOOK_ANSWERS_KEPT = 100;
/** One webhook POST that waits: which kept event (`PetEvent.seq`) goes to which subscription. */
export interface PetDelivery {
seq: number;
id: string;
}
/** How many webhook POSTs wait at most. One more pushes out the one that waits longest. */
const PET_DELIVERIES_KEPT = 200;
/** The most things that one day makes happen, and the least and the most time between two. */
export const SHOP_DAY_MOST_HAPPENINGS = 10;
export const SHOP_DAY_LEAST_EVERY_MS = 5_000;
export const SHOP_DAY_MOST_EVERY_MS = 5 * 60 * 1000;
/** An account gets one automatic day in this long, however often its clients start to watch. */
const SHOP_DAY_AUTO_ONCE_IN_MS = 60 * 60 * 1000;
/** How many arrived pets an account keeps: the oldest leaves the shop when one more arrives. */
export const ARRIVED_PETS_KEPT = 6;
/** One thing that happened to an account's pets, as MCP Events delivers it (`eventId`, `name`,
* `timestamp`, `data`), with whose pets (`owner`) and its place in the list (`seq`). */
export interface PetEvent {
seq: number;
owner: string;
eventId: string;
name: PetEventName;
timestamp: string;
/** The pet, and for an adoption who adopted it: the account, or a walk-in visitor. */
data: { id: string; name: string; species: string; by?: "account" | "walk-in visitor" };
}
/** What a reader of an account's pet events gets: the events after its cursor, the cursor to
* read from next, and `truncated` when events after its cursor are no longer kept. */
export interface PetEventsRead {
events: PetEvent[];
cursor: number;
truncated: boolean;
}
/** A pull request the GitHub fake serves (`/__test-controls/github/pulls` seeds it). */
export interface GithubPull {
owner: string;
repo: string;
number: number;
headSha: string;
files: { filename: string; status: string; patch: string }[];
}
/** A check run posted to the GitHub fake. */
export interface GithubCheckRun {
id: number;
owner: string;
repo: string;
name: string;
head_sha: string;
status: string;
conclusion: string | null;
external_id: string | null;
output: unknown;
}
/** An RS256 key pair as JWKs, and the `kid` its ID tokens name. */
export interface OidcSigningKey {
kid: string;
privateJwk: JsonWebKey;
publicJwk: JsonWebKey;
}
/** One `chat.postMessage` the Slack fake accepted. */
export interface SlackMessage {
channel: string;
text: string;
ts: string;
}
/** How many GitHub App installations, revoked token ids, and Slack workspaces (and messages per
* workspace) are kept: every e2e run mints its own, so the oldest go first (never the seeded
* installation). */
const RECORDS_KEPT = 200;
/** How many deliveries a webhook inbox keeps. */
const INBOX_DELIVERIES_KEPT = 20;
/** One POST that a webhook inbox got: when, the headers a webhook's sender signs with, and the
* body as it came. */
export type InboxDelivery = { at: string; headers: Record<string, string>; body: string };
/** How many pet events are kept, of every account together. They are in the one stored value
* (see `MINTED_RECORDS_KEPT` on why that stays small), and a reader that fell further behind is
* told `truncated`. */
const PET_EVENTS_KEPT = 50;
/** The longest a read of pet events waits for one. Under the 30 seconds after which clients and
* proxies give up on a call. */
export const PET_EVENTS_LONGEST_WAIT_MS = 25_000;
/**
* How many minted OAuth clients, account revocation epochs and spent authorization codes are
* kept, the oldest going first. The state is one stored value that every change rewrites and every
* read copies whole, so its size is the cost of each call to the Durable Object; kept unbounded,
* those calls queue behind the storage writes until workerd resets the object. A test uses its
* client, account or code for minutes, while the e2e suites mint fewer than 700 clients an hour.
*/
const MINTED_RECORDS_KEPT = 500;
const MINTED_CLIENT_ID_PREFIX = "petshop-client-";
/** Drops what `MINTED_RECORDS_KEPT` does not keep. A minted client's accounts' revocation epochs
* and its scheduled token-endpoint failures go with it; the seeded client stays. */
function dropOldestMintedRecords(state: PetshopState): void {
const mintedClientIds = Object.keys(state.clients).filter((id) =>
id.startsWith(MINTED_CLIENT_ID_PREFIX),
);
for (const clientId of mintedClientIds.slice(0, -MINTED_RECORDS_KEPT))
delete state.clients[clientId];
for (const byClient of [state.accessTokenEpochs, state.tokenEndpointFailuresRemainingByClient])
for (const key of Object.keys(byClient)) {
// a minted client's id has no colon: a failure's whole key, an epoch key's first part
const clientId = key.split(":")[0]!;
if (clientId.startsWith(MINTED_CLIENT_ID_PREFIX) && !state.clients[clientId])
delete byClient[key];
}
for (const key of Object.keys(state.accessTokenEpochs).slice(0, -MINTED_RECORDS_KEPT))
delete state.accessTokenEpochs[key];
state.usedAuthorizationCodeIds = state.usedAuthorizationCodeIds.slice(-MINTED_RECORDS_KEPT);
}
/** A fake account's numeric id, stable for its login or email: FNV-1a of it — a GitHub user's or organization's id, a Google or Cloudflare subject. */
export function fakeUserIdOf(login: string): number {
let hash = 0x811c9dc5;
for (const char of login.toLowerCase()) hash = Math.imul(hash ^ char.charCodeAt(0), 0x01000193);
return hash >>> 0;
}
/** The revocation epoch of the tokens `holder.account` holds from `holder.clientId`: 0 until they
* are first expired. */
export function accessTokenEpochFor(
state: PetshopState,
holder: { clientId: string; account: string },
): number {
return state.accessTokenEpochs[accountRevocationKey(holder.clientId, holder.account)] ?? 0;
}
/** The key of the tokens ONE account holds from `clientId` in `accessTokenEpochs`. */
const accountRevocationKey = (clientId: string, account: string) => `${clientId}:${account}`;
/** Where the state blob and the Google fake's records are kept: a Durable Object's storage, or a
* map (memory-state.ts). */
export interface PetshopStorage {
get<T>(key: string): Promise<T | undefined>;
put(key: string, value: unknown): Promise<void>;
delete(key: string): Promise<unknown>;
}
const gmailMailboxKey = (email: string) => `gmail-mailbox:${email}`;
const googleCalendarKey = (email: string) => `google-calendar:${email}`;
/**
* The shop's state and every change to it, over one storage blob. Every method
* is a single load → mutate → save step. In production it lives inside the one
* Durable Object (durable-object.ts), whose input gate serializes the methods,
* so the stateless worker never does read-modify-write races; tests and
* memory-state.ts run it over a map. The Google fake's mailboxes and calendars are
* stored values of their own beside the blob (`googleRecordKeys`), each changed in one step
* the same way.
*/
export class PetshopStore {
readonly #storage: PetshopStorage;
/** The reads of pet events that wait for one (`petEventsAfter`), each woken by the next event. */
readonly #petEventWaiters = new Set<() => void>();
constructor(storage: PetshopStorage) {
this.#storage = storage;
}
async #load(): Promise<PetshopState> {
const existing = await this.#storage.get<PetshopState>("state");
if (existing) return existing;
const initial: PetshopState = {
accessTokenEpochs: {},
clients: {
[DEFAULT_CLIENT_ID]: { clientSecret: DEFAULT_CLIENT_SECRET },
},
revokedRefreshTokenIds: [],
usedAuthorizationCodeIds: [],
tokenEndpointFailuresRemainingByClient: {},
// the seeded installation, with no verifying key until one is registered (DEFAULT_APP_ID)
apps: { [DEFAULT_INSTALLATION_ID]: githubApp({ publicKeyPem: "" }, {}) },
installationOrder: [DEFAULT_INSTALLATION_ID],
slackMessages: {},
githubPulls: {},
githubCheckRuns: {},
};
await this.#storage.put("state", initial);
return initial;
}
async #save(state: PetshopState): Promise<void> {
dropOldestMintedRecords(state);
await this.#storage.put("state", state);
}
async getState(): Promise<PetshopState> {
return await this.#load();
}
async createClient(input: {
redirectUris?: string[];
public?: boolean;
}): Promise<{ clientId: string; clientSecret: string }> {
const state = await this.#load();
const clientId = `${MINTED_CLIENT_ID_PREFIX}${crypto.randomUUID().slice(0, 8)}`;
// A public client has no usable secret; a confidential one authenticates with it.
const clientSecret = input.public ? "" : crypto.randomUUID();
state.clients[clientId] = {
clientSecret,
redirectUris: input.redirectUris,
...(input.public && { public: true }),
};
await this.#save(state);
return { clientId, clientSecret };
}
/** Every outstanding access token `account` holds from `clientId` answers 401 from now on, and
* no other account's. Answers the new epoch. */
async expireAccessTokens(clientId: string, account: string): Promise<number> {
const state = await this.#load();
const key = accountRevocationKey(clientId, account);
const next = accessTokenEpochFor(state, { clientId, account }) + 1;
// re-inserted, so the order of the epochs is the order they were last revoked in
delete state.accessTokenEpochs[key];
state.accessTokenEpochs[key] = next;
await this.#save(state);
return next;
}
/** A long-lived token (see `revokedRefreshTokenIds`) stops working. */
async revokeToken(tokenId: string): Promise<void> {
const state = await this.#load();
state.revokedRefreshTokenIds = [
...state.revokedRefreshTokenIds.filter((id) => id !== tokenId),
tokenId,
].slice(-RECORDS_KEPT);
await this.#save(state);
}
/** Consume a single-use authorization code by its jti. Returns true the
* first time, false on replay (RFC 6749 §4.1.2). */
async consumeAuthorizationCode(codeId: string): Promise<boolean> {
const state = await this.#load();
if (state.usedAuthorizationCodeIds.includes(codeId)) return false;
state.usedAuthorizationCodeIds.push(codeId);
await this.#save(state);
return true;
}
/**
* Register (or replace) a GitHub App installation's verifying key — how the
* OS side installs the PUBLIC key matching the private key it will sign App
* JWTs with. Returns the stored record (webhook secret included) for the
* caller.
*/
async registerApp(input: AppRegistration): Promise<GithubApp> {
const state = await this.#load();
const app = githubApp(input, state.apps);
state.apps[app.installationId] = app;
const order = state.installationOrder.filter((id) => id !== app.installationId);
order.push(app.installationId);
while (order.length > RECORDS_KEPT) {
const [oldest] = order.splice(order[0] === DEFAULT_INSTALLATION_ID ? 1 : 0, 1);
delete state.apps[oldest!];
}
state.installationOrder = order;
await this.#save(state);
return app;
}
async recordSlackMessage(teamId: string, message: SlackMessage): Promise<void> {
const state = await this.#load();
const { [teamId]: earlier = [], ...others } = state.slackMessages;
// the workspace moves to the end, so the least recently posted-to are the ones dropped
state.slackMessages = Object.fromEntries([
...Object.entries(others).slice(-(RECORDS_KEPT - 1)),
[teamId, [...earlier, message].slice(-RECORDS_KEPT)],
]);
await this.#save(state);
}
/** The ID-token signing key, minted and saved on first use. */
async oidcSigningKey(): Promise<OidcSigningKey> {
const state = await this.#load();
if (state.oidcSigningKey) return state.oidcSigningKey;
const pair = (await crypto.subtle.generateKey(
{
name: "RSASSA-PKCS1-v1_5",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256",
},
true,
["sign", "verify"],
)) as CryptoKeyPair;
state.oidcSigningKey = {
kid: crypto.randomUUID(),
privateJwk: (await crypto.subtle.exportKey("jwk", pair.privateKey)) as JsonWebKey,
publicJwk: (await crypto.subtle.exportKey("jwk", pair.publicKey)) as JsonWebKey,
};
await this.#save(state);
return state.oidcSigningKey;
}
/** Seed a pull request an installation reaches; the newest `RECORDS_KEPT` per installation. */
async recordGithubPull(installationId: string, pull: GithubPull): Promise<void> {
const state = await this.#load();
const pulls = (state.githubPulls[installationId] || []).filter(
(known) =>
!(known.owner === pull.owner && known.repo === pull.repo && known.number === pull.number),
);
state.githubPulls = {
...Object.fromEntries(Object.entries(state.githubPulls).slice(-(RECORDS_KEPT - 1))),
[installationId]: [...pulls, pull].slice(-RECORDS_KEPT),
};
await this.#save(state);
}
/** Keep a check run an installation posted: its id, numbered from 1 per installation. */
async recordGithubCheckRun(
installationId: string,
run: Omit<GithubCheckRun, "id">,
): Promise<GithubCheckRun> {
const state = await this.#load();
const runs = state.githubCheckRuns[installationId] || [];
const stored = { ...run, id: runs.length + 1 };
state.githubCheckRuns = {
...Object.fromEntries(Object.entries(state.githubCheckRuns).slice(-(RECORDS_KEPT - 1))),
[installationId]: [...runs, stored].slice(-RECORDS_KEPT),
};
await this.#save(state);
return stored;
}
/** Keep one delivery of the webhook inbox `name`. */
async recordInboxDelivery(name: string, delivery: InboxDelivery): Promise<void> {
const state = await this.#load();
const { [name]: held = [], ...others } = state.webhookInboxes || {};
state.webhookInboxes = Object.fromEntries(
[
...Object.entries(others),
[name, [...held, delivery].slice(-INBOX_DELIVERIES_KEPT)] as const,
].slice(-RECORDS_KEPT),
);
await this.#save(state);
}
/** Mark `id` as adopted among `owner`'s pets, by the account or by a walk-in visitor, and
* answer every pet id that is adopted there. A pet that is adopted already keeps its holder. */
async adoptPet(
owner: string,
id: string,
by: "account" | "walk-in visitor" = "account",
): Promise<string[]> {
const state = await this.#load();
const { [owner]: held = [], ...others } = state.adoptedPets || {};
const adopted = [...new Set([...held, id])].slice(-RECORDS_KEPT);
state.adoptedPets = Object.fromEntries(
[...Object.entries(others), [owner, adopted]].slice(-RECORDS_KEPT),
);
if (by === "walk-in visitor" && !held.includes(id)) {
const { [owner]: visitors = [], ...rest } = state.visitorPets || {};
state.visitorPets = Object.fromEntries(
[...Object.entries(rest), [owner, [...visitors, id]]].slice(-RECORDS_KEPT),
);
}
await this.#save(state);
return adopted;
}
/** Every pet `owner` adopted is up for adoption again. Answers the ids that were adopted. */
async returnPets(owner: string): Promise<string[]> {
const state = await this.#load();
const { [owner]: held = [], ...others } = state.adoptedPets || {};
const { [owner]: _visitors, ...rest } = state.visitorPets || {};
state.adoptedPets = others;
state.visitorPets = rest;
await this.#save(state);
return held;
}
/**
* The pet that a walk-in visitor adopted last among `owner`'s pets, and still holds, is up for
* adoption again. Answers its id, or null when no visitor holds one: a pet that the account
* adopted never comes back this way.
*/
async returnVisitorPet(owner: string): Promise<string | null> {
const state = await this.#load();
const held = state.adoptedPets?.[owner] || [];
const id = (state.visitorPets?.[owner] || []).findLast((other) => held.includes(other));
if (!id) return null;
state.adoptedPets = { ...state.adoptedPets, [owner]: held.filter((other) => other !== id) };
state.visitorPets = {
...state.visitorPets,
[owner]: state.visitorPets![owner]!.filter((other) => other !== id),
};
await this.#save(state);
return id;
}
/** A pet comes into the shop by itself for `owner`. Answers it, with its new id. */
async arrivePet(owner: string, pet: Omit<ArrivedPet, "id">): Promise<ArrivedPet> {
const state = await this.#load();
const seq = (state.arrivedPetSeq ?? 0) + 1;
const arrived = { id: `pet-a${seq}`, ...pet };
const { [owner]: own = [], ...others } = state.arrivedPets || {};
state.arrivedPetSeq = seq;
state.arrivedPets = Object.fromEntries(
[...Object.entries(others), [owner, [...own, arrived].slice(-ARRIVED_PETS_KEPT)]].slice(
-RECORDS_KEPT,
),
);
await this.#save(state);
return arrived;
}
/**
* Begin `owner`'s day: `happenings` things, one every `everyMs`, the first after `everyMs`.
* Both are brought into their bounds. No happenings ends the day that runs, and keeps when it
* began. Answers the day, or null when none began:
*
* - an automatic day (`auto`) begins only when none runs and the account's last day began
* longer ago than `SHOP_DAY_AUTO_ONCE_IN_MS`, so a client that watches again and again does
* not keep the shop busy for ever
* - an account that never had a day gets no record for an end of one
* - when `RECORDS_KEPT` accounts have a day, a new account's day takes the place of the
* oldest that is over for that hour (or whose clock stood still for it). A day that runs
* and an hour that is not over are never given up: the new day does not begin.
*/
async startShopDay(
owner: string,
{ happenings, everyMs, auto }: { happenings: number; everyMs: number; auto: boolean },
now = Date.now(),
): Promise<ShopDay | null> {
const state = await this.#load();
const { [owner]: last, ...others } = state.shopDays || {};
if (auto && last && (last.left > 0 || now - last.startedAt < SHOP_DAY_AUTO_ONCE_IN_MS))
return null;
const left = Math.min(Math.max(Math.trunc(happenings), 0), SHOP_DAY_MOST_HAPPENINGS);
if (left === 0) {
if (!last) return null;
const ended = { ...last, left: 0 };
state.shopDays = { ...state.shopDays, [owner]: ended };
await this.#save(state);
return ended;
}
const days = Object.entries(others);
if (days.length >= RECORDS_KEPT) {
const spare = days.findIndex(([, day]) =>
day.left > 0
? now - day.nextAt >= SHOP_DAY_AUTO_ONCE_IN_MS
: now - day.startedAt >= SHOP_DAY_AUTO_ONCE_IN_MS,
);
if (spare < 0) return null;
days.splice(spare, 1);
}
const every = Math.min(Math.max(everyMs, SHOP_DAY_LEAST_EVERY_MS), SHOP_DAY_MOST_EVERY_MS);
const day: ShopDay = {
startedAt: now,
auto,
everyMs: every,
left,
step: 0,
nextAt: now + every,
};
state.shopDays = Object.fromEntries([...days, [owner, day]]);
await this.#save(state);
return day;
}
/** Keep what webhook callbacks answered, the newest `WEBHOOK_ANSWERS_KEPT` of them. */
async recordWebhookAnswers(answers: WebhookAnswer[]): Promise<void> {
if (answers.length === 0) return;
const state = await this.#load();
state.webhookAnswers = [...(state.webhookAnswers || []), ...answers].slice(
-WEBHOOK_ANSWERS_KEPT,
);
await this.#save(state);
}
/**
* Put `add` at the end of the webhook POSTs that wait, and take the `most` that wait longest.
* One step, so a POST is taken once. Answers the taken, how many still wait, and how many were
* pushed out because more than `PET_DELIVERIES_KEPT` waited.
*/
async exchangePetDeliveries(
add: PetDelivery[],
most: number,
): Promise<{ taken: PetDelivery[]; waiting: number; dropped: number }> {
const state = await this.#load();
const all = [...(state.petDeliveries || []), ...add];
const kept = all.slice(-PET_DELIVERIES_KEPT);
const taken = kept.slice(0, Math.max(most, 0));
if (all.length === 0) return { taken, waiting: 0, dropped: 0 };
state.petDeliveries = kept.slice(taken.length);
await this.#save(state);
return {
taken,
waiting: state.petDeliveries.length,
dropped: all.length - kept.length,
};
}
/**
* Take the next thing of `owner`'s day when it is due: one fewer is left, and the one after is
* due `everyMs` later. Answers the number of the thing to do now (0 is the day's first), or
* null when nothing is due. The count goes down before the thing happens, so a thing that
* fails is not done twice.
*/
async takeShopDayStep(owner: string, now = Date.now()): Promise<number | null> {
const state = await this.#load();
const day = state.shopDays?.[owner];
if (!day || day.left <= 0 || day.nextAt > now) return null;
state.shopDays = {
...state.shopDays,
[owner]: { ...day, left: day.left - 1, step: day.step + 1, nextAt: now + day.everyMs },
};
await this.#save(state);
return day.step;
}
/** Keep one pet event of `owner`, and hand it to every read that waits for one. */
async recordPetEvent(
owner: string,
name: PetEventName,
data: PetEvent["data"],
): Promise<PetEvent> {
const state = await this.#load();
const seq = (state.petEventSeq ?? 0) + 1;
const event: PetEvent = {
seq,
owner,
eventId: `evt_${crypto.randomUUID()}`,
name,
timestamp: new Date().toISOString(),
data,
};
state.petEventSeq = seq;
state.petEvents = [...(state.petEvents || []), event].slice(-PET_EVENTS_KEPT);
await this.#save(state);
for (const wake of this.#petEventWaiters) wake();
return event;
}
/**
* `owner`'s pet events after the cursor `after`; `null` means from now, which answers no event
* and the newest cursor. With `waitMs` and no event yet, the read is held until one is recorded
* or the wait ends (at most `PET_EVENTS_LONGEST_WAIT_MS`): the answer then leaves at the moment
* the shop changes, with nobody asking again.
*/
async petEventsAfter(owner: string, after: number | null, waitMs = 0): Promise<PetEventsRead> {
const read = async (): Promise<PetEventsRead> => {
const { petEvents = [], petEventSeq = 0 } = await this.#load();
// a cursor ahead of the newest event is from a shop whose state began again
if (after === null || after > petEventSeq)
return { events: [], cursor: petEventSeq, truncated: after !== null };
return {
events: petEvents.filter((event) => event.owner === owner && event.seq > after),
cursor: petEventSeq,
truncated: petEvents.length > 0 && after < petEvents[0]!.seq - 1,
};
};
const first = await read();
if (first.events.length > 0 || first.truncated || after === null || waitMs <= 0) return first;
const deadline = Date.now() + Math.min(waitMs, PET_EVENTS_LONGEST_WAIT_MS);
for (;;) {
const left = deadline - Date.now();
if (left <= 0) return await read();
// any account's event wakes the read, which then looks for its own
await new Promise<void>((resolve) => {
const wake = () => {
clearTimeout(timer);
this.#petEventWaiters.delete(wake);
resolve();
};
const timer = setTimeout(wake, left);
this.#petEventWaiters.add(wake);
});
const next = await read();
if (next.events.length > 0 || next.truncated) return next;
}
}
/** Store a subscription under its id, moved to the end, or drop it (`null`). */
async setMcpEventSubscription(
id: string,
subscription: McpEventSubscription | null,
): Promise<void> {
const state = await this.#load();
const { [id]: _replaced, ...others } = state.mcpEventSubscriptions || {};
state.mcpEventSubscriptions = Object.fromEntries(
[...Object.entries(others), ...(subscription ? [[id, subscription]] : [])].slice(
-RECORDS_KEPT,
),
);
await this.#save(state);
}
/** The Google fake's mailbox of `email` (an address in lower case), or undefined when nothing
* changed it yet. */
async gmailMailbox(email: string): Promise<GmailMailbox | undefined> {
return await this.#storage.get<GmailMailbox>(gmailMailboxKey(email));
}
/** One step of that mailbox (google-records.ts `gmailChanged`), kept. */
async changeGmailMailbox(email: string, action: GmailAction) {
const key = gmailMailboxKey(email);
const changed = gmailChanged(await this.#storage.get<GmailMailbox>(key), action, Date.now());
await this.#storage.put(key, changed.mailbox);
await this.#keepGoogleRecord(key);
return changed;
}
/** The Google fake's primary calendar of `email`, or undefined when nothing changed it yet. */
async googleCalendar(email: string): Promise<GoogleCalendar | undefined> {
return await this.#storage.get<GoogleCalendar>(googleCalendarKey(email));
}
/** One step of that calendar (google-records.ts `calendarChanged`), kept. */
async changeGoogleCalendar(email: string, action: CalendarAction) {
const key = googleCalendarKey(email);
const changed = calendarChanged(
await this.#storage.get<GoogleCalendar>(key),
action,
Date.now(),
);
await this.#storage.put(key, changed.calendar);
await this.#keepGoogleRecord(key);
return changed;
}
/** A Google record's key moves to the end of the list of the kept ones, and the value of a key
* that the list no longer holds is deleted. Nothing is written when the key is the newest
* already: a test changes one account many times in a row. */
async #keepGoogleRecord(key: string): Promise<void> {
const state = await this.#load();
const keys = state.googleRecordKeys || [];
if (keys.at(-1) === key) return;
const kept = [...keys.filter((each) => each !== key), key];
for (const dropped of kept.slice(0, -RECORDS_KEPT)) await this.#storage.delete(dropped);
state.googleRecordKeys = kept.slice(-RECORDS_KEPT);
await this.#save(state);
}
async setTokenEndpointFailures(clientId: string, times: number): Promise<void> {
const state = await this.#load();
if (times === 0) delete state.tokenEndpointFailuresRemainingByClient[clientId];
else state.tokenEndpointFailuresRemainingByClient[clientId] = times;
await this.#save(state);
}
/** Atomically consume one scheduled failure for this client. */
async consumeTokenEndpointFailure(clientId: string): Promise<boolean> {
const state = await this.#load();
const remaining = state.tokenEndpointFailuresRemainingByClient[clientId] ?? 0;
if (remaining <= 0) return false;
if (remaining === 1) delete state.tokenEndpointFailuresRemainingByClient[clientId];
else state.tokenEndpointFailuresRemainingByClient[clientId] = remaining - 1;
await this.#save(state);
return true;
}
}
/** A GitHub App installation's registration (`registerApp`): its App's public key, and what
* differs from the seeded installation's. */
interface AppRegistration {
publicKeyPem: string;
appId?: string;
installationId?: string;
webhookSecret?: string;
appSlug?: string;
callbackUrl?: string;
account?: { login: string; id?: number; type?: GithubAccount["type"] };
/** At least one: the first installs the App by default (github.ts). */
users?: [GithubInstallationUser, ...GithubInstallationUser[]];
oauthClientId?: string;
}
/**
* The installation `input` registers, over the one of its id in `registered`. What `input` leaves
* out is the seeded installation's (which is `githubApp({ publicKeyPem: "" }, {})`): the
* well-known ids, the seeded OAuth client, and one admin `petshop-user` on the organization
* `petshop-org`, so the common case is `{ publicKeyPem }`. A replace keeps the existing appId and
* webhook secret unless overridden, so registering a key does not silently rotate the webhook
* secret; a new webhook secret is random, so signature specs prove real verification. An
* account's id defaults to its login's user id.
*/
function githubApp(input: AppRegistration, registered: PetshopState["apps"]): GithubApp {
const installationId = input.installationId || DEFAULT_INSTALLATION_ID;
const existing = registered[installationId];
const account = input.account || { login: "petshop-org" };
return {
appId: input.appId || existing?.appId || DEFAULT_APP_ID,
publicKeyPem: input.publicKeyPem,
installationId,
webhookSecret: input.webhookSecret || existing?.webhookSecret || crypto.randomUUID(),
appSlug: input.appSlug || DEFAULT_APP_ID,
callbackUrl: input.callbackUrl,
account: {
login: account.login,
id: account.id || fakeUserIdOf(account.login),
type: account.type || "Organization",
},
users: input.users || [{ login: "petshop-user", role: "admin" }],
oauthClientId: input.oauthClientId || DEFAULT_CLIENT_ID,
};
}
/** What every route needs from the shop: its state, and the key that seals its codes and tokens.
* `state` is the Durable Object's RPC stub in production and a plain PetshopStore over a map in
* tests (memory-state.ts); Pick<> keeps the two structurally interchangeable. */
export interface ShopDeps {
state: Pick<
PetshopStore,
| "getState"
| "createClient"
| "expireAccessTokens"
| "revokeToken"
| "consumeAuthorizationCode"
| "setTokenEndpointFailures"
| "consumeTokenEndpointFailure"
| "registerApp"
| "recordSlackMessage"
| "oidcSigningKey"
| "recordGithubPull"
| "recordGithubCheckRun"
| "setMcpEventSubscription"
| "adoptPet"
| "recordInboxDelivery"
| "returnPets"
| "returnVisitorPet"
| "arrivePet"
| "startShopDay"
| "takeShopDayStep"
| "exchangePetDeliveries"
| "recordWebhookAnswers"
| "recordPetEvent"
| "petEventsAfter"
| "gmailMailbox"
| "changeGmailMailbox"
| "googleCalendar"
| "changeGoogleCalendar"
>;
sealKey: string;
}