readJob

tcmts.cli.mcp.readJob · #elcqa5jc · term · runs on the server

uses node:path

A job in dir as it is now, or undefined if it has no record there.

import { plain, processAlive } from "#codebase/tcmts/cli/mcp";
import type { Job, JobEnd, JobState } from "#codebase/tcmts/cli/mcp";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

export function readJob(dir: string, id: number): JobState | undefined {
  const file = (ext: string) => path.join(dir, `${id}.${ext}`);
  let job: Job;
  try {
    job = JSON.parse(fs.readFileSync(file("json"), "utf8")) as Job;
  } catch {
    return undefined;
  }
  const ended = (): JobEnd | undefined => {
    try {
      return JSON.parse(fs.readFileSync(file("exit"), "utf8")) as JobEnd;
    } catch {
      return undefined;
    }
  };
  let done = ended();
  // (its end looked for again once its process is known to be gone: it may have ended meanwhile; and one started
  // before the machine was, its process id another's now, is gone too)
  const booted = Date.now() - os.uptime() * 1000;
  const lost = !done && (job.started < booted || !processAlive(job.pid)) && !(done = ended());
  let out = "";
  try {
    out = plain(fs.readFileSync(file("log"), "utf8"));
  } catch {}
  return {
    ...job,
    id,
    log: file("log"),
    out,
    ...(done ? { done } : {}),
    ...(lost ? { lost } : {}),
  };
}

uses

used by