示例工程 40-node-api-native-modules

40-node-api-native-modules/app/main/index.ts

typescript · 12 KB

import { app, BrowserWindow, ipcMain } from "electron";
import { createHash } from "node:crypto";
import fsSync from "node:fs";
import { createRequire } from "node:module";
import os from "node:os";
import path from "node:path";
import { performance } from "node:perf_hooks";
import {
  assertFallbackReq,
  assertHashReq,
  CH,
  type BenchRow,
  type EventRow,
  type HashResult,
  type NativeInfo,
  type Snapshot,
} from "../shared/ipc";
import type { NativeApi } from "../shared/native";

app.setName("Native Module 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(),
        `native-${isSmoke ? "smoke" : "shots"}-${process.pid}`,
      )
    : "";
if (tempData) app.setPath("userData", tempData);

const nodeRequire = createRequire(__filename);
let native: NativeApi | null = null;
let nativePath = "";
let nativeError = "";
let forcedFallback = false;
let lastHash: HashResult | null = null;
let bench: BenchRow[] = [];
let events: EventRow[] = [];
let win: BrowserWindow | null = null;

function log(kind: string, detail: string): void {
  events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40);
  if (win && !win.isDestroyed()) {
    win.webContents.send("native:event", { kind, detail, at: Date.now() });
  }
}

function nativeCandidates(): string[] {
  const name = "hash_bridge.node";
  if (app.isPackaged) {
    return [
      path.join(process.resourcesPath, "app.asar.unpacked", "native", name),
      path.join(process.resourcesPath, "native", name),
    ];
  }
  return [
    path.join(app.getAppPath(), "native", name),
    path.join(process.cwd(), "native", name),
  ];
}

function loadNative(): void {
  native = null;
  nativeError = "";
  nativePath = "";
  for (const candidate of nativeCandidates()) {
    if (!fsSync.existsSync(candidate)) continue;
    try {
      try {
        delete nodeRequire.cache[nodeRequire.resolve(candidate)];
      } catch {
        // 首次加载没有缓存。
      }
      const loaded = nodeRequire(candidate) as Partial<NativeApi>;
      if (
        typeof loaded.hashText !== "function" ||
        typeof loaded.nativeVersion !== "function" ||
        typeof loaded.byteLength !== "function"
      ) {
        throw new Error("BAD_NATIVE_EXPORTS");
      }
      native = loaded as NativeApi;
      nativePath = candidate;
      log("native", `已加载 hash_bridge ${native.nativeVersion()}`);
      return;
    } catch (error) {
      nativeError = error instanceof Error ? error.message : String(error);
      log("native-error", nativeError);
    }
  }
  nativeError = nativeError || "NATIVE_MODULE_NOT_FOUND";
  log("fallback", "原生模块不可用,使用 JS SHA-256 回退");
}

function nativeInfo(): NativeInfo {
  return {
    loaded: native !== null,
    path: nativePath ? "native/hash_bridge.node" : "",
    version: native?.nativeVersion() ?? "",
    error: nativeError,
    forcedFallback,
    source: native && !forcedFallback ? "native" : "fallback",
  };
}

function jsHash(text: string): string {
  return createHash("sha256").update(text, "utf8").digest("hex");
}

function average(fn: () => void, repeats: number): number {
  const started = performance.now();
  for (let index = 0; index < repeats; index += 1) fn();
  return (performance.now() - started) / repeats;
}

function hashText(text: string): HashResult {
  const jsStarted = performance.now();
  const hash = jsHash(text);
  const jsMs = performance.now() - jsStarted;
  let nativeHash = "";
  let nativeMs = 0;
  const useNative = native !== null && !forcedFallback;
  if (useNative && native) {
    const started = performance.now();
    nativeHash = native.hashText(text);
    nativeMs = performance.now() - started;
  }
  lastHash = {
    inputLength: text.length,
    byteLength: Buffer.byteLength(text, "utf8"),
    nativeHash,
    jsHash: hash,
    equal: nativeHash === "" || nativeHash === hash,
    usedNative: useNative,
    nativeMs: Number(nativeMs.toFixed(3)),
    jsMs: Number(jsMs.toFixed(3)),
    at: Date.now(),
  };
  log(
    "hash",
    `${useNative ? "native" : "fallback"} · ${text.length} 字符 · 相等 ${lastHash.equal}`,
  );
  return lastHash;
}

function runBenchmark(): BenchRow[] {
  const sizes: Array<[string, number, number]> = [
    ["1 KB", 1024, 60],
    ["100 KB", 100 * 1024, 12],
    ["1 MB", 1024 * 1024, 3],
  ];
  bench = sizes.map(([label, size, repeats]) => {
    const text = "a".repeat(size);
    const expected = jsHash(text);
    let nativeMs = 0;
    let nativeOk = true;
    if (native) {
      nativeMs = average(() => {
        if (native) native.hashText(text);
      }, repeats);
      nativeOk = native.hashText(text) === expected;
    }
    const jsMs = average(() => jsHash(text), repeats);
    return {
      label,
      size,
      nativeMs: Number(nativeMs.toFixed(3)),
      jsMs: Number(jsMs.toFixed(3)),
      equal: nativeOk,
      nativeRepeats: repeats,
      jsRepeats: repeats,
    };
  });
  log(
    "bench",
    bench
      .map((row) => `${row.label} native ${row.nativeMs}ms / js ${row.jsMs}ms`)
      .join(" · "),
  );
  return bench;
}

function snapshot(): Snapshot {
  return {
    abi: {
      platform: process.platform,
      arch: process.arch,
      modules: process.versions.modules ?? "",
      napi: process.versions.napi ?? "",
      node: process.versions.node,
      electron: process.versions.electron,
    },
    native: nativeInfo(),
    lastHash,
    bench,
    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: "原生模块实验室",
    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", "原生模块实验室已加载");
  });
  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 (error) {
      lastError = error;
      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 = {
  nativeLoaded: boolean;
  version: string;
  napi: string;
  modules: string;
  hashEqual: boolean;
  usedNative: boolean;
  nativeHashLength: number;
  fallbackEqual: boolean;
  fallbackUsed: boolean;
  benchRows: number;
  benchEqual: boolean;
  benchNativePositive: boolean;
  reloadLoaded: boolean;
  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.nativeLoaded &&
          result.version === "0.1.0" &&
          result.napi.length > 0 &&
          result.modules.length > 0 &&
          result.hashEqual &&
          result.usedNative &&
          result.nativeHashLength === 64 &&
          result.fallbackEqual &&
          result.fallbackUsed &&
          result.benchRows === 3 &&
          result.benchEqual &&
          result.benchNativePositive &&
          result.reloadLoaded &&
          result.events >= 4,
        ...result,
      })}\n`,
    );
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "smoke", ok: false, message: String(error) })}\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/40-node-api-native-modules",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    await waitForRenderer(window);
    await delay(700);
    await waitForRenderer(window);
    await evalRenderer(window, `window.__prepareShots("native")`);
    await delay(400);
    await capture(window, dir, "40-01-native.png");
    await evalRenderer(window, `window.__prepareShots("fallback")`);
    await delay(400);
    await capture(window, dir, "40-02-fallback.png");
    await evalRenderer(window, `window.__prepareShots("bench")`);
    await delay(500);
    await capture(window, dir, "40-03-bench.png");
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "shots-error", message: String(error) })}\n`,
    );
    app.exit(1);
  }
}

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

ipcMain.handle(CH.hash, (_event, raw: unknown) => {
  assertHashReq(raw);
  hashText(raw.text);
  return snapshot();
});

ipcMain.handle(CH.benchmark, () => {
  runBenchmark();
  return snapshot();
});

ipcMain.handle(CH.setFallback, (_event, raw: unknown) => {
  assertFallbackReq(raw);
  forcedFallback = raw.enabled;
  log("fallback", forcedFallback ? "强制 JS 回退" : "恢复原生模块");
  return snapshot();
});

ipcMain.handle(CH.reload, () => {
  loadNative();
  return snapshot();
});

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

app.whenReady().then(() => {
  loadNative();
  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", () => {
  if (tempData) {
    try {
      fsSync.rmSync(tempData, { recursive: true, force: true });
    } catch {
      // 清理失败不影响退出。
    }
  }
});

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