示例工程 03-process-model

03-process-model/app/main/index.ts

typescript · 7.9 KB

import { app, BrowserWindow, ipcMain, utilityProcess } from "electron";
import fsSync from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
import {
  CH,
  type ProcessEntry,
  type ProcessInfo,
  type UtilityResult,
} from "../shared/ipc";

type ParentPort = {
  on(event: "message", listener: (event: { data: unknown }) => void): void;
  postMessage(message: unknown): void;
};

const isUtility = process.env.UTILITY_MODE === "1";

function runUtilityChild(): void {
  const parentPort = (process as unknown as { parentPort?: ParentPort })
    .parentPort;
  if (!parentPort) {
    process.exit(1);
  }
  parentPort.on("message", (event) => {
    const payload = event.data as { n?: number };
    const n = typeof payload.n === "number" ? payload.n : 0;
    let sum = 0;
    for (let index = 1; index <= n; index += 1) sum += index;
    parentPort.postMessage({ sum });
  });
}

function runMain(): void {
  const isSmoke =
    process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
  const isShots = process.argv.includes("--shots");
  const isCrashDemo = process.argv.includes("--crash-demo");

  let mainWindow: BrowserWindow | null = null;
  let started = false;
  let crashCount = 0;

  function log(record: Record<string, unknown>): void {
    process.stdout.write(`${JSON.stringify(record)}\n`);
  }

  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 collectInfo(): ProcessInfo {
    const rendererPid = mainWindow?.webContents.getOSProcessId() ?? -1;
    const metrics = app.getAppMetrics();
    const processes: ProcessEntry[] = metrics.map((metric) => ({
      pid: metric.pid,
      type: metric.type,
      memoryMB: Math.round(metric.memory.workingSetSize / 1024),
    }));
    const gpu = metrics.find((metric) => metric.type === "GPU");
    return {
      mainPid: process.pid,
      rendererPid,
      gpuPid: gpu?.pid ?? -1,
      processes,
      crashCount,
      electron: process.versions.electron ?? "unknown",
      node: process.versions.node,
      chrome: process.versions.chrome,
    };
  }

  function runUtility(n: number): Promise<UtilityResult> {
    return new Promise((resolve, reject) => {
      const startedAt = Date.now();
      const child = utilityProcess.fork(path.join(__dirname, "index.cjs"), [], {
        env: { ...process.env, UTILITY_MODE: "1" },
      });
      const timer = setTimeout(() => {
        child.kill();
        reject(new Error("utility timeout"));
      }, 5000);
      child.once("spawn", () => {
        child.postMessage({ n });
      });
      child.on("message", (message) => {
        const data = message as { sum?: number };
        if (typeof data.sum === "number") {
          clearTimeout(timer);
          child.kill();
          resolve({ sum: data.sum, elapsedMs: Date.now() - startedAt });
        }
      });
      child.on("exit", (code) => {
        if (code !== 0) {
          clearTimeout(timer);
          reject(new Error(`utility exit ${code}`));
        }
      });
    });
  }

  function createWindow(): void {
    mainWindow = new BrowserWindow({
      width: 1000,
      height: 720,
      show: false,
      backgroundColor: "#ffffff",
      webPreferences: {
        preload: resolvePreload(),
        contextIsolation: true,
        sandbox: true,
        nodeIntegration: false,
        webSecurity: true,
        allowRunningInsecureContent: false,
        experimentalFeatures: false,
        webviewTag: false,
        spellcheck: false,
        backgroundThrottling: true,
      },
    });

    mainWindow.once("ready-to-show", () => {
      mainWindow?.show();
    });

    mainWindow.webContents.on("render-process-gone", (_event, details) => {
      crashCount += 1;
      log({
        evt: "render-process-gone",
        reason: details.reason,
        exitCode: details.exitCode,
        crashCount,
      });
      if (isCrashDemo) {
        app.quit();
        return;
      }
      if (crashCount <= 3) {
        setTimeout(() => mainWindow?.reload(), 300);
      }
    });

    mainWindow.webContents.on("did-finish-load", () => {
      if (started) return;
      started = true;
      const pid = mainWindow?.webContents.getOSProcessId() ?? -1;
      log({ evt: "window-created", id: mainWindow?.id, pid });
      if (isSmoke) {
        void runSmoke();
      } else if (isShots) {
        void runShots();
      } else if (isCrashDemo) {
        setTimeout(
          () => mainWindow?.webContents.forcefullyCrashRenderer(),
          300,
        );
      }
    });

    mainWindow.on("closed", () => {
      if (!isSmoke) log({ evt: "window-closed" });
      mainWindow = null;
    });

    if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
      void mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
    } else {
      void mainWindow.loadFile(
        path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
      );
    }
  }

  async function runSmoke(): Promise<void> {
    try {
      await new Promise((resolve) => setTimeout(resolve, 300));
      const utility = await runUtility(1000);
      const info = collectInfo();
      log({
        evt: "smoke",
        ok: info.rendererPid > 0 && info.gpuPid > 0 && utility.sum === 500500,
        mainPid: info.mainPid,
        rendererPid: info.rendererPid,
        gpuPid: info.gpuPid,
        utilitySum: utility.sum,
        crashCount: info.crashCount,
      });
      app.quit();
    } catch (error) {
      log({ evt: "error", message: String(error) });
      app.exit(1);
    }
  }

  async function runShots(): Promise<void> {
    try {
      const dir = path.resolve(
        process.cwd(),
        "../../../docs/assets/images/03-process-model",
      );
      await fs.mkdir(path.join(dir, "raw"), { recursive: true });
      await mainWindow?.webContents.executeJavaScript(
        `new Promise((resolve) => {
          const started = Date.now();
          const tick = () => {
            if (typeof window.__setTab === "function") resolve(true);
            else if (Date.now() - started > 3000) resolve(false);
            else setTimeout(tick, 20);
          };
          tick();
        })`,
      );
      const shots = [
        { tab: "processes", file: "03-01-processes.png" },
        { tab: "crash", file: "03-02-crash.png" },
        { tab: "utility", file: "03-03-utility.png" },
      ];
      for (const shot of shots) {
        await mainWindow?.webContents.executeJavaScript(
          `window.__setTab(${JSON.stringify(shot.tab)})`,
        );
        await new Promise((resolve) => setTimeout(resolve, 120));
        const image = await mainWindow?.webContents.capturePage();
        if (!image) throw new Error("capturePage returned null");
        const png = image.toPNG();
        await fs.writeFile(path.join(dir, shot.file), png);
        await fs.writeFile(path.join(dir, "raw", shot.file), png);
        log({ evt: "shot", file: shot.file, bytes: png.byteLength });
      }
      app.quit();
    } catch (error) {
      log({ evt: "error", message: String(error) });
      app.exit(1);
    }
  }

  ipcMain.handle(CH.info, () => collectInfo());
  ipcMain.handle(CH.crash, () => {
    mainWindow?.webContents.forcefullyCrashRenderer();
    return { ok: true };
  });
  ipcMain.handle(CH.utility, (_event, n: unknown) => {
    const count = typeof n === "number" && Number.isFinite(n) ? n : 0;
    return runUtility(count);
  });

  app.whenReady().then(() => {
    log({ evt: "app-ready", electron: process.versions.electron });
    createWindow();
    app.on("activate", () => {
      if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
  });

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

if (isUtility) {
  runUtilityChild();
} else {
  runMain();
}