iterate.com / kernel

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

kernel / core / lib / src / cli / daemon.test.tsmain at 949894f

// daemon.test.ts — `iterate daemon` (daemon.ts) and a program's connection to it
// (daemon-client.ts), over real sockets and real capnweb sessions on localhost. The mind is a
// stand-in: a WebSocket server whose root keeps what is lent to it, as a mind's `provide` does.
import { existsSync, mkdtempDisposableSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { newWebSocketRpcSession, RpcTarget, type RpcStub } from "capnweb";
import { expect, test, vi } from "vitest";
import WebSocket, { WebSocketServer } from "ws";
import type { MindConnection, MindItx } from "../node.ts";
import { connectDaemon, readDaemonFile, runningDaemon } from "./daemon-client.ts";
import { startDaemon } from "./daemon.ts";

type Lent = RpcStub<RpcTarget> & {
  deliverEvent(event: { type: string }): Promise<string>;
  files: { read(path: string): Promise<Uint8Array> };
};

/** A mind that keeps the newest lend of each name, and says which of its connections holds it. */
async function standInMind() {
  const lent = new Map<string, { target: Lent; connection: number }>();
  const appended: { path: string; type: string }[] = [];
  const sockets: WebSocket[] = [];
  class Context extends RpcTarget {
    path: string;
    connection: number;
    constructor(path: string, connection: number) {
      super();
      this.path = path;
      this.connection = connection;
    }
    whoami() {
      return { path: this.path };
    }
    cd(path: string) {
      return new Context(path, this.connection);
    }
    append(event: { type: string }) {
      appended.push({ path: this.path, type: event.type });
      return [{ ...event, offset: appended.length, path: this.path }];
    }
    provide(match: string, target: Lent) {
      const mine = { target: target.dup() as Lent, connection: this.connection };
      lent.set(match, mine);
      return new (class extends RpcTarget {
        [Symbol.dispose]() {
          if (lent.get(match) === mine) lent.delete(match);
        }
      })();
    }
  }
  const server = new WebSocketServer({ port: 0, host: "127.0.0.1" });
  await new Promise((resolve) => server.once("listening", resolve));
  server.on("connection", (socket) => {
    sockets.push(socket);
    newWebSocketRpcSession(
      socket as unknown as globalThis.WebSocket,
      new Context("/", sockets.length),
    );
  });
  const { port } = server.address() as { port: number };
  let refuse = "";
  const connect = async (address: string): Promise<MindConnection> => {
    if (refuse) throw new Error(refuse);
    const socket = new WebSocket(`ws://127.0.0.1:${port}`);
    socket.on("error", () => {});
    const closed = new Promise<{ code: number; reason: string }>((resolve) =>
      socket.once("close", (code, reason) => resolve({ code, reason: reason.toString() })),
    );
    const itx = newWebSocketRpcSession(
      socket as unknown as globalThis.WebSocket,
    ) as unknown as MindItx;
    await itx.whoami();
    return { address, itx, closed, [Symbol.dispose]: () => socket.close() };
  };
  return {
    lent,
    appended,
    connect,
    /** how many connections the daemon has made */
    connections: () => sockets.length,
    /** the mind closes the newest connection, as it does when a sign-in ends */
    drop: () => sockets.at(-1)!.close(4000, "the sign-in ended"),
    refuse: (why: string) => (refuse = why),
    [Symbol.dispose]: () => {
      for (const socket of sockets) socket.terminate();
      server.close();
    },
  };
}

const daemonFor = async (
  mind: Awaited<ReturnType<typeof standInMind>>,
  folder: string,
  more: Partial<Parameters<typeof startDaemon>[0]> = {},
) =>
  startDaemon({
    mind: "iterate.example.com",
    connect: mind.connect,
    addressOf: (typed) => typed,
    version: "0.0.0-test",
    file: join(folder, "daemon.json"),
    log: () => {},
    timing: { reconnectMs: 20, retireAfterMs: 20 },
    ...more,
  });

const bridge = {
  deliverEvent: (event: { type: string }) => `delivered ${event.type}`,
  files: { read: (path: string) => new TextEncoder().encode(path) },
};

test("a local program lends a capability to the mind and reaches the mind's itx, both through the daemon's one connection; when the program goes away its lend goes too", async () => {
  using folder = mkdtempDisposableSync(join(tmpdir(), "iterate-daemon-"));
  using mind = await standInMind();
  const daemon = await daemonFor(mind, folder.path);
  const file = join(folder.path, "daemon.json");
  try {
    expect(readDaemonFile(file)).toMatchObject({ pid: process.pid, mind: "iterate.example.com" });
    expect(statSync(file).mode & 0o777).toBe(0o600);

    const program = await connectDaemon({ name: "bridge.codex", file });
    await program.provide("beelink.codex", bridge, { description: "Codex sessions on beelink" });
    // the mind calls what the program lent: a function, and one of a nested object, with bytes
    const lent = mind.lent.get("itx.beelink.codex")!.target;
    expect(await lent.deliverEvent({ type: "message-received" })).toBe(
      "delivered message-received",
    );
    expect(new TextDecoder().decode(await lent.files.read("a.txt"))).toBe("a.txt");
    // the mind's itx, in one pipeline: no connection to the mind of the program's own
    using itx = program.itx();
    using session = itx.cd("/agents/codex/one");
    const [event] = await session.append({ type: "codex/noted" });
    expect(event).toMatchObject({ path: "/agents/codex/one", type: "codex/noted" });
    expect(mind.connections()).toBe(1);
    expect(await program.status()).toMatchObject({
      mind: "iterate.example.com",
      minds: [{ address: "iterate.example.com", state: "connected" }],
      clients: [{ name: "bridge.codex", pid: process.pid }],
      lends: [{ name: "itx.beelink.codex", client: "bridge.codex", live: true }],
    });

    program[Symbol.dispose]();
    await vi.waitFor(() => expect(mind.lent.has("itx.beelink.codex")).toBe(false));
  } finally {
    daemon.stop();
  }
  await daemon.stopped;
  expect(existsSync(file)).toBe(false);
});

test("the daemon's connection to the mind closes: it connects again and lends every name again, and a program does nothing", async () => {
  using folder = mkdtempDisposableSync(join(tmpdir(), "iterate-daemon-"));
  using mind = await standInMind();
  const daemon = await daemonFor(mind, folder.path);
  try {
    using program = await connectDaemon({ file: join(folder.path, "daemon.json") });
    await program.provide("codex", bridge);
    expect(mind.lent.get("itx.codex")!.connection).toBe(1);

    mind.refuse("the network is down");
    mind.drop();
    await vi.waitFor(async () =>
      expect((await program.status()).minds[0]).toMatchObject({
        state: "reconnecting",
        lastFailure: "the network is down",
      }),
    );
    mind.refuse("");
    await vi.waitFor(() => expect(mind.lent.get("itx.codex")!.connection).toBe(2));
    expect(await mind.lent.get("itx.codex")!.target.deliverEvent({ type: "again" })).toBe(
      "delivered again",
    );
    expect(await program.itx().whoami()).toEqual({ path: "/" });
  } finally {
    daemon.stop();
  }
});

test("before a sign-in ends the daemon makes the next connection and lends over it first, so a name is never without a lender", async () => {
  using folder = mkdtempDisposableSync(join(tmpdir(), "iterate-daemon-"));
  using mind = await standInMind();
  let endsAt: number | undefined = Date.now() + 150;
  const daemon = await daemonFor(mind, folder.path, {
    // the first connection's sign-in ends soon; the next one's end is not known
    endsAt: () => {
      const ends = endsAt;
      endsAt = undefined;
      return ends;
    },
    timing: { reconnectMs: 20, renewBeforeMs: 50, retireAfterMs: 20 },
  });
  try {
    using program = await connectDaemon({ file: join(folder.path, "daemon.json") });
    await program.provide("codex", bridge);
    const seen = new Set<number | undefined>();
    await vi.waitFor(() => {
      seen.add(mind.lent.get("itx.codex")?.connection);
      expect(mind.lent.get("itx.codex")!.connection).toBe(2);
    });
    // never unlent on the way from the first connection to the second
    expect(seen.has(undefined)).toBe(false);
    expect((await program.status()).minds[0]!.state).toBe("connected");
    expect(await mind.lent.get("itx.codex")!.target.deliverEvent({ type: "after" })).toBe(
      "delivered after",
    );
  } finally {
    daemon.stop();
  }
});

test("the port alone opens nothing: a wrong token is refused, and so is a browser's page", async () => {
  using folder = mkdtempDisposableSync(join(tmpdir(), "iterate-daemon-"));
  using mind = await standInMind();
  const daemon = await daemonFor(mind, folder.path);
  try {
    const { port } = daemon.file;
    const socket = new WebSocket(`ws://127.0.0.1:${port}/`);
    const api = newWebSocketRpcSession<{ authenticate(token: string): { status(): unknown } }>(
      socket as unknown as globalThis.WebSocket,
    );
    await expect(api.authenticate("a guess").status()).rejects.toThrow(
      "Not the iterate daemon's token",
    );
    socket.close();

    const page = new WebSocket(`ws://127.0.0.1:${port}/`, { origin: "https://example.com" });
    const refused = await new Promise<number | undefined>((resolve) => {
      page.once("unexpected-response", (_request, response) => resolve(response.statusCode));
      page.once("open", () => resolve(undefined));
      page.on("error", () => {});
    });
    expect(refused).toBe(403);
  } finally {
    daemon.stop();
  }
});

test("a file that a dead daemon left is no daemon: its pid may be another process's, so only an answer counts, and a new daemon writes over it", async () => {
  using folder = mkdtempDisposableSync(join(tmpdir(), "iterate-daemon-"));
  using mind = await standInMind();
  const file = join(folder.path, "daemon.json");
  // a port that nothing listens on, and the pid of a process that runs (this test's parent)
  const unused = new WebSocketServer({ port: 0, host: "127.0.0.1" });
  await new Promise((resolve) => unused.once("listening", resolve));
  const { port } = unused.address() as { port: number };
  await new Promise((resolve) => unused.close(resolve));
  writeFileSync(
    file,
    JSON.stringify({
      pid: process.ppid,
      port,
      token: "left-behind",
      mind: "iterate.example.com",
      version: "0.0.0-test",
      startedAt: new Date().toISOString(),
    }),
  );
  expect(await runningDaemon(file)).toBe(null);
  await expect(connectDaemon({ file })).rejects.toThrow("No iterate daemon runs here");

  const daemon = await daemonFor(mind, folder.path);
  try {
    expect(await runningDaemon(file)).toMatchObject({ pid: process.pid, port: daemon.file.port });
  } finally {
    daemon.stop();
  }
});