sayRunning

tcmts.cli.running.sayRunning · #zwmmkxda · term · runs on the server

uses node:path

Say this process is running on the codebase in root (written whole: a file beside it, renamed over it), its record taken away as it exits. A process stopped by a signal its handlers don't see leaves its record, which the next reader clears away (liveRunning).

import { runDir } from "#codebase/tcmts/cli/running";
import type { Running } from "#codebase/tcmts/cli/running";
import { randomBytes } from "node:crypto";
import fs from "node:fs";
import path from "node:path";

export function sayRunning(
  root: string,
  r: { command: string; app?: string; url?: string; branch?: string },
): void {
  const dir = runDir(root);
  const file = path.join(dir, `${process.pid}.json`);
  fs.mkdirSync(dir, { recursive: true });
  const record: Running = {
    pid: process.pid,
    command: r.command,
    ...(r.app ? { app: r.app } : {}),
    ...(r.url ? { url: r.url } : {}),
    ...(r.branch ? { branch: r.branch } : {}),
    started: Math.round(Date.now() - process.uptime() * 1000),
    parent: process.ppid,
    args: process.argv.slice(2),
  };
  const part = `${file}.${randomBytes(4).toString("hex")}.part`;
  fs.writeFileSync(part, JSON.stringify(record));
  fs.renameSync(part, file);
  process.once("exit", () => fs.rmSync(file, { force: true }));
}

uses

used by