iterate.com / cloud

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

cloud / internal-packages / dummy-petshop / src / pet-stream.tsmain at aacbc74

// pet-stream.ts: THE GALLERY'S OWN CONNECTION TO THE SHOP. MCP Apps gives a host no message that
// pushes new data into a frame that is open. But a frame may open a connection of its own to an
// origin that its resource names in `_meta.ui.csp.connectDomains` (mcp.ts), and on that connection
// the shop pushes with no host in between:
//
//   GET /pets/stream?ticket=<t>[&cursor=<c>]   server-sent events: each message is
//                                              {events, cursor, pets?}, the same as an answer of
//                                              the `watch_pets` tool, sent when a pet event happens
//
// The frame holds no token of the account. So `watch_pets`, which the host calls for the frame as
// the account, answers the stream's address with a ticket in it: the account's name, sealed with
// the shop's key, good for an hour.
import { occurrenceOf, petsOf } from "./pet-events.ts";
import type { Pet } from "./pets.ts";
import { nowSeconds, seal, unseal } from "./seal.ts";
import type { ShopDeps } from "./state.ts";

interface StreamTicket {
  t: "pet-stream";
  owner: string;
  exp: number;
}

const TICKET_TTL_SECONDS = 60 * 60;

/** How long one response lasts. The browser's `EventSource` then opens the next by itself, from
 *  the last message's id. */
const STREAM_LASTS_MS = 4 * 60 * 1000;

/** How long the stream waits for an event before it sends a message with none, which tells the
 *  frame that the connection is alive. */
const QUIET_MS = 15_000;

// the frame's origin is the host's sandbox, a different one in each host
const CORS = { "access-control-allow-origin": "*", "access-control-allow-headers": "*" };

/** The address at `origin` of the stream of `owner`'s pet events, with a fresh ticket. */
export async function petStreamUrl(deps: ShopDeps, origin: string, owner: string) {
  const ticket: StreamTicket = { t: "pet-stream", owner, exp: nowSeconds() + TICKET_TTL_SECONDS };
  return `${origin}/pets/stream?ticket=${await seal(ticket, deps.sealKey)}`;
}

/** A request for the stream: the stream, or null for any other request. */
export async function handlePetStream(
  request: Request,
  deps: ShopDeps & { pets: Pet[] },
): Promise<Response | null> {
  const url = new URL(request.url);
  if (url.pathname !== "/pets/stream") return null;
  if (request.method === "OPTIONS") return new Response(null, { status: 204, headers: CORS });
  const ticket = await unseal<StreamTicket>(url.searchParams.get("ticket") || "", deps.sealKey);
  if (request.method !== "GET" || ticket?.t !== "pet-stream" || ticket.exp < nowSeconds())
    return Response.json({ error: "invalid_ticket" }, { status: 401, headers: CORS });

  const { owner } = ticket;
  // a connection that `EventSource` opened again says where the last one ended
  const from = request.headers.get("last-event-id") ?? url.searchParams.get("cursor");
  let after = /^\d+$/.test(from || "")
    ? Number(from)
    : (await deps.state.petEventsAfter(owner, null)).cursor;
  const ends = Date.now() + STREAM_LASTS_MS;
  const encoder = new TextEncoder();
  const body = new ReadableStream<Uint8Array>({
    start(controller) {
      controller.enqueue(encoder.encode("retry: 1000\n\n"));
    },
    // one held read of the shop's events for each message; a closed connection asks for no more
    async pull(controller) {
      if (Date.now() >= ends) return controller.close();
      const read = await deps.state.petEventsAfter(owner, after, QUIET_MS);
      after = read.cursor;
      const changed = read.events.length > 0 || read.truncated;
      const message = {
        events: read.events.map(occurrenceOf),
        cursor: String(read.cursor),
        ...(changed && { pets: await petsOf(deps.state, owner, deps.pets) }),
      };
      controller.enqueue(
        encoder.encode(`id: ${read.cursor}\ndata: ${JSON.stringify(message)}\n\n`),
      );
    },
  });
  return new Response(body, {
    headers: { ...CORS, "content-type": "text/event-stream", "cache-control": "no-cache" },
  });
}