示例工程 37-local-persistence
37-local-persistence/app/.tsc/main/index.js
import { app, BrowserWindow, ipcMain } from "electron";
import { randomUUID } from "node:crypto";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { runBenchmark } from "../shared/bench";
import { backupFile, jsonFile, jsonStoreSize, readJsonStore, seedNotes, writeJsonStore, } from "../shared/json-store";
import { assertAddNoteReq, assertBenchReq, CH, } from "../shared/ipc";
import { closeStore, countNotes, insertNote, journalMode, listNotes, openStore, seedIfEmpty, sqliteSize, } from "../shared/sqlite-store";
app.setName("Persistence 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(), `persistence-${isSmoke ? "smoke" : "shots"}-${process.pid}`)
: "";
if (tempData)
app.setPath("userData", tempData);
let win = null;
let db = null;
let sqliteError = "";
let jsonDoc = {
version: 1,
updatedAt: new Date(0).toISOString(),
items: [],
};
let jsonSource = "fallback";
let jsonError = "";
let jsonWriteMs = 0;
let jsonReadMs = 0;
let sqliteWriteMs = 0;
let sqliteReadMs = 0;
let lastBench = null;
let events = [];
const userData = app.getPath("userData");
const jsonDir = path.join(userData, "json-store");
const dbPath = path.join(userData, "hub.sqlite");
const benchDir = path.join(userData, "bench");
function log(kind, detail) {
events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40);
if (win && !win.isDestroyed()) {
win.webContents.send("store:event", { kind, detail, at: Date.now() });
}
}
function notesPreview(items) {
return [...items]
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
.slice(0, 3);
}
function jsonInfo() {
let backupBytes = 0;
try {
backupBytes = fsSync.statSync(backupFile(jsonDir)).size;
}
catch {
// 还没有备份。
}
let tmpFiles = 0;
try {
tmpFiles = fsSync
.readdirSync(jsonDir)
.filter((file) => file.includes(".tmp-")).length;
}
catch {
// 目录尚未创建。
}
return {
dir: jsonDir,
path: jsonFile(jsonDir),
backupPath: backupFile(jsonDir),
count: jsonDoc.items.length,
size: jsonStoreSize(jsonDir),
backupBytes,
source: jsonSource,
error: jsonError,
writeMs: Number(jsonWriteMs.toFixed(2)),
readMs: Number(jsonReadMs.toFixed(2)),
updatedAt: jsonDoc.updatedAt,
tmpFiles,
notes: notesPreview(jsonDoc.items),
};
}
function sqliteInfo() {
const available = db !== null;
let count = 0;
let mode = "";
let notes = [];
if (db) {
try {
count = countNotes(db);
mode = journalMode(db);
notes = listNotes(db, 3);
}
catch (error) {
sqliteError = error instanceof Error ? error.message : String(error);
}
}
return {
available,
path: dbPath,
count,
size: sqliteSize(dbPath),
journalMode: mode,
writeMs: Number(sqliteWriteMs.toFixed(2)),
readMs: Number(sqliteReadMs.toFixed(2)),
error: sqliteError,
notes,
};
}
function paths() {
const appPath = app.getAppPath();
return {
userData,
appPath,
resources: process.resourcesPath,
dbInAsar: dbPath.startsWith(appPath),
};
}
function snapshot() {
return {
platform: process.platform,
electronVersion: process.versions.electron,
nodeVersion: process.versions.node,
json: jsonInfo(),
sqlite: sqliteInfo(),
paths: paths(),
bench: lastBench,
events: events.map((row) => ({ ...row })),
};
}
function addNote(text) {
const now = new Date().toISOString();
const note = {
id: randomUUID(),
title: text.length > 40 ? `${text.slice(0, 40)}…` : text,
body: text,
tags: ["manual"],
updatedAt: now,
};
const next = {
version: 1,
updatedAt: now,
items: [...jsonDoc.items, note].slice(-10_000),
};
const written = writeJsonStore(jsonDir, next);
jsonDoc = next;
jsonSource = "main";
jsonError = "";
jsonWriteMs = written.writeMs;
if (db) {
const start = performance.now();
insertNote(db, note);
sqliteWriteMs = performance.now() - start;
}
log("write", `JSON ${written.writeMs.toFixed(2)}ms / SQLite ${sqliteWriteMs.toFixed(2)}ms`);
}
function reload() {
const read = readJsonStore(jsonDir);
jsonDoc = read.doc;
jsonSource = read.source;
jsonError = read.error;
jsonReadMs = read.readMs;
if (read.source === "backup") {
writeJsonStore(jsonDir, read.doc);
log("recover", `主文件损坏,已从备份恢复 ${read.doc.items.length} 条`);
}
if (db) {
const start = performance.now();
countNotes(db);
sqliteReadMs = performance.now() - start;
}
log("read", `JSON ${read.readMs.toFixed(2)}ms · ${read.source}`);
}
function corruptJson() {
const main = jsonFile(jsonDir);
if (!fsSync.existsSync(main)) {
throw new Error("JSON_NOT_FOUND");
}
fsSync.copyFileSync(main, backupFile(jsonDir));
fsSync.writeFileSync(main, '{ "version": 1, "items": [', "utf8");
jsonSource = "main";
jsonError = "INVALID_JSON";
log("corrupt", "主文件已写入半截 JSON,准备从 .bak 恢复");
reload();
}
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,
},
});
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) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function evalRenderer(window, code) {
let lastError = null;
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
return (await window.webContents.executeJavaScript(code));
}
catch (error) {
lastError = error;
await delay(200);
}
}
throw lastError instanceof Error ? lastError : new Error(String(lastError));
}
async function waitForRenderer(window) {
for (let attempt = 0; attempt < 160; attempt += 1) {
if (window.isDestroyed())
return;
try {
const ready = await evalRenderer(window, "typeof window.__smoke === 'function'");
if (ready)
return;
}
catch {
// 页面仍在加载。
}
await delay(100);
}
throw new Error("renderer did not become ready");
}
async function runSmoke(window) {
try {
await waitForRenderer(window);
await delay(700);
await waitForRenderer(window);
const result = await evalRenderer(window, "window.__smoke()");
process.stdout.write(`${JSON.stringify({
evt: "smoke",
ok: result.jsonCount >= 5 &&
result.sqliteCount >= 5 &&
result.sqliteAvailable &&
result.journalMode === "wal" &&
result.source === "main" &&
result.backupSource === "backup" &&
result.recoveredSource === "main" &&
result.jsonWriteMs >= 0 &&
result.jsonReadMs >= 0 &&
result.sqliteWriteMs >= 0 &&
result.sqliteReadMs >= 0 &&
result.jsonBytes > 0 &&
result.sqliteBytes > 0 &&
result.tmpFiles === 0 &&
result.dbInAsar === false &&
result.benchJsonMs > 0 &&
result.benchSqliteMs > 0 &&
result.benchBytes > 0 &&
result.events >= 6,
...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, 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/37-local-persistence");
fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
await waitForRenderer(window);
await delay(700);
await waitForRenderer(window);
await evalRenderer(window, `window.__prepareShots("json")`);
await delay(400);
await capture(window, dir, "37-01-json.png");
await evalRenderer(window, `window.__prepareShots("sqlite")`);
await delay(400);
await capture(window, dir, "37-02-sqlite.png");
await evalRenderer(window, `window.__prepareShots("bench")`);
await delay(700);
await capture(window, dir, "37-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.addNote, (_event, raw) => {
assertAddNoteReq(raw);
addNote(raw.text);
return snapshot();
});
ipcMain.handle(CH.reload, () => {
reload();
return snapshot();
});
ipcMain.handle(CH.corrupt, () => {
corruptJson();
return snapshot();
});
ipcMain.handle(CH.bench, (_event, raw) => {
assertBenchReq(raw);
lastBench = runBenchmark(benchDir, raw.count);
log("bench", `${raw.count} 条:JSON ${lastBench.json.writeMs}ms / SQLite ${lastBench.sqlite.writeMs}ms`);
return snapshot();
});
ipcMain.handle(CH.refresh, () => {
reload();
log("refresh", "已重新读取两个存储");
return snapshot();
});
app.whenReady().then(() => {
const seed = seedNotes();
const read = readJsonStore(jsonDir);
if (read.source === "fallback" || read.doc.items.length === 0) {
jsonDoc = {
version: 1,
updatedAt: new Date().toISOString(),
items: seed,
};
const written = writeJsonStore(jsonDir, jsonDoc);
jsonWriteMs = written.writeMs;
jsonSource = "seed";
log("seed", `JSON 已初始化 ${seed.length} 条`);
}
else {
jsonDoc = read.doc;
jsonSource = read.source;
jsonError = read.error;
jsonReadMs = read.readMs;
if (read.source === "backup") {
writeJsonStore(jsonDir, read.doc);
log("recover", "启动时从 .bak 恢复 JSON");
}
}
try {
db = openStore(dbPath);
const seeded = seedIfEmpty(db, seed);
log("sqlite", `SQLite 打开成功 · WAL · 新增 ${seeded} 条`);
}
catch (error) {
sqliteError = error instanceof Error ? error.message : String(error);
db = null;
log("sqlite-error", sqliteError);
}
const window = createWindow();
if (isSmoke) {
void runSmoke(window);
}
else if (isShots) {
void runShots(window);
}
});
app.on("will-quit", () => {
closeStore(db);
db = null;
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