示例工程 41-sidecar-child-process

41-sidecar-child-process/app/main/index.ts

typescript · 17 KB

import {
  app,
  BrowserWindow,
  ipcMain,
  utilityProcess,
  type UtilityProcess,
} from "electron";
import { spawn, type ChildProcess } from "node:child_process";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import {
  assertJobReq,
  assertModeReq,
  CH,
  type EventRow,
  type JobResult,
  type Mode,
  type Snapshot,
  type Transport,
} from "../shared/ipc";

app.setName("Sidecar Lab");

const isSmoke =
  process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
const tempData =
  isSmoke || isShots
    ? path.join(
        os.tmpdir(),
        `sidecar-${isSmoke ? "smoke" : "shots"}-${process.pid}`,
      )
    : "";
if (tempData) app.setPath("userData", tempData);

const MAX_RESTARTS = 3;
const BASE_DELAY = 500;
const MAX_DELAY = 4000;

let win: BrowserWindow | null = null;
let proc: UtilityProcess | ChildProcess | null = null;
let mode: Mode = "utility";
let transport: Transport = "message";
let pid = 0;
let startedAt = 0;
let restarts = 0;
let nextRestartAt = 0;
let heartbeat = 0;
let manualStop = false;
let error = "";
let lastExit: Snapshot["process"]["lastExit"] = null;
let lastJob: JobResult | null = null;
const byMode: { utility: JobResult | null; child: JobResult | null } = {
  utility: null,
  child: null,
};
let logs: string[] = [];
let events: EventRow[] = [];
let seq = 0;
let restartTimer: NodeJS.Timeout | null = null;
let readyResolve: (() => void) | null = null;
let readyReject: ((reason: Error) => void) | null = null;
let readyTimer: NodeJS.Timeout | null = null;
let stdoutBuffer = "";
const pending = new Map<
  number,
  {
    resolve: (value: Record<string, unknown>) => void;
    reject: (reason: Error) => void;
    timer: NodeJS.Timeout;
  }
>();

function sidecarPath(): string {
  return app.isPackaged
    ? path.join(process.resourcesPath, "sidecar", "worker.cjs")
    : path.join(app.getAppPath(), "sidecar", "worker.cjs");
}

function log(kind: string, detail: string): void {
  events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40);
  broadcast();
}

function addLog(line: string): void {
  const clean = line.length > 300 ? `${line.slice(0, 300)}…` : line;
  logs = [clean, ...logs].slice(0, 40);
}

function broadcast(): void {
  if (win && !win.isDestroyed()) {
    win.webContents.send("sidecar:event", { at: Date.now() });
  }
}

function messageOf(value: unknown): string {
  return typeof value === "string" ? value : JSON.stringify(value);
}

function handleMessage(raw: unknown): void {
  if (typeof raw !== "object" || raw === null) {
    addLog(messageOf(raw));
    return;
  }
  const message = raw as Record<string, unknown>;
  addLog(JSON.stringify(message));
  if (message.type === "ready") {
    pid = Number(message.pid ?? 0);
    transport = message.transport === "stdio" ? "stdio" : "message";
    if (readyTimer) clearTimeout(readyTimer);
    readyTimer = null;
    readyResolve?.();
    readyResolve = null;
    log("ready", `${mode} · pid ${pid} · ${transport}`);
    return;
  }
  if (message.type === "heartbeat") {
    heartbeat = Number(message.seq ?? heartbeat + 1);
    broadcast();
    return;
  }
  if (typeof message.id === "number") {
    const entry = pending.get(message.id);
    if (entry) {
      clearTimeout(entry.timer);
      pending.delete(message.id);
      if (message.type === "error") {
        entry.reject(new Error(String(message.message ?? "SIDECAR_ERROR")));
      } else {
        entry.resolve(message);
      }
    }
  }
}

function handleStdout(chunk: string): void {
  stdoutBuffer += chunk;
  while (true) {
    const index = stdoutBuffer.indexOf("\n");
    if (index === -1) break;
    const line = stdoutBuffer.slice(0, index).trim();
    stdoutBuffer = stdoutBuffer.slice(index + 1);
    if (!line) continue;
    try {
      handleMessage(JSON.parse(line));
    } catch (caught) {
      addLog(`BAD_JSON:${line.slice(0, 120)}`);
      log("protocol", `无法解析 NDJSON:${messageOf(caught)}`);
    }
  }
}

function onExit(
  source: UtilityProcess | ChildProcess,
  code: number | null,
  signal: string,
  reason: string,
): void {
  if (source !== proc) {
    log("exit", `旧进程已退出(${reason})`);
    return;
  }
  proc = null;
  const wasManual = manualStop;
  lastExit = { code, signal, reason, at: Date.now() };
  for (const [, entry] of pending) {
    clearTimeout(entry.timer);
    entry.reject(new Error("PROCESS_EXITED"));
  }
  pending.clear();
  if (wasManual) {
    log("stop", `进程已停止 · code ${code ?? "null"} · ${signal || "none"}`);
    broadcast();
    return;
  }
  log("exit", `意外退出 · code ${code ?? "null"} · ${signal || "none"}`);
  if (restarts >= MAX_RESTARTS) {
    error = "RESTART_LIMIT";
    log("restart", `达到最大重启次数 ${MAX_RESTARTS}`);
    broadcast();
    return;
  }
  restarts += 1;
  const delay = Math.min(BASE_DELAY * 2 ** (restarts - 1), MAX_DELAY);
  nextRestartAt = Date.now() + delay;
  log("restart", `第 ${restarts} 次重启,等待 ${delay}ms`);
  restartTimer = setTimeout(() => {
    restartTimer = null;
    nextRestartAt = 0;
    void start(mode, true).catch((caught) => {
      error = messageOf(caught);
      log("restart-error", error);
    });
  }, delay);
}

async function waitForExit(
  source: UtilityProcess | ChildProcess,
): Promise<void> {
  await new Promise<void>((resolve) => {
    let settled = false;
    const finish = (): void => {
      if (settled) return;
      settled = true;
      resolve();
    };
    if (mode === "utility") {
      (source as UtilityProcess).once("exit", finish);
    } else {
      (source as ChildProcess).once("exit", finish);
    }
    setTimeout(finish, 1500);
  });
}

async function stop(silent = false): Promise<void> {
  manualStop = true;
  if (restartTimer) {
    clearTimeout(restartTimer);
    restartTimer = null;
  }
  nextRestartAt = 0;
  const source = proc;
  if (!source) {
    if (!silent) log("stop", "当前没有运行中的 sidecar");
    broadcast();
    return;
  }
  proc = null;
  if (mode === "utility") {
    (source as UtilityProcess).kill();
  } else {
    (source as ChildProcess).kill("SIGTERM");
  }
  await waitForExit(source);
  if (mode === "child" && (source as ChildProcess).exitCode === null) {
    (source as ChildProcess).kill("SIGKILL");
  }
  lastExit = {
    code: mode === "child" ? (source as ChildProcess).exitCode : null,
    signal: "SIGTERM",
    reason: "manual",
    at: Date.now(),
  };
  if (!silent) log("stop", "已发送停止信号");
  broadcast();
}

function failReady(reason: string): void {
  if (readyTimer) clearTimeout(readyTimer);
  readyTimer = null;
  error = reason;
  readyReject?.(new Error(reason));
  readyResolve = null;
  readyReject = null;
}

function waitReady(): Promise<void> {
  return new Promise<void>((resolve, reject) => {
    readyResolve = resolve;
    readyReject = reject;
    readyTimer = setTimeout(() => failReady("READY_TIMEOUT"), 5000);
  });
}

function spawnUtility(): void {
  const child = utilityProcess.fork(sidecarPath(), [], {
    stdio: "pipe",
    serviceName: "sidecar",
  });
  proc = child;
  pid = child.pid ?? 0;
  transport = "message";
  child.on("message", (message) => handleMessage(message));
  child.stdout?.on("data", (chunk: Buffer) => handleStdout(chunk.toString()));
  child.stderr?.on("data", (chunk: Buffer) => {
    addLog(`stderr:${chunk.toString().slice(0, 200)}`);
  });
  child.on("exit", (code) => onExit(child, code, "", "utility"));
}

function spawnChild(): void {
  const child = spawn(process.execPath, [sidecarPath()], {
    env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
    stdio: ["pipe", "pipe", "pipe"],
    windowsHide: true,
  });
  proc = child;
  pid = child.pid ?? 0;
  transport = "stdio";
  stdoutBuffer = "";
  child.stdout?.on("data", (chunk: Buffer) => handleStdout(chunk.toString()));
  child.stderr?.on("data", (chunk: Buffer) => {
    addLog(`stderr:${chunk.toString().slice(0, 200)}`);
  });
  child.on("exit", (code, signal) =>
    onExit(child, code, signal ?? "", "child"),
  );
  child.on("error", (caught) => failReady(messageOf(caught)));
}

async function start(nextMode: Mode, restarting = false): Promise<void> {
  if (proc) await stop(true);
  mode = nextMode;
  manualStop = false;
  error = "";
  heartbeat = 0;
  stdoutBuffer = "";
  if (!restarting) restarts = 0;
  startedAt = Date.now();
  const ready = waitReady();
  if (nextMode === "utility") spawnUtility();
  else spawnChild();
  log("start", `${nextMode} · ${restarting ? "重启" : "手动启动"}`);
  try {
    await ready;
  } catch (caught) {
    await stop(true);
    throw caught;
  }
  broadcast();
}

function send(
  payload: Record<string, unknown>,
): Promise<Record<string, unknown>> {
  if (!proc) return Promise.reject(new Error("SIDECAR_NOT_RUNNING"));
  const id = ++seq;
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      pending.delete(id);
      reject(new Error("REQUEST_TIMEOUT"));
    }, 5000);
    pending.set(id, { resolve, reject, timer });
    const message = { id, ...payload };
    if (mode === "utility") {
      (proc as UtilityProcess).postMessage(message);
    } else {
      (proc as ChildProcess).stdin?.write(`${JSON.stringify(message)}\n`);
    }
  });
}

function sendRaw(payload: Record<string, unknown>): void {
  if (!proc) throw new Error("SIDECAR_NOT_RUNNING");
  if (mode === "utility") {
    (proc as UtilityProcess).postMessage(payload);
  } else {
    (proc as ChildProcess).stdin?.write(`${JSON.stringify(payload)}\n`);
  }
}

async function runJob(n: number): Promise<JobResult> {
  const response = await send({ type: "job", n });
  if (response.type !== "result") {
    throw new Error("BAD_JOB_RESPONSE");
  }
  const result: JobResult = {
    mode,
    n,
    result: Number(response.result ?? 0),
    ms: Number(response.ms ?? 0),
    pid,
    at: Date.now(),
  };
  lastJob = result;
  byMode[mode] = result;
  log("job", `${mode} · n=${n} → ${result.result} · ${result.ms}ms`);
  return result;
}

function snapshot(): Snapshot {
  return {
    process: {
      running: proc !== null,
      mode,
      transport,
      pid,
      mainPid: process.pid,
      startedAt,
      uptimeMs: proc ? Date.now() - startedAt : 0,
      restarts,
      nextRestartInMs: nextRestartAt
        ? Math.max(0, nextRestartAt - Date.now())
        : 0,
      heartbeat,
      lastExit,
      error,
    },
    lastJob,
    byMode,
    logs: [...logs],
    policy: {
      maxRestarts: MAX_RESTARTS,
      baseDelay: BASE_DELAY,
      maxDelay: MAX_DELAY,
    },
    events: events.map((row) => ({ ...row })),
  };
}

function resolvePreload(): string {
  const candidates = [
    path.join(__dirname, "preload.cjs"),
    path.join(__dirname, "../preload/index.cjs"),
    path.join(__dirname, "preload.js"),
  ];
  return (
    candidates.find((candidate) => fsSync.existsSync(candidate)) ??
    candidates[0] ??
    ""
  );
}

function createWindow(): BrowserWindow {
  const window = new BrowserWindow({
    width: 1100,
    height: 860,
    show: false,
    title: "Sidecar 进程实验室",
    backgroundColor: "#ffffff",
    webPreferences: {
      preload: resolvePreload(),
      contextIsolation: true,
      sandbox: true,
      nodeIntegration: false,
      webSecurity: true,
      allowRunningInsecureContent: false,
      experimentalFeatures: false,
      webviewTag: false,
      spellcheck: false,
      backgroundThrottling: true,
    },
  });
  window.once("ready-to-show", () => window.show());
  window.webContents.once("did-finish-load", () => {
    if (!window.isDestroyed() && !window.isVisible()) window.show();
    log("ready", "Sidecar 实验室已加载");
  });
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    void window.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
  } else {
    void window.loadFile(
      path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
    );
  }
  win = window;
  return window;
}

function delay(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function evalRenderer<T>(
  window: BrowserWindow,
  code: string,
): Promise<T> {
  let lastError: unknown = null;
  for (let attempt = 0; attempt < 3; attempt += 1) {
    try {
      return (await window.webContents.executeJavaScript(code)) as T;
    } catch (caught) {
      lastError = caught;
      await delay(200);
    }
  }
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
}

async function waitForRenderer(window: BrowserWindow): Promise<void> {
  for (let attempt = 0; attempt < 160; attempt += 1) {
    if (window.isDestroyed()) return;
    try {
      const ready = await evalRenderer<boolean>(
        window,
        "typeof window.__smoke === 'function'",
      );
      if (ready) return;
    } catch {
      // 页面仍在加载。
    }
    await delay(100);
  }
  throw new Error("renderer did not become ready");
}

type SmokeResult = {
  utilityPid: number;
  childPid: number;
  mainPid: number;
  utilityResult: number;
  childResult: number;
  equal: boolean;
  utilityTransport: string;
  childTransport: string;
  heartbeat: number;
  restarts: number;
  runningAfterRestart: boolean;
  lastExitCode: number | null;
  finalRunning: boolean;
  logs: number;
  events: number;
};

async function runSmoke(window: BrowserWindow): Promise<void> {
  try {
    await waitForRenderer(window);
    await delay(700);
    await waitForRenderer(window);
    const result = await evalRenderer<SmokeResult>(window, "window.__smoke()");
    process.stdout.write(
      `${JSON.stringify({
        evt: "smoke",
        ok:
          result.utilityPid > 0 &&
          result.childPid > 0 &&
          result.utilityPid !== result.mainPid &&
          result.childPid !== result.mainPid &&
          result.utilityResult === result.childResult &&
          result.equal &&
          result.utilityTransport === "message" &&
          result.childTransport === "stdio" &&
          result.heartbeat > 0 &&
          result.restarts >= 1 &&
          result.runningAfterRestart &&
          result.lastExitCode === 3 &&
          !result.finalRunning &&
          result.logs > 0 &&
          result.events >= 5,
        ...result,
      })}\n`,
    );
    app.quit();
  } catch (caught) {
    process.stdout.write(
      `${JSON.stringify({ evt: "smoke", ok: false, message: String(caught) })}\n`,
    );
    app.exit(1);
  }
}

async function capture(
  window: BrowserWindow,
  dir: string,
  file: string,
): Promise<void> {
  const image = await window.webContents.capturePage();
  if (image.isEmpty()) throw new Error(`empty capture: ${file}`);
  const png = image.toPNG();
  fsSync.writeFileSync(path.join(dir, file), png);
  fsSync.writeFileSync(path.join(dir, "raw", file), png);
}

async function runShots(window: BrowserWindow): Promise<void> {
  try {
    const dir = path.resolve(
      process.cwd(),
      "../../../docs/assets/images/41-sidecar-child-process",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    await waitForRenderer(window);
    await delay(700);
    await waitForRenderer(window);
    await evalRenderer(window, `window.__prepareShots("utility")`);
    await delay(500);
    await capture(window, dir, "41-01-utility.png");
    await evalRenderer(window, `window.__prepareShots("child")`);
    await delay(500);
    await capture(window, dir, "41-02-child.png");
    await evalRenderer(window, `window.__prepareShots("restart")`);
    await delay(500);
    await capture(window, dir, "41-03-restart.png");
    await stop(true);
    app.quit();
  } catch (caught) {
    process.stdout.write(
      `${JSON.stringify({ evt: "shots-error", message: String(caught) })}\n`,
    );
    app.exit(1);
  }
}

ipcMain.handle(CH.snapshot, () => snapshot());

ipcMain.handle(CH.start, async (_event, raw: unknown) => {
  assertModeReq(raw);
  await start(raw.mode);
  return snapshot();
});

ipcMain.handle(CH.stop, async () => {
  await stop();
  return snapshot();
});

ipcMain.handle(CH.crash, () => {
  sendRaw({ type: "crash" });
  log("crash", "已发送崩溃指令");
  return snapshot();
});

ipcMain.handle(CH.job, async (_event, raw: unknown) => {
  assertJobReq(raw);
  await runJob(raw.n);
  return snapshot();
});

ipcMain.handle(CH.refresh, () => {
  log("refresh", "刷新 sidecar 状态");
  return snapshot();
});

app.whenReady().then(() => {
  const window = createWindow();
  if (isSmoke) {
    void runSmoke(window);
  } else if (isShots) {
    void runShots(window);
  }
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    } else {
      win?.show();
      win?.focus();
    }
  });
});

app.on("will-quit", () => {
  manualStop = true;
  if (restartTimer) clearTimeout(restartTimer);
  try {
    if (proc && mode === "utility") (proc as UtilityProcess).kill();
    if (proc && mode === "child") (proc as ChildProcess).kill("SIGKILL");
  } catch {
    // 退出清理尽力而为。
  }
  proc = null;
  if (tempData) {
    try {
      fsSync.rmSync(tempData, { recursive: true, force: true });
    } catch {
      // 清理失败不影响退出。
    }
  }
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") app.quit();
});