示例工程 03-process-model

03-process-model/app/.tsc/main/index.js

javascript · 8.6 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, } from "../shared/ipc";
const isUtility = process.env.UTILITY_MODE === "1";
function runUtilityChild() {
    const parentPort = process
        .parentPort;
    if (!parentPort) {
        process.exit(1);
    }
    parentPort.on("message", (event) => {
        const payload = event.data;
        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() {
    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 = null;
    let started = false;
    let crashCount = 0;
    function log(record) {
        process.stdout.write(`${JSON.stringify(record)}\n`);
    }
    function resolvePreload() {
        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() {
        const rendererPid = mainWindow?.webContents.getOSProcessId() ?? -1;
        const metrics = app.getAppMetrics();
        const processes = 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) {
        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;
                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() {
        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() {
        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() {
        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) => {
        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();
}
//# sourceMappingURL=index.js.map