iterate.com / kernel

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

kernel / core / itx / src / context / catalog-watch.tsmain at 949894f

// catalog-watch.ts — THE SESSION'S END OF A WATCH OF THE CATALOG (`itx.contexts.watch`). A client
// holds a capnweb callback and nothing else: its frames ride the connection that its session has
// already. This file is what stands between that callback and the object that owns the rows:
//
//   client ─capnweb, the session's one connection─► the session's end (../iterate-context.ts)
//   the session's end ─ONE hibernated WebSocket for all of the session's watches─► /awake
//   /awake (reactive-catalog.ts) ─a message for each write─► here ─`onFrame(frame)`─► client
//
// The socket is dialled at the session's first watch and closed with its last one, or with the
// session. It is the kernel's own dial into the context that accepts the awake sockets, as a
// context's awake socket is (awake.ts): no client, no loaded code and no other Worker can open one.
// The callback's stub lives here, in the stateless Worker, never in a Durable Object, so /awake
// hibernates under any number of watchers.
//
// A SOCKET THAT ENDS UNDER A LIVE SESSION (a deploy resets every Durable Object) is dialled again,
// and every watch is asked again with no cursor: each watcher gets a `reset` frame with the whole
// answer. A frame that does not follow the one before (`from`) is treated the same way. When the
// socket cannot be dialled again, every watch ends, and its handle's `ended()` says why.
import { RpcTarget } from "capnweb";
import { z } from "zod";
import type { CatalogCursor, CatalogFrame, CatalogQuery } from "iterate/api";
import { codedError } from "iterate/lib";
import type { Caller } from "../caller.ts";
import { unavailableError } from "../unavailable.ts";
import { redial } from "./redial.ts";
import { CatalogRefusal, normalizeQuery } from "./reactive-catalog.ts";
import {
  disposeRpcStub,
  RPC_STUB_PAGER_KEEPALIVE_REQUEST,
  RPC_STUB_PAGER_KEEPALIVE_RESPONSE,
} from "./rpc-stubs.ts";

/** On a request to the context that accepts the awake sockets: the upgrade of a watch socket. */
export const CATALOG_WATCH_HEADER = "x-itx-catalog-watch";

/** How long a watch socket that dropped under a live session is dialled again before every watch
 *  ends: as long as a lent stub's pager (rpc-stub-relay.ts). */
const REDIAL_DEADLINE_MS = 60_000;
/** A subscribe that the catalog does not answer in this time fails. The first watch of a mind
 *  waits for the catalog's first fill, a page of 500 rows at a time. */
const ANSWER_DEADLINE_MS = 60_000;
/** The runtime answers a keepalive for /awake, which sleeps on (the Durable Object's
 *  `setWebSocketAutoResponse`). Three in a row unanswered: the socket is dead, with no close. */
const KEEPALIVE_EVERY_MS = 5_000;

const WatchOptions = z.strictObject({ cursor: z.unknown().optional() }).optional();

/** WHAT THE BUILT-IN `contexts.watch(query, options)` ANSWERS: the query, checked, for the
 *  session's end, which alone holds a callback and a socket. The built-in is reached through a
 *  context's own table, as `contexts.list` is, so who may list may watch. A ticket is data: it
 *  opens nothing, and whoever else reads one has what it sent. */
export type CatalogWatchTicket = {
  $itxCatalogWatch: { query: CatalogQuery; cursor?: CatalogCursor };
};

/** WHO MAY WATCH, AND WHO MAY ASK WHAT IS WATCHED: a session that is no code's (a member's, or
 *  the platform's own). Loaded code is refused, whatever its table lets through: `watches()`
 *  names the paths and the facts that other sessions ask for, which a rule that narrows
 *  `contexts.list` for some code does not narrow. The boundary is here, by the caller, and not by
 *  the name `contexts`. */
export function refuseLoadedCode(caller: Pick<Caller, "app">, call: "watch" | "watches"): void {
  if (caller.app)
    throw codedError(
      "FORBIDDEN",
      `contexts.${call} is a session's call: loaded code reads the catalog with contexts.list(options)`,
    );
}

export function catalogWatchTicket(query: unknown, options: unknown): CatalogWatchTicket {
  const parsed = WatchOptions.safeParse(options);
  if (!parsed.success)
    throw codedError(
      "INVALID_INPUT",
      "contexts.watch(query, onFrame, { cursor? }) is a session's call: the callback stays at the session's end, and the only option is a cursor. Loaded code reads the catalog with contexts.list(options)",
    );
  try {
    normalizeQuery(query);
  } catch (error) {
    if (error instanceof CatalogRefusal)
      throw codedError("INVALID_INPUT", `contexts.watch: ${error.message}`);
    throw error;
  }
  return {
    $itxCatalogWatch: {
      // checked above, and again by the catalog itself, which trusts no ticket
      query: query as CatalogQuery,
      cursor: parsed.data?.cursor as CatalogCursor | undefined,
    },
  };
}

export function isCatalogWatchTicket(value: unknown): value is CatalogWatchTicket {
  // oxlint-disable-next-line iterate/simple-truthiness-check -- an answer of any shape: a table may send `contexts` to another object, which answers what it likes
  return typeof value === "object" && value !== null && "$itxCatalogWatch" in value;
}

/** What `itx.contexts.watch` answers: a handle whose dispose ends the watch. `ended()` settles
 *  when the watch ends in any other way, with the reason: the session ended, or the catalog could
 *  not be reached again. */
export class CatalogWatchHandle extends RpcTarget {
  readonly #end: () => void;
  readonly #ended: Promise<string>;
  constructor(end: () => void, ended: Promise<string>) {
    super();
    this.#end = end;
    this.#ended = ended;
  }
  ended(): Promise<string> {
    return this.#ended;
  }
  [Symbol.dispose](): void {
    this.#end();
  }
}

/** A watcher's callback as this end holds it: a stub of the client's function, or the function. */
type FrameCallback = ((frame: CatalogFrame<unknown>) => unknown) & { dup?(): FrameCallback };

type Watch = {
  query: CatalogQuery;
  onFrame: FrameCallback;
  /** Of the watch's last frame: a change must follow it. */
  gen: string;
  rev: number;
  /** Its query went to the catalog on a socket: a socket that takes that one's place asks it
   *  again. A watch that still waits for the first socket sends its query itself. */
  asked: boolean;
  /** Settles the call that made the watch, at the catalog's first answer or its refusal. */
  answered?: {
    resolve: () => void;
    reject: (error: Error) => void;
    timer: ReturnType<typeof setTimeout>;
  };
  end: (reason: string) => void;
};

/** What the catalog sends down a watch socket (reactive-catalog.ts, "THE WIRE"). */
const SocketMessage = z.union([
  z.object({
    sub: z.string(),
    q: z.string(),
    gen: z.string(),
    rev: z.number(),
    full: z.boolean(),
    reset: z.array(z.unknown()).optional(),
    ids: z.array(z.string()).optional(),
    put: z.array(z.unknown()).optional(),
  }),
  z.object({
    gen: z.string(),
    rows: z.array(z.looseObject({ path: z.string() })),
    d: z.array(
      z.tuple([z.string(), z.number(), z.number(), z.array(z.string()), z.array(z.string())]),
    ),
    /** More of the same write comes in the next message. */
    more: z.literal(true).optional(),
  }),
  z.object({
    sub: z.string().optional(),
    error: z.string(),
    kind: z.enum(["query", "limit", "failed"]).optional(),
  }),
]);

type DialAnswer = { status: number; webSocket?: WebSocket | null; body?: ReadableStream | null };

/** ONE SESSION'S WATCHES, over one socket into the catalog. */
export class CatalogWatchRelay {
  readonly #dial: () => Promise<DialAnswer>;
  readonly #waitUntil: (work: Promise<unknown>) => void;
  readonly #watches = new Map<string, Watch>();
  #socket: WebSocket | undefined;
  #opening: Promise<WebSocket> | undefined;
  #keepalive: ReturnType<typeof setInterval> | undefined;
  #names = 0;
  #over = false;
  /** The frames of a write that the catalog sends in several messages: they go when its last
   *  message has come, as one batch. */
  #heldFrames: { sub: string; watch: Watch; frame: CatalogFrame<unknown> }[] = [];

  constructor(deps: {
    /** The upgrade request to the context that accepts the awake sockets. */
    dial: () => Promise<DialAnswer>;
    waitUntil: (work: Promise<unknown>) => void;
  }) {
    this.#dial = deps.dial;
    this.#waitUntil = deps.waitUntil;
  }

  /** Asks the catalog to keep answering the ticket's query. Resolves when `onFrame` has RETURNED
   *  from the first frame, the answer: a watcher that awaits the call has the answer. Waiting for
   *  the function's return is what makes that true for a session that ends in another Worker,
   *  where the call's answer and a call of the function travel apart, in no order. Rejects with
   *  the catalog's reason when it refuses the query. */
  async watch(ticket: CatalogWatchTicket, onFrame: FrameCallback): Promise<CatalogWatchHandle> {
    if (this.#over) throw unavailableError("disconnected", "contexts.watch: the session ended");
    const { query, cursor } = ticket.$itxCatalogWatch;
    // dup first: the stub is the call's alone, and a watch outlives the call
    const callback = onFrame.dup ? onFrame.dup() : onFrame;
    const sub = `w${(this.#names += 1).toString(36)}`;
    let settleEnded = (_reason: string) => {};
    const ended = new Promise<string>((resolve) => (settleEnded = resolve));
    const watch: Watch = {
      query,
      onFrame: callback,
      gen: "",
      rev: -1,
      asked: false,
      end: (reason) => {
        if (this.#watches.get(sub) !== watch) return;
        this.#watches.delete(sub);
        if (watch.answered) {
          clearTimeout(watch.answered.timer);
          watch.answered.reject(unavailableError("disconnected", `contexts.watch: ${reason}`));
        }
        disposeRpcStub(callback);
        settleEnded(reason);
        if (this.#watches.size === 0) this.#closeSocket();
      },
    };
    this.#watches.set(sub, watch);
    // capnweb's death signal for the client's stub: the watch has nobody to tell
    (callback as { onRpcBroken?: (broken: () => void) => void }).onRpcBroken?.(() =>
      this.#drop(sub, "the watcher's session broke"),
    );
    try {
      const socket = await this.#open();
      await new Promise<void>((resolve, reject) => {
        watch.answered = {
          resolve,
          reject,
          timer: setTimeout(
            // our own deadline is an overload: the caller may ask again later, never at once
            () =>
              reject(unavailableError("overloaded", "contexts.watch: the catalog did not answer")),
            ANSWER_DEADLINE_MS,
          ),
        };
        socket.send(JSON.stringify({ op: "subscribe", sub, query, cursor }));
        watch.asked = true;
      });
    } catch (error) {
      watch.answered = undefined;
      this.#drop(sub, "the watch was refused");
      throw error;
    }
    return new CatalogWatchHandle(() => this.#drop(sub, "the watcher ended it"), ended);
  }

  /** The session's end: every watch ends with it, and the socket closes. Final. */
  dispose(): void {
    this.#over = true;
    for (const watch of [...this.#watches.values()]) watch.end("the session ended");
    this.#closeSocket();
  }

  #drop(sub: string, reason: string): void {
    const watch = this.#watches.get(sub);
    if (!watch) return;
    try {
      this.#socket?.send(JSON.stringify({ op: "unsubscribe", sub }));
    } catch {
      // a socket that is closing takes its queries with it
    }
    watch.end(reason);
  }

  #closeSocket(): void {
    clearInterval(this.#keepalive);
    this.#keepalive = undefined;
    // the rest of a write that this socket was sending does not come: its watches are asked again
    this.#heldFrames = [];
    const socket = this.#socket;
    this.#socket = undefined;
    try {
      socket?.close(1000, "no watch is left");
    } catch {
      // already closing
    }
  }

  #open(): Promise<WebSocket> {
    if (this.#socket) return Promise.resolve(this.#socket);
    this.#opening ||= this.#dial()
      .then(async (answer) => {
        if (answer.status !== 101 || !answer.webSocket) {
          await answer.body?.cancel();
          throw unavailableError(
            "disconnected",
            `contexts.watch: the catalog answered the dial ${answer.status}`,
          );
        }
        answer.webSocket.accept();
        // the session ended, or its last watch went, while the dial was on its way
        if (this.#over || this.#watches.size === 0) {
          answer.webSocket.close(1000, "no watch is left");
          throw unavailableError("disconnected", "contexts.watch: the session ended");
        }
        this.#attach(answer.webSocket);
        return answer.webSocket;
      })
      .finally(() => (this.#opening = undefined));
    return this.#opening;
  }

  #attach(socket: WebSocket): void {
    this.#socket = socket;
    let unanswered = 0;
    clearInterval(this.#keepalive);
    this.#keepalive = setInterval(() => {
      if (this.#socket !== socket) return;
      if (unanswered >= 3) return this.#lost(socket, "its keepalives went unanswered");
      // counted before the send: a send that throws is a keepalive that nobody answers
      unanswered += 1;
      try {
        socket.send(RPC_STUB_PAGER_KEEPALIVE_REQUEST);
      } catch {
        // closing: its close event, or three unanswered keepalives, dials again
      }
    }, KEEPALIVE_EVERY_MS);
    socket.addEventListener("message", (event) => {
      unanswered = 0;
      if (this.#socket !== socket || typeof event.data !== "string") return;
      if (event.data === RPC_STUB_PAGER_KEEPALIVE_RESPONSE) return;
      this.#received(event.data);
    });
    const gone = (event: { reason?: string }) => this.#lost(socket, event.reason || "it closed");
    socket.addEventListener("close", gone);
    socket.addEventListener("error", () => gone({ reason: "it failed" }));
  }

  /** The socket ended under watches that live: dial again, and ask every query again. A watch
   *  that starts meanwhile waits for this dial (`#open`), and dials none of its own: two sockets
   *  of one session would each get the frames of the watches that were asked on it. */
  #lost(socket: WebSocket, why: string): void {
    if (this.#socket !== socket) return;
    this.#closeSocket();
    if (this.#over || this.#watches.size === 0) return;
    const redialing = redial(
      this.#dial as () => Promise<DialAnswer & { webSocket?: WebSocket | null }>,
      () => this.#over || this.#watches.size === 0,
      REDIAL_DEADLINE_MS,
    ).then((redialed) => {
      if (!redialed) throw unavailableError("disconnected", "contexts.watch: the session ended");
      if ("gaveUp" in redialed) {
        console.error({
          event: "catalog-watch.redial-failed",
          message:
            "a session's watch socket dropped and could not be dialled again: its watches end",
          why,
          lastFailure: redialed.gaveUp,
        });
        for (const watch of [...this.#watches.values()])
          watch.end("the catalog could not be reached again: watch again");
        throw unavailableError(
          "disconnected",
          "contexts.watch: the catalog could not be reached again: watch again",
        );
      }
      console.info({ event: "catalog-watch.redialed", why, attempt: redialed.dials });
      this.#attach(redialed.socket);
      for (const [sub, watch] of this.#watches) if (watch.asked) this.#askAgain(sub);
      return redialed.socket;
    });
    this.#opening = redialing;
    this.#waitUntil(
      redialing
        .then(
          () => {},
          () => {},
        )
        .finally(() => {
          if (this.#opening === redialing) this.#opening = undefined;
        }),
    );
  }

  /** The watcher's next frame is the whole answer: it holds a frame that the catalog's next one
   *  does not follow, or none that this socket knows of. */
  #askAgain(sub: string): void {
    const watch = this.#watches.get(sub);
    if (!watch) return;
    watch.gen = "";
    watch.rev = -1;
    try {
      this.#socket?.send(JSON.stringify({ op: "subscribe", sub, query: watch.query }));
    } catch {
      // closing: the socket's end dials again and asks again
    }
  }

  #received(raw: string): void {
    let message: z.infer<typeof SocketMessage>;
    try {
      message = SocketMessage.parse(JSON.parse(raw));
    } catch {
      // the catalog's greeting, and its word that a query is taken off: nothing for a watcher
      return;
    }
    if ("error" in message) {
      const watch = this.#watches.get(message.sub || "");
      if (!watch) return;
      if (!watch.answered) return watch.end(message.error);
      clearTimeout(watch.answered.timer);
      // Each kind has its own code, so that a watcher knows what to do: write another query,
      // dispose a watch, or read the catalog in another way (`contexts.list`). The catalog's own
      // failure has no code: it is a defect, and the catalog reported it.
      const text = `contexts.watch: ${message.error}`;
      watch.answered.reject(
        message.kind === "query"
          ? codedError("INVALID_INPUT", text)
          : message.kind === "limit"
            ? codedError("WATCH_LIMIT", text)
            : new Error(text),
      );
      return;
    }
    if ("d" in message) {
      const rows = new Map(message.rows.map((row) => [row.path, row]));
      for (const [sub, from, rev, del, put] of message.d) {
        const watch = this.#watches.get(sub);
        // a watch that waits for its answer takes no change: the answer is newer than it
        if (!watch || watch.rev < 0) continue;
        if (watch.gen !== message.gen || watch.rev !== from) {
          this.#askAgain(sub);
          continue;
        }
        watch.rev = rev;
        this.#heldFrames.push({
          sub,
          watch,
          frame: {
            type: "change",
            gen: message.gen,
            from,
            rev,
            del,
            rows: put.map((path) => rows.get(path)),
          },
        });
      }
      // ONE WRITE IS ONE BATCH, however many messages the catalog cut it into: its frames go
      // when the last message has come. `more` is over the frames that go: the last one to go
      // ends the batch, whatever the catalog held for a watch that is gone or is asked again.
      if (message.more) return;
      const batch = this.#heldFrames.filter(({ sub, watch }) => this.#watches.get(sub) === watch);
      this.#heldFrames = [];
      batch.forEach(({ watch, frame }, at) =>
        this.#send(watch, at < batch.length - 1 ? { ...frame, more: true } : frame),
      );
      return;
    }
    const watch = this.#watches.get(message.sub);
    if (!watch) return;
    watch.gen = message.gen;
    watch.rev = message.rev;
    const head = { gen: message.gen, rev: message.rev, q: message.q, full: message.full };
    const handed = this.#send(
      watch,
      message.reset
        ? { type: "reset", ...head, rows: message.reset }
        : { type: "resume", ...head, ids: message.ids || [], rows: message.put || [] },
    );
    const { answered } = watch;
    if (!answered) return;
    // the call that made the watch settles when the watcher's function has returned from this
    // frame; until then the watch's end, or the deadline, still rejects it
    void handed.then(() => {
      if (watch.answered !== answered) return;
      clearTimeout(answered.timer);
      watch.answered = undefined;
      answered.resolve();
    });
  }

  /** One frame to one watcher: settles when the watcher's function has returned from it, or
   *  thrown. A change waits for nobody: the catalog's next frame goes when it comes, and a
   *  function that throws is its own page's fault. */
  #send(watch: Watch, frame: CatalogFrame<unknown>): Promise<void> {
    try {
      return Promise.resolve(watch.onFrame(frame)).then(disposeRpcStub, () => {});
    } catch {
      // a stub that broke: its `onRpcBroken` ends the watch
      return Promise.resolve();
    }
  }
}

const relays = new WeakMap<object, CatalogWatchRelay>();

/** The one relay of a session: every context that the session reaches by `cd` shares its
 *  teardown, and so shares the socket. `register` puts the relay's end into that teardown. */
export function catalogWatchRelayOf(
  session: object,
  make: () => CatalogWatchRelay,
  register: (relay: CatalogWatchRelay) => void,
): CatalogWatchRelay {
  let relay = relays.get(session);
  if (!relay) {
    relay = make();
    relays.set(session, relay);
    register(relay);
  }
  return relay;
}