10.2 异步撤销与内存
10.1 的命令 do/undo 是同步的。但工业级编辑器的撤销命令常常天然异步:撤销「导入一张贴图」要等文件系统返回、撤销「触发重编译」要等编译管线跑完、撤销「写回磁盘」要等 I/O。这些命令的 do/undo 必须返回 Promise,撤销系统就得处理异步。
AsyncCommandStack 深化两点:
- 异步命令:
do/undo允许返回Promise<void>,栈await它们完成。 - busy 闸门:异步执行期间
#busy = true,并发 execute/undo/redo 一律被拒——撤销与重做交错执行是最隐蔽的状态破坏来源,闸门把栈串行化。 - 内存预算:每条命令
estimateBytes()报体积,栈按总字节记账;超预算从最老命令开始驱逐——撤销历史的内存有上限。
本章与站内既有内容的分工
| 主题 | 站内既有内容 | 本节做什么 |
|---|---|---|
| 同步命令栈 | 10.1 命令栈与事务 | 同步命令;本节升级为异步 do/undo |
| 事务 | 10.1 命令栈与事务 | 事务命令可异步;异步栈同样支持 |
| 内存控制 | 卷三 8.1 条数 + 字节预算 | 卷三按条数+字节预算;本节落地为 estimateBytes 记账 |
| 跨文档撤销 | 10.3 跨文档/跨会话撤销 | 异步栈管单文档;跨文档历史下节处理 |
为什么 busy 闸门必须存在
同步命令栈不会交错——每个调用在返回前完成。异步命令栈不同:execute(cmdA) 挂起在 await cmdA.do() 上时,用户可能又触发 execute(cmdB)。如果没有闸门,undo 会在 do 完成前执行——撤销的是「尚未完成的命令」,状态彻底错乱。
#busy 闸门把栈变成单飞:同一时刻最多一个命令在飞,其余调用返回 false 拒绝。代价是吞吐受限(并发场景要排队而不是拒绝),但对撤销系统这是对的取舍——正确性优先于吞吐。拒绝而不是排队,是为了让调用方显式决定「要不要重试」:脚本知道操作被拒,可以选择提示用户,而不是被无声吞掉。
内存预算:按字节驱逐
撤销历史是「活得越久越值钱」的数据——越老的历史越可能被回退到,理论上应该尽可能保留。但内存必须封顶。本节的策略是字节预算:estimateBytes() 让每条命令自报体积(拖一张大贴图的撤销可能占几 MB,改一个字段占几十字节),栈按总量记账,超预算从最老命令开始驱逐。
驱逐最老而不是最新,符合撤销的直觉:最近的操作最可能被撤销,最老的先牺牲。bytesUsed() 让调用方可以监控历史体积,把「撤销历史占用多少内存」变成一个可见、可观测的值。
对标撤销历史与异步边界
Godot 的 UndoRedo 提供动作记录、合并模式和历史上限设置。helio 本节的预算来自命令自报的字节估计,bytesUsed() 仅统计撤销侧,实际进程内存还包含重做历史和运行时开销。 Godot UndoRedo
示例等待命令完成后才迁移历史项。失败时可重试原命令,命令自身负责让外部副作用保持一致。
可运行产物:7 条用例
下面 src/async-undo.ts 层级 L1,完整可编译,命令 node --test test/10-2-merge-async-undo-memory.test.ts:
// file: src/async-undo.ts
// tier: L1
// verify: node --test test/10-2-merge-async-undo-memory.test.ts
//
// 撤销系统深化(第十章):异步撤销与内存预算。
// 工业级编辑器的撤销命令可能是异步的:资产导入、磁盘写回、编译触发。
// AsyncCommandStack 的 do/undo 允许返回 Promise,用 busy 闸门串行化——
// 并发执行被拒,避免撤销与重做交错。内存预算按 estimateBytes 记账,
// 超预算从最老命令开始驱逐,撤销历史的体积有上限,不会无限膨胀。
export interface AsyncCommand {
name: string;
estimateBytes(): number;
do(): Promise<void> | void;
undo(): Promise<void> | void;
}
export class AsyncCommandStack {
readonly #undo: AsyncCommand[] = [];
readonly #redo: AsyncCommand[] = [];
#budgetBytes: number;
#busy = false;
constructor(budgetBytes: number) { this.#budgetBytes = budgetBytes; }
/** 执行命令;busy 期间并发执行被拒。 */
async execute(cmd: AsyncCommand): Promise<boolean> {
if (this.#busy) return false;
this.#busy = true;
try { await cmd.do(); } finally { this.#busy = false; }
this.#redo.pop();
this.#undo.push(cmd);
this.#redo.length = 0;
this.#evict();
return true;
}
async undo(): Promise<boolean> {
if (this.#busy || this.#undo.length === 0) return false;
const cmd = this.#undo.at(-1)!;
this.#busy = true;
try { await cmd.undo(); } finally { this.#busy = false; }
this.#undo.pop();
this.#redo.push(cmd);
return true;
}
async redo(): Promise<boolean> {
if (this.#busy || this.#redo.length === 0) return false;
const cmd = this.#redo.at(-1)!;
this.#busy = true;
try { await cmd.do(); } finally { this.#busy = false; }
this.#redo.pop();
this.#undo.push(cmd);
return true;
}
undoCount(): number { return this.#undo.length; }
bytesUsed(): number { return this.#undo.reduce((sum, c) => sum + c.estimateBytes(), 0); }
/** 超预算时从最老命令开始驱逐,直到体积回到预算内。 */
#evict(): void {
let bytes = this.bytesUsed();
while (bytes > this.#budgetBytes && this.#undo.length > 0) {
bytes -= this.#undo.shift()!.estimateBytes();
}
}
}
try/finally 是 busy 闸门的关键:无论 await cmd.do() 成功还是抛错,#busy 都在 finally 里复位——命令失败也不能卡死撤销栈。#evict 逐条从最老命令扣体积,直到总量回到预算内;驱逐发生在 push 之后,所以新命令永远安全,牺牲的是旧历史。
可运行产物:7 条用例
下面是 test/10-2-merge-async-undo-memory.test.ts 层级 L1,命令 node --test test/10-2-merge-async-undo-memory.test.ts:
// file: test/10-2-merge-async-undo-memory.test.ts
// tier: L1
// verify: node --test test/10-2-merge-async-undo-memory.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { AsyncCommandStack } from '../src/async-undo.ts';
import type { AsyncCommand } from '../src/async-undo.ts';
const tick = () => Promise.resolve();
function setCmd(target: number[], idx: number, value: number, bytes: number): AsyncCommand {
let prev = 0;
return {
name: `set${idx}`,
estimateBytes: () => bytes,
async do() { prev = target[idx]; await tick(); target[idx] = value; },
async undo() { await tick(); target[idx] = prev; },
};
}
test('失败的撤销与重做保留原历史项', async () => {
const stack = new AsyncCommandStack(100);
let fail = false;
const attempt = () => { if (fail) throw new Error('operation failed'); };
await stack.execute({ name: 'retry', estimateBytes: () => 1, do: attempt, undo: attempt });
fail = true;
await assert.rejects(stack.undo(), /operation failed/);
fail = false;
assert.equal(await stack.undo(), true);
fail = true;
await assert.rejects(stack.redo(), /operation failed/);
fail = false;
assert.equal(await stack.redo(), true);
});
test('异步命令执行完成后可 undo 回滚', async () => {
const stack = new AsyncCommandStack(1000);
const a: number[] = [0];
assert.equal(await stack.execute(setCmd(a, 0, 7, 10)), true);
assert.equal(a[0], 7);
assert.equal(await stack.undo(), true);
assert.equal(a[0], 0);
});
test('多个异步命令 undo 逆序回放', async () => {
const stack = new AsyncCommandStack(1000);
const a: number[] = [0];
await stack.execute(setCmd(a, 0, 1, 10));
await stack.execute(setCmd(a, 0, 2, 10));
await stack.undo();
assert.equal(a[0], 1);
await stack.undo();
assert.equal(a[0], 0);
});
test('redo 恢复撤销的命令', async () => {
const stack = new AsyncCommandStack(1000);
const a: number[] = [0];
await stack.execute(setCmd(a, 0, 9, 10));
await stack.undo();
assert.equal(await stack.redo(), true);
assert.equal(a[0], 9);
});
test('busy 期间并发 execute 被拒', async () => {
const stack = new AsyncCommandStack(1000);
const a: number[] = [0];
let release!: () => void;
const gate = new Promise<void>((r) => { release = r; });
const held: AsyncCommand = {
name: 'held',
estimateBytes: () => 1,
do: () => gate, // 挂起
undo: () => {},
};
const p = stack.execute(held);
assert.equal(await stack.execute(setCmd(a, 0, 1, 10)), false); // busy
release!();
await p;
assert.equal(await stack.execute(setCmd(a, 0, 2, 10)), true); // 空闲后可执行
});
test('内存预算:超预算驱逐最老命令', async () => {
const stack = new AsyncCommandStack(100);
const a: number[] = [0];
await stack.execute(setCmd(a, 0, 1, 60));
await stack.execute(setCmd(a, 0, 2, 60)); // 120 > 100 → 驱逐最老
assert.equal(stack.undoCount(), 1);
assert.equal(stack.bytesUsed(), 60);
});
test('预算边界:刚好不超则不清除', async () => {
const stack = new AsyncCommandStack(100);
const a: number[] = [0];
await stack.execute(setCmd(a, 0, 1, 50));
await stack.execute(setCmd(a, 0, 2, 50)); // 恰好 100
assert.equal(stack.undoCount(), 2);
assert.equal(stack.bytesUsed(), 100);
});
本机实测(Node v26.5.0,node --test test/10-2-merge-async-undo-memory.test.ts):tests 7、pass 7、fail 0。
第四条验收 busy 闸门:held 命令挂起在 gate 上时,并发 execute 返回 false;释放 gate、await p 完成后栈恢复空闲,再执行成功——拒绝只是临时的,不是死锁。第五条验收字节驱逐:两条 60 字节命令超 100 预算,最老一条被驱逐,undoCount=1、bytesUsed=60。第六条钉住边界:恰好 100 不驱逐。
小结
- 异步命令让撤销栈原生支持 I/O:
do/undo返回 Promise,栈 await 完成。 - busy 闸门串行化:并发 execute/undo/redo 被拒,
try/finally保证失败也不卡死栈。 - 内存预算按
estimateBytes记账,超预算从最老命令驱逐——历史有上限、体积可观测。 - 对标 Unity/Godot:helio 的命令本身可异步(撤销一次导入是一等公民),字节预算比数量控制更精确。
- 下一节把撤销推进到全局:跨文档/跨会话撤销——统一历史 + 光标,undoFor(docId) 只撤指定文档。
阅读导航:上一节:10.1 命令栈与事务 · 下一节:10.3 跨文档/跨会话撤销 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。