示例工程 41-sidecar-child-process

41-sidecar-child-process/app/.tsc/main/index.js

javascript · 17 KB

import { app, BrowserWindow, ipcMain, utilityProcess, } from "electron";
import { spawn } from "node:child_process";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { assertJobReq, assertModeReq, CH, } 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 = null;
let proc = null;
let mode = "utility";
let transport = "message";
let pid = 0;
let startedAt = 0;
let restarts = 0;
let nextRestartAt = 0;
let heartbeat = 0;
let manualStop = false;
let error = "";
let lastExit = null;
let lastJob = null;
const byMode = {
    utility: null,
    child: null,
};
let logs = [];
let events = [];
let seq = 0;
let restartTimer = null;
let readyResolve = null;
let readyReject = null;
let readyTimer = null;
let stdoutBuffer = "";
const pending = new Map();
function sidecarPath() {
    return app.isPackaged
        ? path.join(process.resourcesPath, "sidecar", "worker.cjs")
        : path.join(app.getAppPath(), "sidecar", "worker.cjs");
}
function log(kind, detail) {
    events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40);
    broadcast();
}
function addLog(line) {
    const clean = line.length > 300 ? `${line.slice(0, 300)}…` : line;
    logs = [clean, ...logs].slice(0, 40);
}
function broadcast() {
    if (win && !win.isDestroyed()) {
        win.webContents.send("sidecar:event", { at: Date.now() });
    }
}
function messageOf(value) {
    return typeof value === "string" ? value : JSON.stringify(value);
}
function handleMessage(raw) {
    if (typeof raw !== "object" || raw === null) {
        addLog(messageOf(raw));
        return;
    }
    const message = raw;
    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) {
    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, code, signal, reason) {
    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) {
    await new Promise((resolve) => {
        let settled = false;
        const finish = () => {
            if (settled)
                return;
            settled = true;
            resolve();
        };
        if (mode === "utility") {
            source.once("exit", finish);
        }
        else {
            source.once("exit", finish);
        }
        setTimeout(finish, 1500);
    });
}
async function stop(silent = false) {
    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.kill();
    }
    else {
        source.kill("SIGTERM");
    }
    await waitForExit(source);
    if (mode === "child" && source.exitCode === null) {
        source.kill("SIGKILL");
    }
    lastExit = {
        code: mode === "child" ? source.exitCode : null,
        signal: "SIGTERM",
        reason: "manual",
        at: Date.now(),
    };
    if (!silent)
        log("stop", "已发送停止信号");
    broadcast();
}
function failReady(reason) {
    if (readyTimer)
        clearTimeout(readyTimer);
    readyTimer = null;
    error = reason;
    readyReject?.(new Error(reason));
    readyResolve = null;
    readyReject = null;
}
function waitReady() {
    return new Promise((resolve, reject) => {
        readyResolve = resolve;
        readyReject = reject;
        readyTimer = setTimeout(() => failReady("READY_TIMEOUT"), 5000);
    });
}
function spawnUtility() {
    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) => handleStdout(chunk.toString()));
    child.stderr?.on("data", (chunk) => {
        addLog(`stderr:${chunk.toString().slice(0, 200)}`);
    });
    child.on("exit", (code) => onExit(child, code, "", "utility"));
}
function spawnChild() {
    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) => handleStdout(chunk.toString()));
    child.stderr?.on("data", (chunk) => {
        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, restarting = false) {
    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) {
    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.postMessage(message);
        }
        else {
            proc.stdin?.write(`${JSON.stringify(message)}\n`);
        }
    });
}
function sendRaw(payload) {
    if (!proc)
        throw new Error("SIDECAR_NOT_RUNNING");
    if (mode === "utility") {
        proc.postMessage(payload);
    }
    else {
        proc.stdin?.write(`${JSON.stringify(payload)}\n`);
    }
}
async function runJob(n) {
    const response = await send({ type: "job", n });
    if (response.type !== "result") {
        throw new Error("BAD_JOB_RESPONSE");
    }
    const result = {
        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() {
    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() {
    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() {
    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) {
    return new Promise((resolve) => setTimeout(resolve, ms));
}
async function evalRenderer(window, code) {
    let lastError = null;
    for (let attempt = 0; attempt < 3; attempt += 1) {
        try {
            return (await window.webContents.executeJavaScript(code));
        }
        catch (caught) {
            lastError = caught;
            await delay(200);
        }
    }
    throw lastError instanceof Error ? lastError : new Error(String(lastError));
}
async function waitForRenderer(window) {
    for (let attempt = 0; attempt < 160; attempt += 1) {
        if (window.isDestroyed())
            return;
        try {
            const ready = await evalRenderer(window, "typeof window.__smoke === 'function'");
            if (ready)
                return;
        }
        catch {
            // 页面仍在加载。
        }
        await delay(100);
    }
    throw new Error("renderer did not become ready");
}
async function runSmoke(window) {
    try {
        await waitForRenderer(window);
        await delay(700);
        await waitForRenderer(window);
        const result = await evalRenderer(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, dir, file) {
    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) {
    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) => {
    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) => {
    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.kill();
        if (proc && mode === "child")
            proc.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();
});
//# sourceMappingURL=index.js.map