示例工程 37-local-persistence

37-local-persistence/app/src/App.ts

typescript · 16 KB

import type { Snapshot } from "../shared/ipc";

function escape(text: string): string {
  return text.replace(/[&<>"]/g, (char) => {
    if (char === "&") return "&amp;";
    if (char === "<") return "&lt;";
    if (char === ">") return "&gt;";
    return "&quot;";
  });
}

function bytes(value: number): string {
  if (value < 1024) return `${value} B`;
  if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`;
  return `${(value / 1024 / 1024).toFixed(2)} MB`;
}

function time(at: number): string {
  return new Date(at).toLocaleTimeString("zh-CN", { hour12: false });
}

function sourceClass(source: string): string {
  if (source === "main") return "ok";
  if (source === "backup") return "warn";
  if (source === "seed") return "warn";
  return "bad";
}

export function mountApp(root: HTMLElement): void {
  root.innerHTML = `
    <div class="app">
      <header class="header">
        <div class="brand">
          <span class="logo">DB</span>
          <div>
            <h1>本地持久化实验室</h1>
            <span class="muted small">JSON 原子写 · node:sqlite · 基准与崩溃恢复</span>
          </div>
        </div>
        <div class="header-side">
          <span class="pill" data-testid="versions">—</span>
          <button class="btn" data-testid="refresh">重读两个存储</button>
          <span class="muted small" data-testid="status"></span>
        </div>
      </header>

      <main class="layout">
        <div class="column">
          <section class="card pad">
            <div class="card-head">
              <h2>JSON 原子写</h2>
              <span class="tag" data-testid="json-source">—</span>
            </div>
            <code class="path" data-testid="json-path">—</code>
            <div class="metrics">
              <div><span>记录</span><b data-testid="json-count">0</b></div>
              <div><span>体积</span><b data-testid="json-size">0</b></div>
              <div><span>写入</span><b data-testid="json-write">0 ms</b></div>
              <div><span>读取</span><b data-testid="json-read">0 ms</b></div>
              <div><span>备份</span><b data-testid="json-backup">0</b></div>
              <div><span>临时文件</span><b data-testid="json-tmp">0</b></div>
            </div>
            <div class="actions wrap">
              <button class="btn primary" data-testid="json-add">新增一条</button>
              <button class="btn" data-testid="json-reload">重读</button>
              <button class="btn danger" data-testid="json-corrupt">模拟损坏并恢复</button>
            </div>
            <div class="error-line" data-testid="json-error"></div>
            <ul class="notes" data-testid="json-notes"></ul>
          </section>

          <section class="card pad">
            <div class="card-head">
              <h2>路径与 ASAR</h2>
              <span class="tag" data-testid="db-asar">—</span>
            </div>
            <ul class="paths" data-testid="paths"></ul>
          </section>

          <section class="card pad">
            <div class="card-head">
              <h2>活动</h2>
              <span class="muted small">写入 / 恢复 / 基准</span>
            </div>
            <ul class="activity" data-testid="events"></ul>
          </section>
        </div>

        <div class="column">
          <section class="card pad">
            <div class="card-head">
              <h2>SQLite · node:sqlite</h2>
              <span class="tag" data-testid="sqlite-available">—</span>
            </div>
            <code class="path" data-testid="sqlite-path">—</code>
            <div class="metrics">
              <div><span>记录</span><b data-testid="sqlite-count">0</b></div>
              <div><span>体积</span><b data-testid="sqlite-size">0</b></div>
              <div><span>写入</span><b data-testid="sqlite-write">0 ms</b></div>
              <div><span>读取</span><b data-testid="sqlite-read">0 ms</b></div>
              <div><span>日志</span><b data-testid="sqlite-journal">—</b></div>
            </div>
            <div class="actions wrap">
              <button class="btn primary" data-testid="sqlite-add">新增一条</button>
              <button class="btn" data-testid="sqlite-reload">查询</button>
            </div>
            <div class="error-line" data-testid="sqlite-error"></div>
            <ul class="notes" data-testid="sqlite-notes"></ul>
          </section>

          <section class="card pad bench-card">
            <div class="card-head">
              <h2>选型基准</h2>
              <span class="muted small">单次运行,仅作量级参考</span>
            </div>
            <div class="actions wrap">
              <button class="btn" data-testid="bench-1000">1,000 条</button>
              <button class="btn" data-testid="bench-5000">5,000 条</button>
              <button class="btn" data-testid="bench-10000">10,000 条</button>
            </div>
            <div class="bench" data-testid="bench-table"></div>
          </section>

          <section class="card pad decision">
            <div class="card-head">
              <h2>怎么选</h2>
              <span class="muted small">先看数据形态,再看性能</span>
            </div>
            <ul class="bullets">
              <li><strong>设置 / 少量文档(&lt;1,000 条)</strong>:JSON 原子写,简单、可读、易备份。</li>
              <li><strong>结构化查询 / 频繁写入</strong>:<code>node:sqlite</code> + WAL,单写者、事务。</li>
              <li><strong>better-sqlite3</strong>:只在需要扩展或目标 Node 缺少 <code>node:sqlite</code> 时考虑,需处理 ABI。</li>
            </ul>
          </section>
        </div>
      </main>
    </div>
  `;

  const versions = root.querySelector<HTMLElement>('[data-testid="versions"]');
  const jsonSource = root.querySelector<HTMLElement>(
    '[data-testid="json-source"]',
  );
  const jsonPath = root.querySelector<HTMLElement>('[data-testid="json-path"]');
  const jsonCount = root.querySelector<HTMLElement>(
    '[data-testid="json-count"]',
  );
  const jsonSize = root.querySelector<HTMLElement>('[data-testid="json-size"]');
  const jsonWrite = root.querySelector<HTMLElement>(
    '[data-testid="json-write"]',
  );
  const jsonRead = root.querySelector<HTMLElement>('[data-testid="json-read"]');
  const jsonBackup = root.querySelector<HTMLElement>(
    '[data-testid="json-backup"]',
  );
  const jsonTmp = root.querySelector<HTMLElement>('[data-testid="json-tmp"]');
  const jsonError = root.querySelector<HTMLElement>(
    '[data-testid="json-error"]',
  );
  const jsonNotes = root.querySelector<HTMLElement>(
    '[data-testid="json-notes"]',
  );
  const sqliteAvailable = root.querySelector<HTMLElement>(
    '[data-testid="sqlite-available"]',
  );
  const sqlitePath = root.querySelector<HTMLElement>(
    '[data-testid="sqlite-path"]',
  );
  const sqliteCount = root.querySelector<HTMLElement>(
    '[data-testid="sqlite-count"]',
  );
  const sqliteSize = root.querySelector<HTMLElement>(
    '[data-testid="sqlite-size"]',
  );
  const sqliteWrite = root.querySelector<HTMLElement>(
    '[data-testid="sqlite-write"]',
  );
  const sqliteRead = root.querySelector<HTMLElement>(
    '[data-testid="sqlite-read"]',
  );
  const sqliteJournal = root.querySelector<HTMLElement>(
    '[data-testid="sqlite-journal"]',
  );
  const sqliteError = root.querySelector<HTMLElement>(
    '[data-testid="sqlite-error"]',
  );
  const sqliteNotes = root.querySelector<HTMLElement>(
    '[data-testid="sqlite-notes"]',
  );
  const pathsEl = root.querySelector<HTMLElement>('[data-testid="paths"]');
  const dbAsar = root.querySelector<HTMLElement>('[data-testid="db-asar"]');
  const benchTable = root.querySelector<HTMLElement>(
    '[data-testid="bench-table"]',
  );
  const eventsEl = root.querySelector<HTMLElement>('[data-testid="events"]');
  const status = root.querySelector<HTMLElement>('[data-testid="status"]');

  let state: Snapshot | null = null;

  function renderNotes(
    element: HTMLElement | null,
    notes: Snapshot["json"]["notes"],
  ): void {
    if (!element) return;
    element.innerHTML =
      notes.length === 0
        ? `<li class="muted small">暂无记录</li>`
        : notes
            .map(
              (note) => `
              <li class="note" data-testid="note-row">
                <span class="note-title">${escape(note.title)}</span>
                <span class="muted small">${escape(note.tags.join(" · "))} · ${time(Date.parse(note.updatedAt))}</span>
              </li>`,
            )
            .join("");
  }

  function renderJson(): void {
    if (!state) return;
    const info = state.json;
    if (jsonSource) {
      jsonSource.textContent = info.source;
      jsonSource.className = `tag ${sourceClass(info.source)}`;
    }
    if (jsonPath) jsonPath.textContent = "userData/json-store/store.json";
    if (jsonCount) jsonCount.textContent = String(info.count);
    if (jsonSize) jsonSize.textContent = bytes(info.size);
    if (jsonWrite) jsonWrite.textContent = `${info.writeMs} ms`;
    if (jsonRead) jsonRead.textContent = `${info.readMs} ms`;
    if (jsonBackup) jsonBackup.textContent = bytes(info.backupBytes);
    if (jsonTmp) jsonTmp.textContent = String(info.tmpFiles);
    if (jsonError)
      jsonError.textContent = info.error ? `恢复原因:${info.error}` : "";
    renderNotes(jsonNotes, info.notes);
  }

  function renderSqlite(): void {
    if (!state) return;
    const info = state.sqlite;
    if (sqliteAvailable) {
      sqliteAvailable.textContent = info.available ? "内置可用" : "不可用";
      sqliteAvailable.className = `tag ${info.available ? "ok" : "bad"}`;
    }
    if (sqlitePath) sqlitePath.textContent = "userData/hub.sqlite";
    if (sqliteCount) sqliteCount.textContent = String(info.count);
    if (sqliteSize) sqliteSize.textContent = bytes(info.size);
    if (sqliteWrite) sqliteWrite.textContent = `${info.writeMs} ms`;
    if (sqliteRead) sqliteRead.textContent = `${info.readMs} ms`;
    if (sqliteJournal) sqliteJournal.textContent = info.journalMode || "—";
    if (sqliteError) sqliteError.textContent = info.error || "";
    renderNotes(sqliteNotes, info.notes);
  }

  function renderPaths(): void {
    if (!state || !pathsEl) return;
    const p = state.paths;
    const rows: Array<[string, string]> = [
      ["userData", "userData/(可写)"],
      ["JSON", "userData/json-store/store.json"],
      ["SQLite", "userData/hub.sqlite"],
      ["appPath", "app/(只读,不可写)"],
      ["resources", "resources/(只读)"],
    ];
    pathsEl.innerHTML = rows
      .map(
        ([key, value]) => `
        <li><span>${key}</span><code>${escape(value)}</code></li>`,
      )
      .join("");
    if (dbAsar) {
      dbAsar.textContent = p.dbInAsar
        ? "数据库在 ASAR 内(错误)"
        : "数据库不在 ASAR";
      dbAsar.className = `tag ${p.dbInAsar ? "bad" : "ok"}`;
    }
  }

  function renderBench(): void {
    if (!benchTable || !state) return;
    const bench = state.bench;
    if (!bench) {
      benchTable.innerHTML = `<p class="muted small">尚未运行基准。点击 1,000 / 5,000 / 10,000 条。</p>`;
      return;
    }
    benchTable.innerHTML = `
      <table>
        <thead><tr><th>指标</th><th>JSON</th><th>SQLite</th></tr></thead>
        <tbody>
          <tr><td>写入</td><td data-testid="bench-json-write">${bench.json.writeMs} ms</td><td data-testid="bench-sqlite-write">${bench.sqlite.writeMs} ms</td></tr>
          <tr><td>读取</td><td>${bench.json.readMs} ms</td><td>${bench.sqlite.readMs} ms</td></tr>
          <tr><td>体积</td><td>${bytes(bench.json.bytes)}</td><td>${bytes(bench.sqlite.bytes)}</td></tr>
          <tr><td>日志</td><td>—</td><td>${bench.sqlite.journalMode}</td></tr>
        </tbody>
      </table>
      <div class="bench-meta muted small">${bench.count.toLocaleString()} 条 · JSON 写入 ${bench.json.writeMs}ms / SQLite 写入 ${bench.sqlite.writeMs}ms</div>`;
  }

  function renderEvents(): void {
    if (!eventsEl || !state) return;
    eventsEl.innerHTML =
      state.events.length === 0
        ? `<li class="muted small">暂无活动</li>`
        : state.events
            .slice(0, 8)
            .map(
              (row) => `
              <li class="event-row" data-testid="event-row">
                <span class="muted">${time(row.at)}</span>
                <span class="kind">${escape(row.kind)}</span>
                <span>${escape(row.detail)}</span>
              </li>`,
            )
            .join("");
  }

  function render(next: Snapshot): void {
    state = next;
    if (versions) {
      versions.textContent = `Electron ${next.electronVersion} · Node ${next.nodeVersion}`;
    }
    renderJson();
    renderSqlite();
    renderPaths();
    renderBench();
    renderEvents();
  }

  void window.api.store.snapshot().then(render);
  const unsubscribe = window.api.store.onEvent(() => {
    void window.api.store.snapshot().then(render);
  });

  const add = async (): Promise<void> => {
    render(
      await window.api.store.addNote(
        "来自界面的持久化记录:比较 JSON 原子写与 SQLite 事务。",
      ),
    );
  };
  root
    .querySelector<HTMLButtonElement>('[data-testid="json-add"]')
    ?.addEventListener("click", () => void add());
  root
    .querySelector<HTMLButtonElement>('[data-testid="sqlite-add"]')
    ?.addEventListener("click", () => void add());
  root
    .querySelector<HTMLButtonElement>('[data-testid="json-reload"]')
    ?.addEventListener("click", async () => {
      render(await window.api.store.reload());
    });
  root
    .querySelector<HTMLButtonElement>('[data-testid="sqlite-reload"]')
    ?.addEventListener("click", async () => {
      render(await window.api.store.reload());
    });
  root
    .querySelector<HTMLButtonElement>('[data-testid="json-corrupt"]')
    ?.addEventListener("click", async () => {
      render(await window.api.store.corrupt());
      if (status) status.textContent = "已模拟损坏并从 .bak 恢复";
    });
  root
    .querySelector<HTMLButtonElement>('[data-testid="refresh"]')
    ?.addEventListener("click", async () => {
      render(await window.api.store.refresh());
    });

  for (const count of [1000, 5000, 10000]) {
    root
      .querySelector<HTMLButtonElement>(`[data-testid="bench-${count}"]`)
      ?.addEventListener("click", async () => {
        render(await window.api.store.bench(count));
        if (status)
          status.textContent = `已完成 ${count.toLocaleString()} 条基准`;
      });
  }

  const sleep = (ms: number): Promise<void> =>
    new Promise((resolve) => setTimeout(resolve, ms));

  window.__prepareShots = async (stage) => {
    document.body.dataset.shot = stage;
    if (stage === "json") {
      render(
        await window.api.store.addNote(
          "截图记录:JSON 原子写把临时文件 rename 到 store.json,旧文件保留为 .bak。",
        ),
      );
      return;
    }
    if (stage === "sqlite") {
      render(
        await window.api.store.addNote(
          "截图记录:SQLite 使用 WAL 与事务,单写者顺序写入。",
        ),
      );
      return;
    }
    render(await window.api.store.bench(5000));
    await sleep(200);
  };

  window.__smoke = async () => {
    const api = window.api.store;
    const first = await api.snapshot();
    const afterAdd = await api.addNote("smoke 测试:新增一条持久化记录。");
    await sleep(80);
    const reloaded = await api.reload();
    const corrupt = await api.corrupt();
    const recovered = await api.addNote("smoke 测试:恢复后继续写入。");
    const bench = await api.bench(1000);
    const final = await api.refresh();

    unsubscribe();
    const benchValue = bench.bench;
    if (!benchValue) throw new Error("BENCH_MISSING");
    return {
      jsonCount: afterAdd.json.count,
      sqliteCount: afterAdd.sqlite.count,
      sqliteAvailable: first.sqlite.available,
      journalMode: first.sqlite.journalMode,
      source: reloaded.json.source,
      backupSource: corrupt.json.source,
      recoveredSource: recovered.json.source,
      jsonWriteMs: afterAdd.json.writeMs,
      jsonReadMs: afterAdd.json.readMs,
      sqliteWriteMs: afterAdd.sqlite.writeMs,
      sqliteReadMs: afterAdd.sqlite.readMs,
      jsonBytes: afterAdd.json.size,
      sqliteBytes: afterAdd.sqlite.size,
      tmpFiles: afterAdd.json.tmpFiles,
      dbInAsar: final.paths.dbInAsar,
      benchJsonMs: benchValue.json.writeMs,
      benchSqliteMs: benchValue.sqlite.writeMs,
      benchBytes: benchValue.sqlite.bytes,
      events: final.events.length,
    };
  };
}