示例工程 38-schema-migrations-concurrency

38-schema-migrations-concurrency/app/main/index.ts

typescript · 12 KB

import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import type { DatabaseSync } from "node:sqlite";
import { probeContention, type ContentionResult } from "../shared/contention";
import {
  columnNames,
  countRows,
  openLabDb,
  removeDbFiles,
  seedNotes,
  tableNames,
} from "../shared/db";
import {
  assertQueueReq,
  CH,
  type EventRow,
  type FailureInfo,
  type QueueResult,
  type Snapshot,
} from "../shared/ipc";
import {
  brokenMigrations,
  currentVersion,
  migrationHistory,
  runMigrations,
  TARGET_VERSION,
  type MigrationResult,
} from "../shared/migrations";
import { createWriteQueue } from "../shared/write-queue";

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

let win: BrowserWindow | null = null;
let db: DatabaseSync | null = null;
let migrationResult: MigrationResult | null = null;
let lastFailure: FailureInfo | null = null;
let lastQueue: QueueResult | null = null;
let lastContention: ContentionResult | null = null;
let events: EventRow[] = [];
let sequence = 0;

const userData = app.getPath("userData");
const labPath = path.join(userData, "lab.sqlite");
const failPath = path.join(userData, "fail.sqlite");
const lockPath = path.join(userData, "lock.sqlite");
const queue = createWriteQueue();

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

function snapshot(): Snapshot {
  const database = db;
  const version = database ? currentVersion(database) : 0;
  const history = database ? migrationHistory(database) : [];
  return {
    platform: process.platform,
    electronVersion: process.versions.electron,
    nodeVersion: process.versions.node,
    schema: {
      path: labPath,
      version,
      target: TARGET_VERSION,
      tables: database ? tableNames(database) : [],
      columns: database ? columnNames(database, "notes") : [],
      counts: {
        notes: database ? countRows(database, "notes") : 0,
        events: database ? countRows(database, "events") : 0,
        history: history.length,
      },
      history,
    },
    migration: migrationResult,
    failure: lastFailure,
    queue: { pending: queue.pending(), last: lastQueue },
    contention: lastContention,
    events: events.map((row) => ({ ...row })),
  };
}

function openAndMigrate(): DatabaseSync {
  const database = openLabDb(labPath);
  migrationResult = runMigrations(database, TARGET_VERSION);
  const seeded = seedNotes(database);
  log(
    "migrate",
    `v${migrationResult.from} → v${migrationResult.to} · 应用 ${migrationResult.applied} 步 · 种子 ${seeded} 条`,
  );
  return database;
}

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

async function queuedWrites(count: number): Promise<QueueResult> {
  const started = performance.now();
  const order = await Promise.all(
    Array.from({ length: count }, () =>
      queue.run(async () => {
        const seq = ++sequence;
        db?.prepare(
          "INSERT INTO events (kind, detail, at) VALUES (?, ?, ?)",
        ).run("queue", `write ${seq}`, new Date().toISOString());
        await delay(2);
        return seq;
      }),
    ),
  );
  const ms = performance.now() - started;
  const result: QueueResult = {
    count,
    order,
    min: Math.min(...order),
    max: Math.max(...order),
    ms: Number(ms.toFixed(2)),
    at: Date.now(),
  };
  lastQueue = result;
  log("queue", `${count} 条并发写完成 · ${result.ms}ms`);
  return result;
}

function failureDemo(): void {
  removeDbFiles(failPath);
  const database = openLabDb(failPath);
  const first = runMigrations(database, 1);
  const broken = runMigrations(database, 2, brokenMigrations());
  const columns = columnNames(database, "notes");
  lastFailure = {
    from: first.to,
    to: broken.to,
    error: broken.error,
    steps: broken.steps,
    columns,
    titlePresent: columns.includes("title"),
    at: Date.now(),
  };
  database.close();
  log("failure", `v${first.to} → v${broken.to} · ${broken.error || "未失败"}`);
}

function resetLab(): void {
  db?.close();
  db = null;
  removeDbFiles(labPath);
  sequence = 0;
  lastQueue = null;
  lastContention = null;
  lastFailure = null;
  db = openAndMigrate();
  log("reset", "实验库已重建并迁移到最新版本");
}

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;
}

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 = {
  schemaVersion: number;
  history: number;
  tables: number;
  notes: number;
  idempotentApplied: number;
  appliedTo: number;
  queueCount: number;
  queueUnique: number;
  queueMin: number;
  queueMax: number;
  queuePending: number;
  queueMs: number;
  busyMessage: string;
  busyCode: string;
  retryOk: boolean;
  failFrom: number;
  failTo: number;
  failError: string;
  failTitle: boolean;
  failStep: number;
  finalVersion: number;
  finalNotes: number;
  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.schemaVersion === 3 &&
          result.history === 3 &&
          result.tables >= 3 &&
          result.notes >= 5 &&
          result.idempotentApplied === 0 &&
          result.appliedTo === 3 &&
          result.queueCount === 20 &&
          result.queueUnique === 20 &&
          result.queueMin === 1 &&
          result.queueMax === 20 &&
          result.queuePending === 0 &&
          result.busyMessage.includes("locked") &&
          result.busyCode === "ERR_SQLITE_ERROR" &&
          result.retryOk &&
          result.failFrom === 1 &&
          result.failTo === 1 &&
          result.failError.includes("duplicate column") &&
          result.failTitle === false &&
          result.failStep === 2 &&
          result.finalVersion === 3 &&
          result.finalNotes === result.notes &&
          result.events >= 5,
        ...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/38-schema-migrations-concurrency",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    await waitForRenderer(window);
    await delay(700);
    await waitForRenderer(window);
    await evalRenderer(window, `window.__prepareShots("migrations")`);
    await delay(400);
    await capture(window, dir, "38-01-migrations.png");
    await evalRenderer(window, `window.__prepareShots("failure")`);
    await delay(400);
    await capture(window, dir, "38-02-failure.png");
    await evalRenderer(window, `window.__prepareShots("concurrency")`);
    await delay(500);
    await capture(window, dir, "38-03-concurrency.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.migrate, () => {
  if (!db) throw new Error("NO_DB");
  migrationResult = runMigrations(db, TARGET_VERSION);
  log(
    "migrate",
    `v${migrationResult.from} → v${migrationResult.to} · 应用 ${migrationResult.applied} 步`,
  );
  return snapshot();
});

ipcMain.handle(CH.reset, () => {
  resetLab();
  return snapshot();
});

ipcMain.handle(CH.fail, () => {
  failureDemo();
  return snapshot();
});

ipcMain.handle(CH.queue, async (_event, raw: unknown) => {
  assertQueueReq(raw);
  await queuedWrites(raw.count);
  return snapshot();
});

ipcMain.handle(CH.contention, () => {
  lastContention = probeContention(lockPath);
  log(
    "contention",
    `${lastContention.busyMessage || "未冲突"} · 重试 ${lastContention.retryOk}`,
  );
  return snapshot();
});

ipcMain.handle(CH.refresh, () => {
  log("refresh", "刷新 schema 与迁移历史");
  return snapshot();
});

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

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