iterate.com / kernel

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

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

// The session's end of a watch of the catalog: what it does when the socket into the catalog
// drops, when a frame is missing, when the catalog refuses a query and when the session ends. The
// catalog's end is a socket that a test writes to by hand; the whole path, with a real catalog and
// a real capnweb session, is core/mind-worker/src/context/catalog-watch.test.ts.
import type { CatalogFrame } from "iterate/api";
import { expect, onTestFinished, test, vi } from "vitest";
import {
  CatalogWatchRelay,
  catalogWatchTicket,
  isCatalogWatchTicket,
  refuseLoadedCode,
} from "./catalog-watch.ts";
import {
  RPC_STUB_PAGER_KEEPALIVE_REQUEST,
  RPC_STUB_PAGER_KEEPALIVE_RESPONSE,
} from "./rpc-stubs.ts";

test("a watch sends the query once, and the catalog's answer and changes come as frames", async () => {
  const far = catalog();
  const relay = far.relay();
  const frames: CatalogFrame<unknown>[] = [];
  const watching = relay.watch(ticket({ where: { status: "open" } }), (frame) =>
    frames.push(frame),
  );
  const socket = await far.asked();
  expect(socket).toMatchObject({
    sent: [{ op: "subscribe", sub: "w1", query: { where: { status: "open" } } }],
  });
  socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [{ path: "/a" }] });
  using _watch = await watching;
  socket.say({ gen: "g", rows: [{ path: "/b" }], d: [["w1", 4, 5, ["/a"], ["/b"]]] });
  expect(frames).toEqual([
    { type: "reset", gen: "g", rev: 4, q: "q", full: false, rows: [{ path: "/a" }] },
    { type: "change", gen: "g", from: 4, rev: 5, del: ["/a"], rows: [{ path: "/b" }] },
  ]);
});

test("a cursor goes with the query, and its answer is a resume frame", async () => {
  const far = catalog();
  const relay = far.relay();
  const frames: CatalogFrame<unknown>[] = [];
  const cursor = { gen: "g", rev: 3, q: "q", bound: [7, "/a"] as [number, string] };
  const watching = relay.watch(catalogWatchTicket({ limit: 5 }, { cursor }), (frame) =>
    frames.push(frame),
  );
  const socket = await far.asked();
  expect(socket.sent[0]).toMatchObject({ cursor });
  socket.say({ sub: "w1", q: "q", gen: "g", rev: 6, full: true, ids: ["/a", "/b"], put: [] });
  using _watch = await watching;
  expect(frames).toEqual([
    { type: "resume", gen: "g", rev: 6, q: "q", full: true, ids: ["/a", "/b"], rows: [] },
  ]);
});

test("one message of the catalog is one batch: every frame but the last says that more comes", async () => {
  const far = catalog();
  const relay = far.relay();
  const batch: [string, boolean][] = [];
  const first = relay.watch(ticket({ limit: 1 }), (frame) => batch.push(["first", !!frame.more]));
  const socket = await far.asked();
  const second = relay.watch(ticket({ limit: 2 }), (frame) => batch.push(["second", !!frame.more]));
  await far.asked(2);
  for (const sub of ["w1", "w2"])
    socket.say({ sub, q: "q", gen: "g", rev: 1, full: false, reset: [] });
  using _first = await first;
  using _second = await second;
  batch.length = 0;
  socket.say({
    gen: "g",
    rows: [{ path: "/a" }],
    d: [
      ["w1", 1, 2, [], ["/a"]],
      ["w2", 1, 2, [], ["/a"]],
    ],
  });
  expect(batch).toEqual([
    ["first", true],
    ["second", false],
  ]);
});

test("a write that the catalog sends in several messages goes to its watchers as one batch, when the last has come", async () => {
  const far = catalog();
  const relay = far.relay();
  const batch: [string, string[], boolean][] = [];
  const watches = ["first", "second", "third"].map((name, at) =>
    relay.watch(ticket({ limit: at + 1 }), (frame) =>
      batch.push([name, (frame.rows as { path: string }[]).map((row) => row.path), !!frame.more]),
    ),
  );
  const socket = await far.asked(3);
  for (const sub of ["w1", "w2", "w3"])
    socket.say({ sub, q: "q", gen: "g", rev: 1, full: false, reset: [] });
  const [first, second, third] = await Promise.all(watches);
  using _first = first;
  using _second = second;
  batch.length = 0;
  // the first of two messages of one write: nothing goes yet
  socket.say({
    gen: "g",
    more: true,
    rows: [{ path: "/a" }],
    d: [
      ["w1", 1, 2, [], ["/a"]],
      ["w2", 1, 2, [], ["/a"]],
    ],
  });
  expect(batch).toEqual([]);
  // the third watch goes away between the two messages
  third![Symbol.dispose]();
  socket.say({
    gen: "g",
    rows: [{ path: "/b" }],
    d: [
      ["w3", 1, 2, [], ["/b"]],
      ["w1", 2, 3, [], ["/b"]],
    ],
  });
  expect(batch).toEqual([
    ["first", ["/a"], true],
    ["second", ["/a"], true],
    ["first", ["/b"], false],
  ]);
});

test("the rest of a write that a dropped socket was sending does not come: its frames are not handed on", async () => {
  vi.useFakeTimers();
  onTestFinished(() => void vi.useRealTimers());
  vi.spyOn(console, "info").mockImplementation(() => {});
  const far = catalog();
  const relay = far.relay();
  const frames: CatalogFrame<unknown>[] = [];
  const watching = relay.watch(ticket({ limit: 5 }), (frame) => frames.push(frame));
  const socket = await far.asked();
  socket.say({ sub: "w1", q: "q", gen: "g", rev: 1, full: false, reset: [] });
  using _watch = await watching;
  socket.say({ gen: "g", more: true, rows: [{ path: "/a" }], d: [["w1", 1, 2, [], ["/a"]]] });
  socket.drop();
  await vi.advanceTimersByTimeAsync(10);
  const again = await far.asked();
  again.say({ sub: "w1", q: "q", gen: "g", rev: 3, full: false, reset: [{ path: "/a" }] });
  // the answer of the new socket alone: no half of the write that was cut
  expect(frames.map((frame) => frame.type)).toEqual(["reset", "reset"]);
});

test("a frame that does not follow the one before asks the query again, and the watcher gets the whole answer", async () => {
  const far = catalog();
  const relay = far.relay();
  const frames: CatalogFrame<unknown>[] = [];
  const watching = relay.watch(ticket({ limit: 5 }), (frame) => frames.push(frame));
  const socket = await far.asked();
  socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [] });
  using _watch = await watching;
  // revision 5 never came
  socket.say({ gen: "g", rows: [{ path: "/a" }], d: [["w1", 5, 6, [], ["/a"]]] });
  expect(frames).toHaveLength(1);
  // asked again with no cursor: this end holds no row to make one from
  expect(socket.sent.at(-1)).toEqual({ op: "subscribe", sub: "w1", query: { limit: 5 } });
  // a change that comes before the new answer is older than it, and is not passed on
  socket.say({ gen: "g", rows: [], d: [["w1", 6, 7, ["/a"], []]] });
  socket.say({ sub: "w1", q: "q", gen: "g", rev: 7, full: false, reset: [{ path: "/b" }] });
  expect(frames.at(-1)).toMatchObject({ type: "reset", rev: 7, rows: [{ path: "/b" }] });
  expect(frames).toHaveLength(2);
});

test("a socket that drops under a live session is dialled again, and every watch gets its whole answer", async () => {
  vi.useFakeTimers();
  onTestFinished(() => void vi.useRealTimers());
  vi.spyOn(console, "info").mockImplementation(() => {});
  const far = catalog();
  const relay = far.relay();
  const frames: CatalogFrame<unknown>[] = [];
  const watching = relay.watch(ticket({ limit: 5 }), (frame) => frames.push(frame));
  const socket = await far.asked();
  socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [{ path: "/a" }] });
  using _watch = await watching;
  // a deploy resets the catalog's object: the socket closes
  socket.drop();
  await vi.advanceTimersByTimeAsync(10);
  const again = await far.asked();
  expect(again).not.toBe(socket);
  expect(again).toMatchObject({ sent: [{ op: "subscribe", sub: "w1", query: { limit: 5 } }] });
  again.say({ sub: "w1", q: "q", gen: "h", rev: 1, full: false, reset: [{ path: "/b" }] });
  expect(frames.at(-1)).toEqual({
    type: "reset",
    gen: "h",
    rev: 1,
    q: "q",
    full: false,
    rows: [{ path: "/b" }],
  });
});

test("a watch that starts while the socket is dialled again waits for that dial, and dials none of its own", async () => {
  vi.useFakeTimers();
  onTestFinished(() => void vi.useRealTimers());
  vi.spyOn(console, "info").mockImplementation(() => {});
  const far = catalog();
  const relay = far.relay();
  const first = relay.watch(ticket({ limit: 1 }), () => {});
  const socket = await far.asked();
  socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [] });
  using _first = await first;
  // the socket drops, and the dial that takes its place is slow
  let answerTheDial = () => {};
  far.before = new Promise<void>((resolve) => (answerTheDial = resolve));
  socket.drop();
  await vi.advanceTimersByTimeAsync(10);
  const frames: CatalogFrame<unknown>[] = [];
  const second = relay.watch(ticket({ limit: 2 }), (frame) => frames.push(frame));
  await vi.advanceTimersByTimeAsync(10);
  expect(far).toMatchObject({ dials: 2 });
  answerTheDial();
  await vi.advanceTimersByTimeAsync(200);
  const again = await far.asked(2);
  // one socket for the session: the first watch is asked again on it, and the second asks once
  expect(far).toMatchObject({ dials: 2 });
  expect(again.sent.toSorted((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)))).toEqual(
    [
      { op: "subscribe", sub: "w1", query: { limit: 1 } },
      { op: "subscribe", sub: "w2", query: { limit: 2 } },
    ],
  );
  again.say({ sub: "w2", q: "q", gen: "g", rev: 5, full: false, reset: [{ path: "/a" }] });
  using _second = await second;
  expect(frames).toMatchObject([{ type: "reset", rows: [{ path: "/a" }] }]);
});

test("a socket whose keepalives go unanswered is taken for dead and dialled again", async () => {
  vi.useFakeTimers();
  onTestFinished(() => void vi.useRealTimers());
  vi.spyOn(console, "info").mockImplementation(() => {});
  const far = catalog();
  const relay = far.relay();
  const watching = relay.watch(ticket({ limit: 5 }), () => {});
  const socket = await far.asked();
  socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [] });
  using _watch = await watching;
  // the runtime answers for a catalog that sleeps: the socket stays
  socket.answersKeepalives = true;
  await vi.advanceTimersByTimeAsync(60_000);
  expect(far).toMatchObject({ dials: 1 });
  // a reset with no close: nothing answers any more
  socket.answersKeepalives = false;
  await vi.advanceTimersByTimeAsync(20_100);
  expect(far).toMatchObject({ dials: 2 });
});

test("when the catalog cannot be dialled again, every watch ends and its handle says why", async () => {
  vi.useFakeTimers();
  onTestFinished(() => void vi.useRealTimers());
  const failed = vi.spyOn(console, "error").mockImplementation(() => {});
  const far = catalog();
  const relay = far.relay();
  const watching = relay.watch(ticket({ limit: 5 }), () => {});
  const socket = await far.asked();
  socket.say({ sub: "w1", q: "q", gen: "g", rev: 4, full: false, reset: [] });
  const watch = await watching;
  far.refuses = true;
  socket.drop();
  await vi.advanceTimersByTimeAsync(61_000);
  await expect(watch.ended()).resolves.toMatch(/could not be reached again/);
  expect(failed).toHaveBeenCalledWith(
    expect.objectContaining({ event: "catalog-watch.redial-failed" }),
  );
});

test.for([
  { kind: "query", error: "not a query of the catalog", code: "INVALID_INPUT" },
  {
    kind: "limit",
    error: "the catalog holds at most 512 different live queries",
    code: "WATCH_LIMIT",
  },
  // the catalog's own failure has no code: a watcher reads the catalog in another way
  { kind: "failed", error: "the catalog failed, and its log says why", code: undefined },
])(
  "a refusal of the catalog ($kind) rejects the call with its own code, and leaves no watch and no socket",
  async ({ kind, error, code }) => {
    const far = catalog();
    const relay = far.relay();
    const watching = relay.watch(ticket({ limit: 5 }), () => {});
    const socket = await far.asked();
    socket.say({ sub: "w1", kind, error });
    const refusal = await watching.then(
      () => undefined,
      (thrown: Error & { code?: string }) => thrown,
    );
    expect(refusal).toMatchObject({ message: `contexts.watch: ${error}` });
    expect(refusal?.code).toBe(code);
    expect(socket).toMatchObject({ closed: true });
  },
);

test("a batch ends with the last frame that goes: an entry for a watch that is gone, or is asked again, ends none", async () => {
  const far = catalog();
  const relay = far.relay();
  const batch: [string, boolean][] = [];
  const watches = ["first", "second", "third"].map((name, at) =>
    relay.watch(ticket({ limit: at + 1 }), (frame) => batch.push([name, !!frame.more])),
  );
  const socket = await far.asked(3);
  for (const sub of ["w1", "w2", "w3"])
    socket.say({ sub, q: "q", gen: "g", rev: 1, full: false, reset: [] });
  const [first, second, third] = await Promise.all(watches);
  using _first = first;
  using _second = second;
  batch.length = 0;
  // the third watch is gone when the catalog's message for all three comes
  third![Symbol.dispose]();
  socket.say({
    gen: "g",
    rows: [{ path: "/a" }],
    d: [
      ["w1", 1, 2, [], ["/a"]],
      ["w2", 1, 2, [], ["/a"]],
      ["w3", 1, 2, [], ["/a"]],
    ],
  });
  expect(batch).toEqual([
    ["first", true],
    ["second", false],
  ]);
  // and the second has a gap in the next one: it is asked again, and the first ends the batch
  batch.length = 0;
  socket.say({
    gen: "g",
    rows: [{ path: "/b" }],
    d: [
      ["w1", 2, 3, [], ["/b"]],
      ["w2", 7, 8, [], ["/b"]],
    ],
  });
  expect(batch).toEqual([["first", false]]);
  expect(socket.sent.at(-1)).toEqual({ op: "subscribe", sub: "w2", query: { limit: 2 } });
});

test("the watcher's dispose takes the query off, and the last watch closes the socket", async () => {
  const far = catalog();
  const relay = far.relay();
  const first = relay.watch(ticket({ limit: 1 }), () => {});
  const socket = await far.asked();
  const second = relay.watch(ticket({ limit: 2 }), () => {});
  await far.asked(2);
  for (const sub of ["w1", "w2"])
    socket.say({ sub, q: "q", gen: "g", rev: 1, full: false, reset: [] });
  const [one, two] = await Promise.all([first, second]);
  one[Symbol.dispose]();
  expect(socket.sent.at(-1)).toEqual({ op: "unsubscribe", sub: "w1" });
  expect(socket).toMatchObject({ closed: false });
  await expect(one.ended()).resolves.toBe("the watcher ended it");
  two[Symbol.dispose]();
  expect(socket).toMatchObject({ closed: true });
});

test("the session's end ends every watch, closes the socket, and takes no new watch", async () => {
  const far = catalog();
  const relay = far.relay();
  const watching = relay.watch(ticket({ limit: 5 }), () => {});
  const socket = await far.asked();
  socket.say({ sub: "w1", q: "q", gen: "g", rev: 1, full: false, reset: [] });
  const watch = await watching;
  relay.dispose();
  await expect(watch.ended()).resolves.toBe("the session ended");
  expect(socket).toMatchObject({ closed: true });
  await expect(relay.watch(ticket({ limit: 5 }), () => {})).rejects.toMatchObject({
    code: "UNAVAILABLE",
  });
});

test("loaded code is refused the watch and the list of what is watched, whatever its table lets through", () => {
  for (const call of ["watch", "watches"] as const) {
    expect(() => refuseLoadedCode({ app: true }, call)).toThrow(
      expect.objectContaining({ code: "FORBIDDEN", message: expect.stringContaining(call) }),
    );
    // a member's session, and the platform's own code
    expect(() => refuseLoadedCode({}, call)).not.toThrow();
  }
});

test("a ticket is the query, checked: a callback, a second option or a query the catalog cannot answer is refused", () => {
  expect(catalogWatchTicket({ under: "/agents", order: "path" }, undefined)).toEqual({
    $itxCatalogWatch: { query: { under: "/agents", order: "path" }, cursor: undefined },
  });
  expect(isCatalogWatchTicket(catalogWatchTicket({}, {}))).toBe(true);
  expect(isCatalogWatchTicket([{ path: "/a" }])).toBe(false);
  // a function where the options stand: the call did not come through a session's end
  expect(() => catalogWatchTicket({}, () => {})).toThrow(/a session's call/);
  expect(() => catalogWatchTicket({}, { cursor: {}, more: 1 })).toThrow(/a session's call/);
  expect(() => catalogWatchTicket({ orderBy: "title" }, undefined)).toThrow(/orderBy/);
  expect(() => catalogWatchTicket({ keys: ["/a"], limit: 2 }, undefined)).toThrow(/stands alone/);
});

function ticket(query: Parameters<typeof catalogWatchTicket>[0]) {
  return catalogWatchTicket(query, undefined);
}

/** The catalog's end of a watch socket, written to by hand. */
function catalog() {
  type Listener = (event: { data?: unknown; reason?: string }) => void;
  const sockets: FarSocket[] = [];
  const onSend: (() => void)[] = [];
  class FarSocket {
    sent: unknown[] = [];
    closed = false;
    answersKeepalives = false;
    #listeners: Record<string, Listener[]> = {};
    accept() {}
    send(raw: string) {
      if (this.closed) throw new Error("the socket is closed");
      if (raw === RPC_STUB_PAGER_KEEPALIVE_REQUEST) {
        if (this.answersKeepalives)
          this.#emit("message", { data: RPC_STUB_PAGER_KEEPALIVE_RESPONSE });
        return;
      }
      this.sent.push(JSON.parse(raw));
      onSend.splice(0).forEach((heard) => heard());
    }
    close() {
      this.closed = true;
    }
    addEventListener(type: string, listener: Listener) {
      (this.#listeners[type] ||= []).push(listener);
    }
    #emit(type: string, event: { data?: unknown; reason?: string }) {
      for (const listener of this.#listeners[type] || []) listener(event);
    }
    /** The catalog sends a message. */
    say(message: unknown) {
      this.#emit("message", { data: JSON.stringify(message) });
    }
    /** The catalog's object is gone: the socket closes under the session. */
    drop() {
      this.closed = true;
      this.#emit("close", { reason: "the object was reset" });
    }
  }
  const far = {
    dials: 0,
    refuses: false,
    /** A dial answers when this settles: a catalog that is slow to come back. */
    before: Promise.resolve(),
    /** The newest socket, once the session's end has sent it `count` messages: it listens then. */
    asked: async (count = 1) => {
      for (;;) {
        const socket = sockets.at(-1);
        if (socket && !socket.closed && socket.sent.length >= count) return socket;
        await new Promise<void>((heard) => onSend.push(heard));
      }
    },
    relay: () => {
      const relay = new CatalogWatchRelay({
        dial: async () => {
          far.dials += 1;
          await far.before;
          if (far.refuses) return { status: 503 };
          const socket = new FarSocket();
          sockets.push(socket);
          return { status: 101, webSocket: socket as unknown as WebSocket };
        },
        waitUntil: () => {},
      });
      // its keepalive is a timer: a relay that outlives its test would dial in the next one
      onTestFinished(() => relay.dispose());
      return relay;
    },
  };
  return far;
}