iterate.com / kernel

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

kernel / core / lib / src / cli / provide.tsmain at 949894f

// provide.ts — `iterate provide <file>`: a local file's functions lent to the mind as
// `itx.<name>` (core-itx iterate-context.ts `provide`) until Ctrl-C, lent again over each new
// connection. A bridge on another machine (a WhatsApp session, a terminal manager) is one such file.
import { existsSync } from "node:fs";
import { basename, dirname, extname, join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { RpcTarget } from "capnweb";
import type { MindConnection } from "../node.ts";
import { ProvideRefusal, type ProvideState } from "./provide-state.ts";

/** What `iterate provide` reads from a file: its default export, called on every connection with
 *  that connection's mind, answers the object whose functions are lent; `description`, when
 *  exported, is the one line a model reads for the name. With `--key` the connection is the key's:
 *  `itx` lends and does nothing else, and `append` adds an event as the key (bridge-key.ts). */
export type ProvidedFile = {
  provide: (input: { itx: unknown; append?: BridgeAppend }) => unknown;
  description?: string;
};

type BridgeAppend = (
  path: string,
  event: { type: string; payload?: Record<string, unknown> },
) => Promise<void>;

/** A capability's name: `itx.<name>`, dotted segments allowed (`whatsapp.jonas`). */
const NAME = /^[a-zA-Z][a-zA-Z0-9]*(\.[a-zA-Z][a-zA-Z0-9]*)*$/;

/** THE FILE, IMPORTED BY NODE ITSELF: `.ts`, `.mts`, `.mjs` and `.js` alike (Node strips a `.ts`
 *  file's types, 22.18 and later). Its bare imports resolve from its own folder's `node_modules`, so
 *  its dependencies are that folder's to install, never this CLI's: a missing one names the folder
 *  to install in. Importing it runs its top level once, for the whole process. */
export async function importProvidedFile(file: string): Promise<ProvidedFile> {
  const path = resolve(file);
  if (!existsSync(path)) throw new Error(`No file ${path}.`);
  let imported: { default?: unknown; description?: unknown };
  try {
    imported = await import(pathToFileURL(path).href);
  } catch (error) {
    // Node's module errors are Errors with a `code`; anything else reads as neither and is rethrown
    const { code, message } = error as { code?: string; message?: string };
    if (code === "ERR_MODULE_NOT_FOUND" && message?.startsWith("Cannot find package")) {
      const packageDirectory = nearestPackageDirectory(path);
      throw new Error(
        packageDirectory
          ? `${message}. Install ${basename(path)}'s dependencies first: npm install (or pnpm install) in ${packageDirectory}.`
          : `${message}. ${basename(path)} has no package.json above it: make one in ${dirname(path)} that lists its dependencies, then npm install there.`,
      );
    }
    if (code === "ERR_UNKNOWN_FILE_EXTENSION")
      throw new Error(
        `${message}. Node ${process.version} cannot load ${extname(path)} files: Node 26 or later strips a TypeScript file's types itself.`,
      );
    throw error;
  }
  if (typeof imported.default !== "function")
    throw new Error(
      `${basename(path)} has no default export to provide: export default function ({ itx }) { return { someFunction() {} } }`,
    );
  return {
    // a function, checked above; what it answers is checked when it is called (rpcTargetOf)
    provide: imported.default as ProvidedFile["provide"],
    description: typeof imported.description === "string" ? imported.description : undefined,
  };
}

/** `whatsapp.ts` → `whatsapp`: the default name, when the file's name is one. */
export function nameOfFile(file: string): string {
  const name = basename(file, extname(file));
  if (!NAME.test(name))
    throw new Error(
      `${basename(file)} is not a capability name: pass --name, letters and digits starting with a letter (e.g. --name whatsapp).`,
    );
  return name;
}

const isPlainObject = (value: unknown): value is Record<string, unknown> =>
  value instanceof Object && Object.getPrototypeOf(value) === Object.prototype;

/** THE LENT STUB: the functions of `provided` as the methods of one RpcTarget of THIS process's
 *  capnweb. capnweb lends only instances of its own `RpcTarget`, and in Node that is a class of each
 *  installed copy: an RpcTarget from the file's own copy of capnweb would not be one here, so the
 *  file answers plain functions and this wraps them. Which functions is capnweb's own rule: a plain
 *  object's own properties, a class instance's methods (never its fields). A plain object of
 *  functions is lent as a member of its own (`files.read`), to any depth. Arguments and answers
 *  cross as they are (plain data, bytes, streams, stubs); anything else fails the call. */
export function rpcTargetOf(provided: unknown): RpcTarget {
  if (typeof provided !== "object" || !provided)
    throw new Error(
      `The default export answered ${String(provided)}: it must answer an object of functions.`,
    );
  // an object, checked above: its properties are read by name, each checked as it is lent
  const target = lend(provided as Record<string, unknown>);
  if (!target)
    throw new Error("The default export answered an object with no functions: nothing to lend.");
  return target;
}

/** `object`'s functions and its plain objects of functions as one RpcTarget; null when it has none. */
function lend(object: Record<string, unknown>): RpcTarget | null {
  const prototype = Object.getPrototypeOf(object);
  const layers: object[] = [];
  if (prototype === Object.prototype || prototype === null) layers.push(object);
  else
    for (
      let layer = prototype;
      layer && layer !== Object.prototype;
      layer = Object.getPrototypeOf(layer)
    )
      layers.push(layer);
  class Provided extends RpcTarget {}
  let lent = 0;
  for (const layer of layers)
    for (const name of Object.getOwnPropertyNames(layer)) {
      const member = object[name];
      if (name === "constructor" || Object.hasOwn(Provided.prototype, name)) continue;
      if (typeof member === "function") {
        lent += 1;
        Object.defineProperty(Provided.prototype, name, {
          // `member` is a function, checked above; `this` stays the provided object
          value: (...args: unknown[]) =>
            (member as (...args: unknown[]) => unknown).apply(object, args),
        });
      } else if (isPlainObject(member)) {
        const nested = lend(member);
        if (!nested) continue;
        lent += 1;
        Object.defineProperty(Provided.prototype, name, { get: () => nested });
      }
    }
  return lent > 0 ? new Provided() : null;
}

/** How long `provide` waits before each attempt to reconnect after its connection closed, about
 *  five minutes in all, as `iterate tunnel` does: long enough for Wi-Fi to come back or a laptop to
 *  wake, short enough that a lend whose network is gone for good says so and exits. */
const RECONNECT_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000, ...Array(9).fill(30_000)];

/** `iterate provide <file>`: lend the file's functions to the mind as `itx.<name>` until Ctrl-C.
 *  On every connection — the first, and each one `reconnect` opens after one closes or the lend
 *  ends under it — the file's default export is called with that connection's root as `itx`,
 *  and what it answers is lent again at the same name: the file keeps its long-lived state (a
 *  socket, a session) in its own module scope and reaches the mind through the newest `itx`.
 *  `itx.<name>` is printed on stdout once live (with `report`, the states instead: --json). Only
 *  when every attempt to reconnect fails, or the mind refuses the key (`ProvideRefusal`), does it
 *  end, with an error. A connection whose sign-in is about to end is replaced before it does (THE
 *  HANDOVER, below), so the hourly end of a token costs no call. */
export async function runProvide(input: {
  connection: MindConnection;
  reconnect: () => Promise<MindConnection>;
  file: ProvidedFile;
  name: string;
  /** with `--key`: how the file adds an event, since its `itx` only lends */
  append?: BridgeAppend;
  /** the reconnect schedule — a test's, `RECONNECT_DELAYS_MS` otherwise */
  reconnectDelaysMs?: readonly number[];
  /** When the sign-in of the connection made last ends, as epoch ms, asked right after each one
   *  is made. None: not known, and the name is lent until the connection closes. */
  endsAt?: () => number | undefined;
  /** how long before that end the next connection is made — a test's, `renewBeforeMs` otherwise */
  renewBeforeMs?: number;
  /** `--json`: each change of state (provide-state.ts); the human lines go to stderr regardless */
  report?: (state: ProvideState) => void;
}): Promise<void> {
  if (!NAME.test(input.name))
    throw new Error(
      `${JSON.stringify(input.name)} is not a capability name: letters and digits starting with a letter, dotted segments allowed (whatsapp, whatsapp.jonas).`,
    );
  const match = `itx.${input.name}`;
  /** how the mind calls the lend, known once the first is live */
  let spelled = match;
  let stop = () => {};
  const stopped = new Promise<"stopped">((resolve) => (stop = () => resolve("stopped")));
  process.once("SIGINT", stop);
  process.once("SIGTERM", stop);
  /** Lend over one connection. `ended` says why it is no longer lent there: the connection closed,
   *  or the lend ended. Lending the name again over a newer connection ends this lend too, at the
   *  mind: the newest lend of a name wins, and a call on its way is sent to it. */
  const lendOver = async (connection: MindConnection, how: "first" | "again" | "renewed") => {
    const mind = connection.itx;
    const target = rpcTargetOf(await input.file.provide({ itx: mind, append: input.append }));
    const lend = await mind.provide(
      match,
      target,
      input.file.description ? { description: input.file.description } : undefined,
    );
    if (how === "first") {
      // A session's root is `/` for a member, and a sandbox's own context for code in a sandbox:
      // the lend sits there, and the mind calls it through that context.
      const { path } = await mind.whoami();
      spelled = path === "/" ? match : `itx.cd(${JSON.stringify(path)}).${input.name}`;
      // with --json stdout is the states' alone: the name is the live state's
      if (!input.report) console.log(spelled);
      console.error(`${spelled} is live for ${connection.address}. Press Ctrl-C to stop.`);
      input.report?.({ state: "live", mind: connection.address, name: spelled, again: false });
    } else if (how === "again") {
      console.error(`Reconnected: ${match} is live again.`);
      input.report?.({ state: "live", mind: connection.address, name: spelled, again: true });
    }
    const lendEnded = lend.lendEnded().then(
      (reason) => `its lend ended: the stub ${reason}`,
      (error: unknown) => `its lend ended: ${messageOf(error)}`,
    );
    const connectionClosed = connection.closed.then(
      ({ code, reason }) => `${code}: ${reason || "connection closed"}`,
    );
    return {
      connection,
      ended: Promise.race([lendEnded, connectionClosed]),
      /** when this connection's sign-in ends, read as it was made */
      endsAt: input.endsAt?.(),
      [Symbol.dispose]() {
        try {
          lend[Symbol.dispose]();
        } finally {
          connection[Symbol.dispose]();
        }
      },
    };
  };
  /** Resolves `what` after `ms`, or "stopped" at Ctrl-C; the timer never outlives the wait. */
  const after = async <What extends string>(ms: number, what: What) => {
    let timer: ReturnType<typeof setTimeout> | undefined;
    const waited = await Promise.race([
      stopped,
      new Promise<What>((resolve) => (timer = setTimeout(() => resolve(what), ms))),
    ]);
    clearTimeout(timer);
    return waited;
  };
  const delaysMs = input.reconnectDelaysMs || RECONNECT_DELAYS_MS;
  // the first connection's refusal is the answer
  let live: Awaited<ReturnType<typeof lendOver>> | null;
  try {
    live = await lendOver(input.connection, "first");
  } catch (error) {
    input.connection[Symbol.dispose]();
    process.removeListener("SIGINT", stop);
    process.removeListener("SIGTERM", stop);
    throw error;
  }
  let lastFailure = "";
  try {
    for (let failures = 0; ;) {
      if (live) {
        // THE HANDOVER: a sign-in's token ends on the hour, and the mind closes its connection
        // then. A while before that the next connection is made and the name lent over it, so the
        // name is never without a lender. When the next one cannot be made, this one is kept until
        // it closes, and the reconnect below takes over as it always did.
        const renewInMs =
          live.endsAt === undefined
            ? undefined
            : live.endsAt - Date.now() - (input.renewBeforeMs ?? renewBeforeMs());
        const outcome: string = await Promise.race([
          live.ended,
          stopped,
          ...(renewInMs === undefined ? [] : [after(Math.max(renewInMs, 0), "renew")]),
        ]);
        if (outcome === "stopped") return;
        if (outcome === "renew") {
          const next = await (async () => {
            const connection = await input.reconnect();
            try {
              return await lendOver(connection, "renewed");
            } catch (error) {
              connection[Symbol.dispose]();
              throw error;
            }
          })().catch((error: unknown) => {
            console.error(`Could not renew ${match} before its sign-in ends: ${messageOf(error)}`);
            return null;
          });
          if (next) {
            // the name is lent over the next connection now: this one's end is no disconnection
            live[Symbol.dispose]();
            live = next;
          } else live.endsAt = undefined; // kept until it closes, with no second try to renew
          continue;
        }
        lastFailure = outcome;
        console.error(`${match} disconnected (${lastFailure}). Reconnecting...`);
        live[Symbol.dispose]();
        live = null;
        failures = 0; // it was lent: a fresh round of attempts
      }
      const delayMs = delaysMs[failures++];
      if (delayMs === undefined)
        throw new Error(
          `${match} disconnected and could not reconnect (${lastFailure}). Run iterate provide again.`,
        );
      input.report?.({
        state: "reconnecting",
        attempt: failures,
        of: delaysMs.length,
        inMs: delayMs,
        lastFailure,
      });
      if ((await after(delayMs, "waited")) === "stopped") return;
      const connection = await input.reconnect().catch((error: unknown) => {
        // the mind's own answer about the key or the protocol: another try changes nothing
        if (error instanceof ProvideRefusal) throw error;
        lastFailure = messageOf(error);
        console.error(`Could not reconnect: ${lastFailure}`);
        return null;
      });
      if (!connection) continue;
      try {
        live = await lendOver(connection, "again");
      } catch (error) {
        connection[Symbol.dispose]();
        lastFailure = messageOf(error);
        console.error(`Could not lend ${match} again: ${lastFailure}`);
      }
    }
  } finally {
    live?.[Symbol.dispose]();
    process.removeListener("SIGINT", stop);
    process.removeListener("SIGTERM", stop);
  }
}

/** How long before a sign-in's end the next connection is made: 20 to 55 seconds, by chance. Under
 *  a minute, so that a stored sign-in counts as ending and is refreshed (node.ts `mindToken`). By
 *  chance, because bridges that share one stored sign-in end at the same moment: the first to renew
 *  refreshes it, and the others find it fresh. Two that renew in the same moment take turns
 *  (config.ts `withSessionsLock`). */
const renewBeforeMs = () => 20_000 + Math.floor(Math.random() * 35_000);

/** The folder of the nearest package.json at or above the file's own folder. */
function nearestPackageDirectory(path: string): string | null {
  for (let directory = dirname(path); ; directory = dirname(directory)) {
    if (existsSync(join(directory, "package.json"))) return directory;
    if (dirname(directory) === directory) return null;
  }
}

function messageOf(error: unknown): string {
  return error instanceof Error ? error.message : String(error);
}