iterate.com / cloud

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

cloud / internal-packages / dummy-petshop / src / durable-object.tsmain at aacbc74

import { DurableObject } from "cloudflare:workers";
import { seedPets } from "./pets.ts";
import { postPetEvents } from "./pet-events.ts";
import { nextShopDayAt, runShopDays, takeDeliveries } from "./shop-day.ts";
import { PetshopStore } from "./state.ts";
import type { Env } from "./worker.ts";

/**
 * The one object's name. It is created in ENAM (`locationHint`, which only takes effect when an
 * object is created), beside the callers that make nearly all its calls: CI runners in AWS
 * us-east-1, which reach Cloudflare at IAD, and the preview Workers at IAD and EWR. From there a
 * call to an object in Europe crosses the Atlantic twice. A new object starts from the seed
 * (state.ts `PetshopStore`).
 */
export const PETSHOP_STATE_NAME = "enam";

/**
 * The one Durable Object behind the whole app (named {@link PETSHOP_STATE_NAME}): the shop's state
 * (state.ts `PetshopStore`) over its storage. Its input gate serializes the store's load → mutate →
 * save methods, which the worker calls over RPC.
 */
export class PetshopStateDurableObject extends DurableObject<Env> {
  readonly #store = new PetshopStore(this.ctx.storage);

  getState() {
    return this.#store.getState();
  }
  createClient(...args: Parameters<PetshopStore["createClient"]>) {
    return this.#store.createClient(...args);
  }
  expireAccessTokens(...args: Parameters<PetshopStore["expireAccessTokens"]>) {
    return this.#store.expireAccessTokens(...args);
  }
  revokeToken(...args: Parameters<PetshopStore["revokeToken"]>) {
    return this.#store.revokeToken(...args);
  }
  consumeAuthorizationCode(...args: Parameters<PetshopStore["consumeAuthorizationCode"]>) {
    return this.#store.consumeAuthorizationCode(...args);
  }
  registerApp(...args: Parameters<PetshopStore["registerApp"]>) {
    return this.#store.registerApp(...args);
  }
  recordGithubPull(...args: Parameters<PetshopStore["recordGithubPull"]>) {
    return this.#store.recordGithubPull(...args);
  }
  recordGithubCheckRun(...args: Parameters<PetshopStore["recordGithubCheckRun"]>) {
    return this.#store.recordGithubCheckRun(...args);
  }
  oidcSigningKey() {
    return this.#store.oidcSigningKey();
  }
  recordSlackMessage(...args: Parameters<PetshopStore["recordSlackMessage"]>) {
    return this.#store.recordSlackMessage(...args);
  }
  setMcpEventSubscription(...args: Parameters<PetshopStore["setMcpEventSubscription"]>) {
    return this.#store.setMcpEventSubscription(...args);
  }
  adoptPet(...args: Parameters<PetshopStore["adoptPet"]>) {
    return this.#store.adoptPet(...args);
  }
  recordInboxDelivery(...args: Parameters<PetshopStore["recordInboxDelivery"]>) {
    return this.#store.recordInboxDelivery(...args);
  }
  returnPets(...args: Parameters<PetshopStore["returnPets"]>) {
    return this.#store.returnPets(...args);
  }
  returnVisitorPet(...args: Parameters<PetshopStore["returnVisitorPet"]>) {
    return this.#store.returnVisitorPet(...args);
  }
  arrivePet(...args: Parameters<PetshopStore["arrivePet"]>) {
    return this.#store.arrivePet(...args);
  }
  takeShopDayStep(...args: Parameters<PetshopStore["takeShopDayStep"]>) {
    return this.#store.takeShopDayStep(...args);
  }
  exchangePetDeliveries(...args: Parameters<PetshopStore["exchangePetDeliveries"]>) {
    return this.#store.exchangePetDeliveries(...args);
  }
  recordWebhookAnswers(...args: Parameters<PetshopStore["recordWebhookAnswers"]>) {
    return this.#store.recordWebhookAnswers(...args);
  }
  /** Begin an account's day (shop-day.ts), and set the clock for its first happening. */
  async startShopDay(...args: Parameters<PetshopStore["startShopDay"]>) {
    const day = await this.#store.startShopDay(...args);
    await this.#setShopDayAlarm();
    return day;
  }
  /**
   * The clock of the shop's days. A tick keeps every account's happening that is due, queues the
   * events' webhook POSTs and takes a bounded number of those that wait, and sets the alarm for
   * the next tick. Only then do the taken POSTs go out, all at once (shop-day.ts). So no
   * callback, however slow, holds up another account's event or the next tick. The happenings
   * are the object's own pets and each account's arrived pets: a pet that a client added
   * (`create_pet`) is in the memory of the worker's isolate alone, so a visitor of a day does not
   * see it. Nothing here throws, so the platform never runs an alarm again.
   */
  override async alarm() {
    const due = await runShopDays(this.#store, seedPets())
      .then((happened) => takeDeliveries(this.#store, happened))
      .catch((error) => {
        console.error({ event: "petshop.shop-day-failed", message: String(error) });
        return [];
      });
    await this.#setShopDayAlarm();
    this.ctx.waitUntil(
      postPetEvents(this.#store, due).catch((error) =>
        console.error({ event: "petshop.shop-day-post-failed", message: String(error) }),
      ),
    );
  }
  async #setShopDayAlarm() {
    const at = nextShopDayAt(await this.#store.getState());
    if (at !== null) await this.ctx.storage.setAlarm(Math.max(at, Date.now() + 1000));
  }
  recordPetEvent(...args: Parameters<PetshopStore["recordPetEvent"]>) {
    return this.#store.recordPetEvent(...args);
  }
  petEventsAfter(...args: Parameters<PetshopStore["petEventsAfter"]>) {
    return this.#store.petEventsAfter(...args);
  }
  gmailMailbox(...args: Parameters<PetshopStore["gmailMailbox"]>) {
    return this.#store.gmailMailbox(...args);
  }
  changeGmailMailbox(...args: Parameters<PetshopStore["changeGmailMailbox"]>) {
    return this.#store.changeGmailMailbox(...args);
  }
  googleCalendar(...args: Parameters<PetshopStore["googleCalendar"]>) {
    return this.#store.googleCalendar(...args);
  }
  changeGoogleCalendar(...args: Parameters<PetshopStore["changeGoogleCalendar"]>) {
    return this.#store.changeGoogleCalendar(...args);
  }
  setTokenEndpointFailures(...args: Parameters<PetshopStore["setTokenEndpointFailures"]>) {
    return this.#store.setTokenEndpointFailures(...args);
  }
  consumeTokenEndpointFailure(...args: Parameters<PetshopStore["consumeTokenEndpointFailure"]>) {
    return this.#store.consumeTokenEndpointFailure(...args);
  }
}