示例工程 38-schema-migrations-concurrency
38-schema-migrations-concurrency/app/.tsc/src/App.js
function escape(text) {
return text.replace(/[&<>"]/g, (char) => {
if (char === "&")
return "&";
if (char === "<")
return "<";
if (char === ">")
return ">";
return """;
});
}
function time(at) {
return new Date(at).toLocaleTimeString("zh-CN", { hour12: false });
}
function ms(value) {
return `${value.toFixed(2)} ms`;
}
export function mountApp(root) {
root.innerHTML = `
<div class="app">
<header class="header">
<div class="brand">
<span class="logo">v3</span>
<div>
<h1>迁移与并发实验室</h1>
<span class="muted small">user_version · 单事务迁移 · 单写者队列 · SQLITE_BUSY</span>
</div>
</div>
<div class="header-side">
<span class="pill" data-testid="versions">—</span>
<button class="btn" data-testid="refresh">刷新 schema</button>
<span class="muted small" data-testid="status"></span>
</div>
</header>
<main class="layout">
<div class="column">
<section class="card pad migration-card">
<div class="card-head">
<h2>迁移</h2>
<span class="muted small" data-testid="schema-path">userData/lab.sqlite</span>
</div>
<div class="version-row">
<div><span>当前</span><b data-testid="schema-version">0</b></div>
<div><span>目标</span><b data-testid="schema-target">0</b></div>
<div><span>历史</span><b data-testid="history-count">0</b></div>
<div><span>表</span><b data-testid="table-count">0</b></div>
</div>
<div class="actions wrap">
<button class="btn primary" data-testid="migrate">再跑迁移</button>
<button class="btn" data-testid="fail-migration">失败迁移(回滚)</button>
<button class="btn danger" data-testid="reset">重建实验库</button>
</div>
<ul class="timeline" data-testid="migration-timeline"></ul>
<div class="failure" data-testid="failure-panel">
<span class="muted small">尚未运行失败迁移</span>
</div>
</section>
<section class="card pad">
<div class="card-head">
<h2>Schema</h2>
<span class="muted small">notes / events / schema_migrations</span>
</div>
<div class="chips" data-testid="schema-tables"></div>
<div class="columns" data-testid="schema-columns"></div>
<div class="counts">
<span>notes <b data-testid="notes-count">0</b></span>
<span>events <b data-testid="events-count">0</b></span>
<span>history <b data-testid="count-history">0</b></span>
</div>
</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 concurrency-card">
<div class="card-head">
<h2>并发写入</h2>
<span class="muted small">单写者队列把并发变成顺序</span>
</div>
<div class="actions wrap">
<button class="btn primary" data-testid="queue-run">并发写入 20 条</button>
<button class="btn" data-testid="contention-run">锁竞争实验</button>
</div>
<div class="queue-grid">
<span>完成</span><b data-testid="queue-count">0</b>
<span>序号范围</span><b data-testid="queue-range">—</b>
<span>耗时</span><b data-testid="queue-ms">—</b>
<span>队列剩余</span><b data-testid="queue-pending">0</b>
</div>
<div class="lock-box">
<div class="muted small">第二个连接在锁住时写入</div>
<div class="lock-message" data-testid="contention-message">尚未运行</div>
<div class="muted small">
错误码 <code data-testid="contention-code">—</code> · 等待
<b data-testid="contention-wait">—</b> · 回滚后重试
<b data-testid="contention-retry">—</b>
</div>
</div>
<p class="hint muted small">
第一个连接 BEGIN IMMEDIATE 持锁,第二个连接 busy_timeout=0 写入会收到
database is locked;回滚后同一连接重试成功。队列则让所有写操作在
主进程内串行执行。
</p>
</section>
<section class="card pad">
<div class="card-head">
<h2>本次迁移耗时</h2>
<span class="muted small">每一步一个事务</span>
</div>
<ul class="steps" data-testid="migration-steps"></ul>
</section>
<section class="card pad rules">
<div class="card-head">
<h2>规则</h2>
</div>
<ul class="bullets">
<li>一个版本一个事务:DDL + 数据回填 + user_version 一起提交。</li>
<li>迁移失败整步回滚,版本停在失败前;不要留下半套结构。</li>
<li>单写者:所有写请求进主进程队列,不把连接交给多个窗口。</li>
<li>WAL 与 busy_timeout 只是缓冲,重试与队列才是方案。</li>
</ul>
</section>
</div>
</main>
</div>
`;
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 = null;
function renderMigration() {
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
? `<li class="muted small">暂无迁移历史</li>`
: state.schema.history
.map((row) => `
<li class="timeline-row" data-testid="timeline-row">
<span class="version">v${row.version}</span>
<span>${escape(row.name)}</span>
<span class="muted small">${time(Date.parse(row.appliedAt))}</span>
</li>`)
.join("");
}
if (failurePanel) {
const failure = state.failure;
failurePanel.className = `failure ${failure ? "bad-panel" : ""}`;
if (!failure) {
failurePanel.innerHTML = `<span class="muted small">尚未运行失败迁移</span>`;
}
else {
failurePanel.innerHTML = `
<div class="failure-head">
<span class="tag bad" data-testid="failure-from">v${failure.from} → v${failure.to}</span>
<span class="muted small">步骤 v${failure.steps[0]?.version ?? "?"}</span>
</div>
<div class="failure-error" data-testid="failure-error">${escape(failure.error)}</div>
<div class="muted small">
title 列存在:<b data-testid="failure-title">${failure.titlePresent}</b> ·
回滚后 columns:${failure.columns.join(" / ")}
</div>`;
}
}
if (tablesEl) {
tablesEl.innerHTML = state.schema.tables
.map((table) => `<span class="chip">${escape(table)}</span>`)
.join("");
}
if (columnsEl) {
columnsEl.innerHTML = `<span class="muted small">notes:</span>${state.schema.columns
.map((column) => `<code class="col">${escape(column)}</code>`)
.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
? `<li class="muted small">本次没有待执行步骤(已是最新版本)</li>`
: steps
.map((step) => `
<li class="step-row">
<span class="tag ${step.applied ? "ok" : "bad"}">v${step.version}</span>
<span>${escape(step.name)}</span>
<span class="muted small">${ms(step.ms)}</span>
</li>`)
.join("");
}
}
function renderQueue() {
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() {
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) {
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) => 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,
};
};
}
//# sourceMappingURL=App.js.map