示例工程 47-crash-recovery

47-crash-recovery/app/.tsc/main/index.js

javascript · 17 KB

import { app, BrowserWindow, crashReporter, ipcMain } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { assertErrorInfo, CH, decideRecovery, } from "../shared/ipc";
app.setName("Crash Recovery 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(), `crash-${isSmoke ? "smoke" : "shots"}-${process.pid}`)
    : "";
if (tempData)
    app.setPath("userData", tempData);
const userData = app.getPath("userData");
const dumpsDir = path.join(userData, "crashes");
const historyFile = path.join(userData, "crash-history.json");
const workspace = path.join(userData, "workspace");
fsSync.mkdirSync(dumpsDir, { recursive: true });
fsSync.mkdirSync(workspace, { recursive: true });
app.setPath("crashDumps", dumpsDir);
const config = {
    contextIsolation: true,
    sandbox: true,
    nodeIntegration: false,
    webSecurity: true,
    allowRunningInsecureContent: false,
    experimentalFeatures: false,
    webviewTag: false,
};
let win = null;
let events = [];
let history = [];
let lastError = null;
const autoRecover = true;
let lastRecoveryMs = 0;
let reporterStarted = false;
let rendererAlive = true;
const flags = {
    crashHandler: false,
    errorHookReady: false,
};
function readHistory() {
    try {
        const raw = fsSync.readFileSync(historyFile, "utf8");
        const parsed = JSON.parse(raw);
        if (!Array.isArray(parsed))
            return [];
        return parsed.filter((row) => {
            if (typeof row !== "object" || row === null)
                return false;
            const item = row;
            return (typeof item.id === "string" &&
                typeof item.at === "number" &&
                typeof item.reason === "string" &&
                typeof item.exitCode === "number");
        });
    }
    catch {
        return [];
    }
}
function persistHistory() {
    try {
        const temp = `${historyFile}.tmp`;
        fsSync.writeFileSync(temp, `${JSON.stringify(history, null, 2)}\n`, "utf8");
        fsSync.renameSync(temp, historyFile);
    }
    catch (error) {
        log("history-error", error instanceof Error ? error.message : String(error));
    }
}
function countDumps() {
    let total = 0;
    let pending = 0;
    const walk = (dir, inPending) => {
        let entries = [];
        try {
            entries = fsSync.readdirSync(dir, { withFileTypes: true });
        }
        catch {
            return;
        }
        for (const entry of entries) {
            const full = path.join(dir, entry.name);
            if (entry.isDirectory()) {
                walk(full, inPending || entry.name === "pending");
            }
            else if (entry.name.endsWith(".dmp")) {
                total += 1;
                if (inPending)
                    pending += 1;
            }
        }
    };
    walk(dumpsDir, false);
    return { total, pending };
}
function recentCrashes(now = Date.now()) {
    return history.filter((row) => now - row.at < 60_000);
}
function log(kind, detail) {
    events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40);
    broadcast();
}
function broadcast() {
    if (!rendererAlive)
        return;
    if (win && !win.isDestroyed()) {
        try {
            win.webContents.send("crash:event", { at: Date.now() });
        }
        catch {
            // 渲染帧可能刚被销毁,事件丢失不影响主进程状态。
        }
    }
}
function checks() {
    const dumps = countDumps();
    const last = history[0];
    let writable = false;
    try {
        fsSync.accessSync(dumpsDir, fsSync.constants.W_OK);
        writable = true;
    }
    catch {
        writable = false;
    }
    return [
        {
            id: "reporter",
            label: "crashReporter 已启动",
            pass: reporterStarted,
            detail: String(reporterStarted),
        },
        {
            id: "upload",
            label: "上传关闭(本地 dump)",
            pass: reporterStarted && !reporterCfg.uploadToServer,
            detail: String(reporterCfg.uploadToServer),
        },
        {
            id: "dumps-dir",
            label: "crashDumps 目录可写",
            pass: writable,
            detail: writable ? "writable" : "not-writable",
        },
        {
            id: "handler",
            label: "render-process-gone 监听已安装",
            pass: flags.crashHandler,
            detail: String(flags.crashHandler),
        },
        {
            id: "auto-recover",
            label: "自动恢复已启用",
            pass: autoRecover,
            detail: String(autoRecover),
        },
        {
            id: "history-file",
            label: "崩溃历史已落盘",
            pass: fsSync.existsSync(historyFile),
            detail: fsSync.existsSync(historyFile) ? "present" : "missing",
        },
        {
            id: "last-recovered",
            label: "最近一次崩溃已恢复",
            pass: last ? last.recovered : true,
            detail: last ? String(last.recovered) : "no crash yet",
        },
        {
            id: "dumps",
            label: "崩溃 dump 已生成(首次崩溃后)",
            pass: last ? dumps.total >= 1 : true,
            detail: last ? `${dumps.total} dmp` : "waiting",
        },
        {
            id: "error-hook",
            label: "渲染进程错误钩子已安装",
            pass: flags.errorHookReady,
            detail: String(flags.errorHookReady),
        },
        {
            id: "sandbox",
            label: "sandbox / contextIsolation 开启",
            pass: config.sandbox && config.contextIsolation,
            detail: `${config.sandbox}/${config.contextIsolation}`,
        },
    ];
}
const reporterCfg = {
    uploadToServer: false,
    compress: false,
};
function snapshot() {
    const list = checks();
    const passed = list.filter((check) => check.pass).length;
    const dumps = countDumps();
    return {
        platform: process.platform,
        electronVersion: process.versions.electron,
        nodeVersion: process.versions.node,
        checks: list,
        score: Math.round((passed / list.length) * 100),
        crashReporter: {
            started: reporterStarted,
            uploadToServer: reporterCfg.uploadToServer,
            directory: dumpsDir,
            dumpCount: dumps.total,
            pendingCount: dumps.pending,
        },
        history: history.map((row) => ({ ...row })),
        recovery: {
            autoRecover,
            lastRecoveryMs,
            recoveredCount: history.filter((row) => row.recovered).length,
        },
        lastError: lastError ? { ...lastError } : null,
        errorHookReady: flags.errorHookReady,
        events: events.map((row) => ({ ...row })),
    };
}
function scheduleRecovery(row) {
    const attempts = Math.max(0, recentCrashes().length - 1);
    const decision = decideRecovery(row.reason, attempts);
    log("recovery-plan", `${decision.action} · ${decision.detail}`);
    if (decision.action !== "reload") {
        log("safe-mode", "停止自动恢复,等待人工处理");
        return;
    }
    const start = Date.now();
    setTimeout(() => {
        if (!win || win.isDestroyed())
            return;
        win.webContents.once("did-finish-load", () => {
            row.recovered = true;
            row.recoveryMs = Date.now() - start;
            row.dumpCount = countDumps().total;
            lastRecoveryMs = row.recoveryMs;
            persistHistory();
            log("recovered", `${row.reason} · ${row.recoveryMs}ms`);
            broadcast();
        });
        try {
            win.webContents.reload();
        }
        catch (error) {
            log("reload-error", error instanceof Error ? error.message : String(error));
        }
    }, decision.delayMs);
}
function installCrashHandler(window) {
    window.webContents.on("render-process-gone", (_event, details) => {
        rendererAlive = false;
        const row = {
            id: `${Date.now()}-${Math.random().toString(16).slice(2, 8)}`,
            at: Date.now(),
            reason: details.reason,
            exitCode: details.exitCode,
            recovered: false,
            recoveryMs: 0,
            dumpCount: countDumps().total,
        };
        history = [row, ...history].slice(0, 50);
        persistHistory();
        log("render-gone", `${details.reason} · exit ${details.exitCode}`);
        scheduleRecovery(row);
    });
    flags.crashHandler = true;
}
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: "崩溃恢复实验室",
        backgroundColor: "#ffffff",
        webPreferences: {
            preload: resolvePreload(),
            contextIsolation: true,
            sandbox: true,
            nodeIntegration: false,
            webSecurity: true,
            allowRunningInsecureContent: false,
            experimentalFeatures: false,
            webviewTag: false,
            spellcheck: false,
            backgroundThrottling: true,
        },
    });
    installCrashHandler(window);
    const contents = window.webContents;
    contents.setWindowOpenHandler(() => ({ action: "deny" }));
    contents.on("will-navigate", (event, url) => {
        if (!url.startsWith("file://"))
            event.preventDefault();
    });
    contents.on("will-attach-webview", (event) => event.preventDefault());
    window.once("ready-to-show", () => window.show());
    contents.on("did-finish-load", () => {
        rendererAlive = true;
        if (!window.isDestroyed() && !window.isVisible())
            window.show();
        log("ready", "崩溃恢复界面已加载");
    });
    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 lastCaught = null;
    for (let attempt = 0; attempt < 3; attempt += 1) {
        try {
            return (await window.webContents.executeJavaScript(code));
        }
        catch (caught) {
            lastCaught = caught;
            await delay(150);
        }
    }
    throw lastCaught instanceof Error
        ? lastCaught
        : new Error(String(lastCaught));
}
async function waitForRenderer(window) {
    for (let attempt = 0; attempt < 160; attempt += 1) {
        if (window.isDestroyed())
            return;
        try {
            const ready = await evalRenderer(window, "typeof window.__demo === 'function'");
            if (ready)
                return;
        }
        catch {
            // 窗口正在重建或页面尚未加载。
        }
        await delay(100);
    }
    throw new Error("renderer did not become ready");
}
async function waitForRecovery(window) {
    for (let attempt = 0; attempt < 220; attempt += 1) {
        if (window.isDestroyed())
            return;
        try {
            const recovered = await evalRenderer(window, "window.__demo().then((row) => row.lastRecovered)");
            if (recovered)
                return;
        }
        catch {
            // 渲染进程尚未重建。
        }
        await delay(100);
    }
    throw new Error("renderer did not recover");
}
async function runSmoke(window) {
    try {
        await waitForRenderer(window);
        await delay(900);
        await waitForRenderer(window);
        const pre = await evalRenderer(window, "window.__demo()");
        window.webContents.forcefullyCrashRenderer();
        await waitForRecovery(window);
        await delay(1400);
        const post = await evalRenderer(window, "window.__demo()");
        await evalRenderer(window, "window.__simulateError()");
        await delay(300);
        const final = await evalRenderer(window, "window.__demo()");
        process.stdout.write(`${JSON.stringify({
            evt: "smoke",
            ok: pre.score === 100 &&
                post.score === 100 &&
                post.checks === 10 &&
                post.passed === 10 &&
                post.crashes === 1 &&
                post.lastReason === "killed" &&
                post.lastRecovered &&
                post.recoveryMs >= 0 &&
                post.dumps >= 1 &&
                post.pending >= 1 &&
                post.historyExists &&
                post.errorHookReady &&
                final.lastError.includes("BOOM") &&
                final.banner.includes("恢复") &&
                final.crashes === 1,
            pre,
            post,
            final,
        })}\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/47-crash-recovery");
        fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
        await waitForRenderer(window);
        await delay(900);
        await waitForRenderer(window);
        await evalRenderer(window, `window.__prepareShots("overview")`);
        await delay(300);
        await capture(window, dir, "47-01-overview.png");
        window.webContents.forcefullyCrashRenderer();
        await waitForRecovery(window);
        await delay(1500);
        await evalRenderer(window, `window.__prepareShots("recovered")`);
        await delay(300);
        await capture(window, dir, "47-02-recovered.png");
        await evalRenderer(window, `window.__prepareShots("degraded")`);
        await delay(400);
        await capture(window, dir, "47-03-degraded.png");
        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.ready, () => {
    flags.errorHookReady = true;
    log("error-hook", "渲染进程错误钩子已就绪");
    return snapshot();
});
ipcMain.handle(CH.crash, async () => {
    const current = snapshot();
    setTimeout(() => {
        if (win && !win.isDestroyed()) {
            win.webContents.forcefullyCrashRenderer();
        }
    }, 150);
    return current;
});
ipcMain.handle(CH.reload, () => {
    if (win && !win.isDestroyed()) {
        win.webContents.reload();
    }
    return snapshot();
});
ipcMain.handle(CH.reportError, (_event, raw) => {
    assertErrorInfo(raw);
    lastError = { ...raw, at: Date.now() };
    log("renderer-error", raw.message.slice(0, 120));
    return snapshot();
});
ipcMain.handle(CH.refresh, () => snapshot());
ipcMain.handle(CH.clearHistory, () => {
    history = [];
    persistHistory();
    log("clear-history", "崩溃历史已清空");
    return snapshot();
});
app.whenReady().then(() => {
    if (!fsSync.existsSync(historyFile)) {
        fsSync.writeFileSync(historyFile, `${JSON.stringify([], null, 2)}\n`, "utf8");
    }
    history = readHistory();
    try {
        crashReporter.start({
            uploadToServer: false,
            compress: false,
            rateLimit: false,
        });
        reporterStarted = true;
        log("reporter", `本地 dump:${dumpsDir}`);
    }
    catch (error) {
        log("reporter-error", error instanceof Error ? error.message : String(error));
    }
    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("child-process-gone", (_event, details) => {
    log("child-gone", `${details.type} · ${details.reason}`);
});
app.on("will-quit", () => {
    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