iterate.com / kernel

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

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

// daemon-client.ts — A LOCAL PROGRAM'S CONNECTION TO `iterate daemon` (daemon.ts): what a bridge, a
// desktop app or a script imports as `connectDaemon` from `iterate/node`. It reads the daemon's
// file for the port and the token, opens one WebSocket to localhost, and talks capnweb. It makes
// no connection to the mind and holds no sign-in.
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { newWebSocketRpcSession, RpcTarget, type RpcStub } from "capnweb";
import WebSocket from "ws";
import { z } from "zod";
import type { MindItx } from "../node.ts";
import { withTimeout } from "../lib.ts";
import { CONFIG_DIR } from "./config.ts";
import type { DaemonApi, DaemonSessionApi, DaemonStatus } from "./daemon.ts";
import { rpcTargetOf } from "./provide.ts";

/** Where a daemon says how to reach it, for as long as it runs. */
export const DAEMON_FILE = join(CONFIG_DIR, "daemon.json");

/** `daemon.json`: written once the server listens, removed when the daemon ends. */
export const DaemonFile = z.object({
  pid: z.number().int(),
  port: z.number().int(),
  /** what `authenticate` takes: 32 random bytes, new at each start */
  token: z.string(),
  /** the mind that a call names none for */
  mind: z.string(),
  version: z.string(),
  startedAt: z.string(),
});
export type DaemonFile = z.infer<typeof DaemonFile>;

/** The file of a daemon, or null when there is none or it does not parse (a stale one's). */
export function readDaemonFile(path = DAEMON_FILE): DaemonFile | null {
  if (!existsSync(path)) return null;
  try {
    return DaemonFile.parse(JSON.parse(readFileSync(path, "utf8")));
  } catch {
    return null;
  }
}

/** THE DAEMON THAT ANSWERS NOW, as its file says it, or null. Only an answer counts: a file
 *  outlives a daemon that crashed, and its pid may by then be another process's, so nothing
 *  is ever told from the pid, and no signal is sent to it, before the daemon has answered with it. */
export async function runningDaemon(path = DAEMON_FILE): Promise<DaemonFile | null> {
  const file = readDaemonFile(path);
  if (!file) return null;
  try {
    using daemon = await connectDaemon({ name: "iterate daemon", file: path });
    return (await daemon.status()).pid === file.pid ? file : null;
  } catch {
    return null;
  }
}

export type DaemonConnection = Disposable & {
  status(): Promise<DaemonStatus>;
  /** THE MIND'S ROOT CONTEXT over the daemon's connection (`mind`: another mind than the
   *  daemon's own). Ask for it at each use and dispose of it after (`using`): the calls on it
   *  go with the call that asks for it, so a use costs one round trip to the daemon. A copy
   *  that is kept ends when the daemon replaces its connection to the mind, about once an
   *  hour, and one that is never disposed of is held at the daemon until this program goes. */
  itx(mind?: string): MindItx;
  /** LEND `provided` TO THE MIND as `itx.<name>` until the answer is disposed of or this
   *  connection closes: a plain object of functions (wrapped as `iterate provide` wraps a file's,
   *  provide.ts `rpcTargetOf`) or an `RpcTarget` of this package's capnweb. The daemon lends it
   *  again over each connection it makes to the mind, so the program does nothing at a reconnect
   *  of the daemon's. After this connection closes, connect and provide again. */
  provide(
    name: string,
    provided: object,
    options?: { description?: string; mind?: string },
  ): Promise<Disposable>;
  /** resolves when the socket to the daemon has closed */
  closed: Promise<{ code: number; reason: string }>;
};

/** CONNECT TO THE DAEMON OF THIS COMPUTER'S USER. It fails with the command that starts one when
 *  none runs. `name` is what `iterate daemon status` shows for this program. */
export async function connectDaemon(
  input: { name?: string; file?: string } = {},
): Promise<DaemonConnection> {
  const path = input.file || DAEMON_FILE;
  const file = readDaemonFile(path);
  const none = `No iterate daemon runs here (${path}). Start one: iterate daemon start.`;
  if (!file) throw new Error(none);
  const socket = new WebSocket(`ws://127.0.0.1:${file.port}/`, { handshakeTimeout: 5_000 });
  const closed = new Promise<{ code: number; reason: string }>((resolve) => {
    socket.once("close", (code, reason) => resolve({ code, reason: reason.toString() }));
  });
  // The transport surfaces failures through RPC and `closed`; ws also emits an EventEmitter error.
  socket.on("error", () => {});
  // ws implements the DOM event/send/close interface consumed by capnweb.
  const api = newWebSocketRpcSession<DaemonApi>(socket as unknown as globalThis.WebSocket);
  // `authenticate` is never awaited: the calls on its answer go with it (connected-mind.ts)
  const session: RpcStub<DaemonSessionApi> = (() => {
    using promise = api.authenticate(file.token, {
      name: input.name || process.title,
      pid: process.pid,
    });
    return promise.dup() as unknown as RpcStub<DaemonSessionApi>;
  })();
  try {
    // the first call proves the socket and the token; a port that something else took never answers
    await withTimeout(Promise.resolve(session.status()), 5_000, "The iterate daemon's answer");
  } catch (error) {
    socket.terminate();
    const why = error instanceof Error ? error.message : String(error);
    // nothing listens on the file's port: its daemon is gone
    if (/ECONNREFUSED|closed|WebSocket/i.test(why)) throw new Error(none, { cause: error });
    throw new Error(`Could not connect to the iterate daemon on port ${file.port}: ${why}`, {
      cause: error,
    });
  }
  return {
    status: async () => await session.status(),
    // the promise's stub: a call on it is sent with this one, and `await` of it gives the stub
    itx: (mind) => session.itx(mind) as unknown as MindItx,
    provide: async (name, provided, options) => {
      const target = provided instanceof RpcTarget ? provided : rpcTargetOf(provided);
      // the daemon's handle of the lend: disposing of it ends the lend
      return (await session.provide(
        name,
        target as unknown as RpcStub<RpcTarget>,
        options,
      )) as unknown as Disposable;
    },
    closed,
    [Symbol.dispose]() {
      try {
        session[Symbol.dispose]();
        api[Symbol.dispose]();
      } finally {
        socket.close();
      }
    },
  };
}