import type { Snapshot } from "../shared/ipc";
function escape(text: string): string {
return text.replace(/[&<>"]/g, (char) => {
if (char === "&") return "&";
if (char === "<") return "<";
if (char === ">") return ">";
return """;
});
}
function time(at: number): string {
return new Date(at).toLocaleTimeString("zh-CN", { hour12: false });
}
function ms(value: number): string {
return `${value.toFixed(2)} ms`;
}
export function mountApp(root: HTMLElement): void {
root.innerHTML = `
迁移
userData/lab.sqlite
尚未运行失败迁移
Schema
notes / events / schema_migrations
notes 0
events 0
history 0
并发写入
单写者队列把并发变成顺序
完成0
序号范围—
耗时—
队列剩余0
第二个连接在锁住时写入
尚未运行
错误码 — · 等待
— · 回滚后重试
—
第一个连接 BEGIN IMMEDIATE 持锁,第二个连接 busy_timeout=0 写入会收到
database is locked;回滚后同一连接重试成功。队列则让所有写操作在
主进程内串行执行。
规则
- 一个版本一个事务:DDL + 数据回填 + user_version 一起提交。
- 迁移失败整步回滚,版本停在失败前;不要留下半套结构。
- 单写者:所有写请求进主进程队列,不把连接交给多个窗口。
- WAL 与 busy_timeout 只是缓冲,重试与队列才是方案。
`;
const versions = root.querySelector('[data-testid="versions"]');
const schemaPath = root.querySelector(
'[data-testid="schema-path"]',
);
const schemaVersion = root.querySelector(
'[data-testid="schema-version"]',
);
const schemaTarget = root.querySelector(
'[data-testid="schema-target"]',
);
const historyCount = root.querySelector(
'[data-testid="history-count"]',
);
const tableCount = root.querySelector(
'[data-testid="table-count"]',
);
const timeline = root.querySelector(
'[data-testid="migration-timeline"]',
);
const failurePanel = root.querySelector(
'[data-testid="failure-panel"]',
);
const tablesEl = root.querySelector(
'[data-testid="schema-tables"]',
);
const columnsEl = root.querySelector(
'[data-testid="schema-columns"]',
);
const notesCount = root.querySelector(
'[data-testid="notes-count"]',
);
const eventsCount = root.querySelector(
'[data-testid="events-count"]',
);
const countHistory = root.querySelector(
'[data-testid="count-history"]',
);
const stepsEl = root.querySelector(
'[data-testid="migration-steps"]',
);
const queueCount = root.querySelector(
'[data-testid="queue-count"]',
);
const queueRange = root.querySelector(
'[data-testid="queue-range"]',
);
const queueMs = root.querySelector('[data-testid="queue-ms"]');
const queuePending = root.querySelector(
'[data-testid="queue-pending"]',
);
const contentionMessage = root.querySelector(
'[data-testid="contention-message"]',
);
const contentionCode = root.querySelector(
'[data-testid="contention-code"]',
);
const contentionWait = root.querySelector(
'[data-testid="contention-wait"]',
);
const contentionRetry = root.querySelector(
'[data-testid="contention-retry"]',
);
const eventsEl = root.querySelector('[data-testid="events"]');
const status = root.querySelector('[data-testid="status"]');
let state: Snapshot | null = null;
function renderMigration(): void {
if (!state) return;
if (schemaPath) schemaPath.textContent = "userData/lab.sqlite";
if (schemaVersion) schemaVersion.textContent = `v${state.schema.version}`;
if (schemaTarget) schemaTarget.textContent = `v${state.schema.target}`;
if (historyCount)
historyCount.textContent = String(state.schema.counts.history);
if (tableCount) tableCount.textContent = String(state.schema.tables.length);
if (timeline) {
timeline.innerHTML =
state.schema.history.length === 0
? `暂无迁移历史`
: state.schema.history
.map(
(row) => `
v${row.version}
${escape(row.name)}
${time(Date.parse(row.appliedAt))}
`,
)
.join("");
}
if (failurePanel) {
const failure = state.failure;
failurePanel.className = `failure ${failure ? "bad-panel" : ""}`;
if (!failure) {
failurePanel.innerHTML = `尚未运行失败迁移`;
} else {
failurePanel.innerHTML = `
v${failure.from} → v${failure.to}
步骤 v${failure.steps[0]?.version ?? "?"}
${escape(failure.error)}
title 列存在:${failure.titlePresent} ·
回滚后 columns:${failure.columns.join(" / ")}
`;
}
}
if (tablesEl) {
tablesEl.innerHTML = state.schema.tables
.map((table) => `${escape(table)}`)
.join("");
}
if (columnsEl) {
columnsEl.innerHTML = `notes:${state.schema.columns
.map((column) => `${escape(column)}`)
.join("")}`;
}
if (notesCount) notesCount.textContent = String(state.schema.counts.notes);
if (eventsCount)
eventsCount.textContent = String(state.schema.counts.events);
if (countHistory)
countHistory.textContent = String(state.schema.counts.history);
if (stepsEl) {
const steps = state.migration?.steps ?? [];
stepsEl.innerHTML =
steps.length === 0
? `本次没有待执行步骤(已是最新版本)`
: steps
.map(
(step) => `
v${step.version}
${escape(step.name)}
${ms(step.ms)}
`,
)
.join("");
}
}
function renderQueue(): void {
if (!state) return;
const last = state.queue.last;
if (queueCount) queueCount.textContent = String(last?.count ?? 0);
if (queueRange) {
queueRange.textContent = last ? `${last.min} … ${last.max}` : "—";
}
if (queueMs) queueMs.textContent = last ? ms(last.ms) : "—";
if (queuePending) queuePending.textContent = String(state.queue.pending);
const lock = state.contention;
if (contentionMessage) {
contentionMessage.textContent = lock?.busyMessage || "尚未运行";
contentionMessage.className = `lock-message ${lock?.busyMessage ? "bad" : ""}`;
}
if (contentionCode) contentionCode.textContent = lock?.busyCode || "—";
if (contentionWait) {
contentionWait.textContent = lock ? ms(lock.waitedMs) : "—";
}
if (contentionRetry) {
contentionRetry.textContent = lock ? String(lock.retryOk) : "—";
contentionRetry.className = lock?.retryOk ? "ok" : "";
}
}
function renderEvents(): void {
if (!eventsEl || !state) return;
eventsEl.innerHTML =
state.events.length === 0
? `暂无活动`
: state.events
.slice(0, 8)
.map(
(row) => `
${time(row.at)}
${escape(row.kind)}
${escape(row.detail)}
`,
)
.join("");
}
function render(next: Snapshot): void {
state = next;
if (versions) {
versions.textContent = `Electron ${next.electronVersion} · Node ${next.nodeVersion}`;
}
renderMigration();
renderQueue();
renderEvents();
}
void window.api.schema.snapshot().then(render);
const unsubscribe = window.api.schema.onEvent(() => {
void window.api.schema.snapshot().then(render);
});
root
.querySelector('[data-testid="migrate"]')
?.addEventListener("click", async () => {
render(await window.api.schema.migrate());
if (status) status.textContent = "迁移已检查";
});
root
.querySelector('[data-testid="fail-migration"]')
?.addEventListener("click", async () => {
render(await window.api.schema.fail());
});
root
.querySelector('[data-testid="reset"]')
?.addEventListener("click", async () => {
render(await window.api.schema.reset());
});
root
.querySelector('[data-testid="queue-run"]')
?.addEventListener("click", async () => {
render(await window.api.schema.queueWrites(20));
});
root
.querySelector('[data-testid="contention-run"]')
?.addEventListener("click", async () => {
render(await window.api.schema.contention());
});
root
.querySelector('[data-testid="refresh"]')
?.addEventListener("click", async () => {
render(await window.api.schema.refresh());
});
const sleep = (msValue: number): Promise =>
new Promise((resolve) => setTimeout(resolve, msValue));
window.__prepareShots = async (stage) => {
document.body.dataset.shot = stage;
if (stage === "failure") {
render(await window.api.schema.fail());
return;
}
if (stage === "concurrency") {
await window.api.schema.queueWrites(20);
render(await window.api.schema.contention());
return;
}
render(await window.api.schema.snapshot());
await sleep(100);
};
window.__smoke = async () => {
const api = window.api.schema;
const first = await api.snapshot();
const migrated = await api.migrate();
const queued = await api.queueWrites(20);
const locked = await api.contention();
const failed = await api.fail();
const final = await api.refresh();
const order = queued.queue.last?.order ?? [];
const unique = new Set(order).size;
const failure = failed.failure;
unsubscribe();
return {
schemaVersion: first.schema.version,
history: first.schema.counts.history,
tables: first.schema.tables.length,
notes: first.schema.counts.notes,
idempotentApplied: migrated.migration?.applied ?? -1,
appliedTo: migrated.schema.version,
queueCount: queued.queue.last?.count ?? 0,
queueUnique: unique,
queueMin: queued.queue.last?.min ?? 0,
queueMax: queued.queue.last?.max ?? 0,
queuePending: queued.queue.pending,
queueMs: queued.queue.last?.ms ?? 0,
busyMessage: locked.contention?.busyMessage ?? "",
busyCode: locked.contention?.busyCode ?? "",
retryOk: locked.contention?.retryOk ?? false,
failFrom: failure?.from ?? 0,
failTo: failure?.to ?? 0,
failError: failure?.error ?? "",
failTitle: failure?.titlePresent ?? true,
failStep: failure?.steps[0]?.version ?? 0,
finalVersion: final.schema.version,
finalNotes: final.schema.counts.notes,
events: final.events.length,
};
};
}