示例工程 10-ipc-streams-and-files

10-ipc-streams-and-files/app/main/index.ts

typescript · 14 KB

import {
  app,
  BrowserWindow,
  ipcMain,
  MessageChannelMain,
  type MessagePortMain,
} from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import {
  CH,
  isStreamAck,
  isStreamOptions,
  type CancelResult,
  type FileResult,
  type FileStats,
  type SlowResult,
  type StartResult,
  type StreamMessage,
  type StreamOptions,
} from "../shared/ipc";

app.setName("Stream Lab");

const isSmoke =
  process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
const isDiagnostics = process.argv.includes("--diagnostics");
const smokeData = isSmoke
  ? path.join(os.tmpdir(), `stream-lab-smoke-${process.pid}`)
  : "";
if (smokeData) app.setPath("userData", smokeData);

const MAX_IN_FLIGHT = 4;
const FILE_BYTES = 200 * 1024 * 1024;
const FILE_CHUNK = 1024 * 1024;

let logFile = "";
let streamSeq = 0;

type ActiveStream = {
  id: string;
  options: StreamOptions;
  port: MessagePortMain;
  sent: number;
  acked: number;
  inFlight: number;
  startedAt: number;
  timer: NodeJS.Timeout;
  cancelled: boolean;
};

let active: ActiveStream | null = null;

function writeLog(level: string, evt: string, msg?: string): void {
  const line = JSON.stringify({
    at: Date.now(),
    level,
    evt,
    ...(msg ? { msg } : {}),
  });
  process.stdout.write(`${line}\n`);
  if (!logFile) return;
  try {
    fsSync.appendFileSync(logFile, `${line}\n`);
  } catch {
    // 日志失败不影响流式演示。
  }
}

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 win = new BrowserWindow({
    width: 1000,
    height: 720,
    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,
    },
  });
  win.once("ready-to-show", () => {
    if (!win.isDestroyed()) win.show();
  });
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    void win.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
  } else {
    void win.loadFile(
      path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
    );
  }
  return win;
}

function delay(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function evalRenderer<T>(win: BrowserWindow, code: string): Promise<T> {
  let lastError: unknown = null;
  for (let attempt = 0; attempt < 3; attempt += 1) {
    try {
      return (await win.webContents.executeJavaScript(code)) as T;
    } catch (error) {
      lastError = error;
      await delay(200);
    }
  }
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
}

async function waitForRenderer(win: BrowserWindow): Promise<void> {
  for (let attempt = 0; attempt < 120; attempt += 1) {
    if (win.isDestroyed()) return;
    try {
      const ready = await evalRenderer<boolean>(
        win,
        "typeof window.__smoke === 'function'",
      );
      if (ready) return;
    } catch {
      // 页面仍在加载。
    }
    await delay(100);
  }
  throw new Error("renderer did not become ready");
}

function closeActive(reason: string): void {
  const stream = active;
  if (!stream) return;
  stream.cancelled = true;
  clearInterval(stream.timer);
  try {
    stream.port.postMessage({
      type: "cancelled",
      sent: stream.sent,
      acked: stream.acked,
      at: Date.now(),
    } satisfies StreamMessage);
  } catch {
    // 端口可能已关闭。
  }
  setTimeout(() => {
    try {
      stream.port.close();
    } catch {
      // 已关闭。
    }
  }, 100);
  writeLog(
    "warn",
    "stream-closed",
    `id=${stream.id} reason=${reason} sent=${stream.sent} acked=${stream.acked}`,
  );
  active = null;
}

function finishIfDone(stream: ActiveStream): void {
  if (stream.sent < stream.options.chunks || stream.inFlight !== 0) return;
  clearInterval(stream.timer);
  stream.port.postMessage({
    type: "done",
    total: stream.sent,
    acked: stream.acked,
    durationMs: Date.now() - stream.startedAt,
  } satisfies StreamMessage);
  const id = stream.id;
  setTimeout(() => {
    try {
      stream.port.close();
    } catch {
      // 已关闭。
    }
  }, 150);
  writeLog(
    "info",
    "stream-done",
    `id=${id} sent=${stream.sent} acked=${stream.acked}`,
  );
  if (active === stream) active = null;
}

function pump(): void {
  const stream = active;
  if (!stream || stream.cancelled) return;
  while (
    stream.sent < stream.options.chunks &&
    stream.inFlight < MAX_IN_FLIGHT
  ) {
    stream.sent += 1;
    stream.inFlight += 1;
    stream.port.postMessage({
      type: "chunk",
      seq: stream.sent,
      total: stream.options.chunks,
      sizeKB: stream.options.sizeKB,
      at: Date.now(),
    } satisfies StreamMessage);
  }
  finishIfDone(stream);
}

ipcMain.handle(CH.start, (event, raw: unknown): StartResult => {
  if (!isStreamOptions(raw)) {
    return { ok: false, code: "BAD_OPTIONS" };
  }
  if (active) closeActive("replaced");
  streamSeq += 1;
  const id = `stream-${streamSeq}`;
  const channel = new MessageChannelMain();
  const stream: ActiveStream = {
    id,
    options: raw,
    port: channel.port1,
    sent: 0,
    acked: 0,
    inFlight: 0,
    startedAt: Date.now(),
    timer: setInterval(() => {}, 1000),
    cancelled: false,
  };
  clearInterval(stream.timer);
  channel.port1.on("message", (messageEvent) => {
    if (!isStreamAck(messageEvent.data)) return;
    stream.acked += 1;
    stream.inFlight = Math.max(0, stream.inFlight - 1);
    // 不在 ack 里继续发:发送节奏由定时器控制,窗口只负责限流。
    finishIfDone(stream);
  });
  channel.port1.start();
  active = stream;
  // 先转移端口,等 preload 挂好 onmessage 再开始发。
  event.sender.postMessage(CH.portChannel, { streamId: id }, [channel.port2]);
  stream.timer = setInterval(pump, Math.max(10, raw.delayMs));
  setTimeout(pump, 60);
  writeLog(
    "info",
    "stream-start",
    `id=${id} chunks=${raw.chunks} sizeKB=${raw.sizeKB}`,
  );
  return { ok: true, streamId: id };
});

ipcMain.handle(CH.cancel, (_event, id: unknown): CancelResult => {
  if (typeof id !== "string") return { ok: false, code: "BAD_ID" };
  if (!active || active.id !== id) return { ok: false, code: "NO_ACTIVE" };
  closeActive("cancelled");
  return { ok: true };
});

ipcMain.handle(
  CH.slow,
  async (_event, delayMs: unknown, timeoutMs: unknown): Promise<SlowResult> => {
    if (
      typeof delayMs !== "number" ||
      typeof timeoutMs !== "number" ||
      !Number.isFinite(delayMs) ||
      !Number.isFinite(timeoutMs) ||
      delayMs < 0 ||
      timeoutMs < 0
    ) {
      return { ok: false, code: "BAD_INPUT" };
    }
    const startedAt = Date.now();
    if (delayMs > timeoutMs) {
      await delay(timeoutMs);
      return { ok: false, code: "TIMEOUT" };
    }
    await delay(delayMs);
    return { ok: true, value: 1, waitedMs: Date.now() - startedAt };
  },
);

function largeFilePath(): string {
  return path.join(os.tmpdir(), "electron-tutorial-200mb.bin");
}

function ensureLargeFile(): string {
  const file = largeFilePath();
  if (!fsSync.existsSync(file) || fsSync.statSync(file).size !== FILE_BYTES) {
    fsSync.writeFileSync(file, "");
    fsSync.truncateSync(file, FILE_BYTES);
  }
  return file;
}

async function measureFile(mode: "stream" | "whole"): Promise<FileStats> {
  const file = ensureLargeFile();
  const startedAt = Date.now();
  const baseline = process.memoryUsage().rss;
  let peak = baseline;
  let chunks = 0;
  if (mode === "whole") {
    const buffer = fsSync.readFileSync(file);
    chunks = Math.ceil(buffer.length / FILE_CHUNK);
    peak = Math.max(peak, process.memoryUsage().rss);
  } else {
    const timer = setInterval(() => {
      peak = Math.max(peak, process.memoryUsage().rss);
    }, 10);
    const stream = fsSync.createReadStream(file, {
      highWaterMark: FILE_CHUNK,
    });
    for await (const chunk of stream) {
      void chunk;
      chunks += 1;
      if (chunks % 16 === 0) {
        peak = Math.max(peak, process.memoryUsage().rss);
      }
    }
    clearInterval(timer);
    peak = Math.max(peak, process.memoryUsage().rss);
  }
  const deltaMB = Number(((peak - baseline) / 1024 / 1024).toFixed(1));
  writeLog(
    "info",
    "file-measured",
    `mode=${mode} chunks=${chunks} deltaMB=${deltaMB}`,
  );
  return {
    mode,
    sizeBytes: FILE_BYTES,
    chunks,
    baselineMB: Number((baseline / 1024 / 1024).toFixed(1)),
    peakMB: Number((peak / 1024 / 1024).toFixed(1)),
    deltaMB,
    durationMs: Date.now() - startedAt,
  };
}

ipcMain.handle(CH.large, (): Promise<FileResult> =>
  measureFile("stream").then(
    (stats) => ({ ok: true, stats }) as FileResult,
    (error) => ({ ok: false, code: String(error) }) as FileResult,
  ),
);

ipcMain.handle(CH.whole, (): Promise<FileResult> =>
  measureFile("whole").then(
    (stats) => ({ ok: true, stats }) as FileResult,
    (error) => ({ ok: false, code: String(error) }) as FileResult,
  ),
);

ipcMain.handle(CH.reset, () => {
  try {
    fsSync.rmSync(largeFilePath(), { force: true });
    return { ok: true };
  } catch {
    return { ok: false };
  }
});

type SmokeResult = {
  streamAcked: number;
  cancelSent: number;
  cancelCode: string;
  timeout: string;
  largeChunks: number;
  wholeChunks: number;
  streamDeltaMB: number;
  wholeDeltaMB: number;
};

async function runSmoke(): Promise<void> {
  try {
    const win = createWindow();
    await waitForRenderer(win);
    // 给 Vite 的首次热更新留时间,避免脚本执行到一半页面重载。
    await delay(800);
    await waitForRenderer(win);
    const result = await evalRenderer<SmokeResult>(win, "window.__smoke()");
    process.stdout.write(
      `${JSON.stringify({
        evt: "smoke",
        ok:
          result.streamAcked === 12 &&
          result.cancelCode === "CANCELLED" &&
          result.cancelSent < 30 &&
          result.timeout === "TIMEOUT" &&
          result.largeChunks === 200 &&
          result.wholeChunks === 200,
        ...result,
      })}\n`,
    );
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "smoke", ok: false, message: String(error) })}\n`,
    );
    app.exit(1);
  }
}

async function setTab(win: BrowserWindow, tab: string): Promise<void> {
  await evalRenderer(
    win,
    `window.__setTab && window.__setTab(${JSON.stringify(tab)})`,
  );
}

async function capture(
  win: BrowserWindow,
  dir: string,
  file: string,
): Promise<void> {
  const image = await win.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);
  writeLog("debug", "shot", file);
}

async function runShots(): Promise<void> {
  try {
    const dir = path.resolve(
      process.cwd(),
      "../../../docs/assets/images/10-ipc-streams-and-files",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    const win = createWindow();
    await waitForRenderer(win);
    await delay(800);
    await waitForRenderer(win);
    await evalRenderer(win, "window.__smoke()");
    await delay(400);
    // 再起一条慢流,拍「进行中」的背压状态。
    await evalRenderer(win, "window.__startStream(80, 60)");
    await delay(600);
    await setTab(win, "stream");
    await delay(200);
    await capture(win, dir, "10-01-stream.png");
    const activeId = await evalRenderer<string | null>(
      win,
      "window.__snapshot().streamId",
    );
    if (activeId) {
      await evalRenderer(
        win,
        `window.api.cancelStream(${JSON.stringify(activeId)})`,
      );
    }
    await setTab(win, "file");
    await delay(250);
    await capture(win, dir, "10-02-large-file.png");
    await setTab(win, "cancel");
    await delay(250);
    await capture(win, dir, "10-03-cancel.png");
    app.quit();
  } catch (error) {
    writeLog("error", "shots-failed", String(error));
    app.exit(1);
  }
}

function runDiagnostics(): void {
  const stream = fsSync.createReadStream("/nope/missing-200mb.bin");
  stream.on("error", (error) => {
    const value = error as NodeJS.ErrnoException;
    process.stdout.write(
      `${JSON.stringify({
        evt: "diagnostics",
        code: value.code,
        message: value.message,
        stack: String(value.stack ?? "")
          .split("\n")
          .slice(0, 2),
      })}\n`,
    );
    app.exit(0);
  });
}

app.whenReady().then(() => {
  if (isDiagnostics) {
    runDiagnostics();
    return;
  }
  logFile = path.join(app.getPath("logs"), "streams.log");
  try {
    fsSync.mkdirSync(path.dirname(logFile), { recursive: true });
  } catch {
    // 目录不可写时退化为只写 stdout。
  }
  writeLog("info", "app-ready", app.getVersion());
  if (isSmoke) {
    void runSmoke();
  } else if (isShots) {
    void runShots();
  } else {
    createWindow();
  }
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on("will-quit", () => {
  if (active) closeActive("quit");
  try {
    fsSync.rmSync(largeFilePath(), { force: true });
  } catch {
    // 临时文件可能不存在。
  }
  if (smokeData) {
    try {
      fsSync.rmSync(smokeData, { recursive: true, force: true });
    } catch {
      // 清理失败不影响退出。
    }
  }
});

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