2.2 启动、关闭与热装卸
上一节的 buildOrder() 只回答了「谁先谁后」。但一个内核真正要处理的是状态:模块不只「被列出来」,它要被 init(初始化数据)、start(开始服务)、再在关编辑器时 stop(停服务)、shutdown(清理资源)。顺序仍然关键——但这次是两个方向的顺序:启动时被依赖者在前,关闭时依赖者在先(否则你先把资产数据库关了,内容浏览器还在它头上要数据)。
本节在此基础上加最难的一环:热装卸。编辑器会话进行到一半,用户装了一个新插件——新模块要在不改动已运行模块的前提下插进内核。这有几个微妙的边界,全部来自同一条原则:已经启动的模块不会重启。于是——
- 新模块可以依赖已运行模块(它们还在,没问题);
- 但新模块不能被已运行模块依赖——它本该更早启动,现在晚了,先启动的模块不会重跑;
- 卸载同理:仍被运行模块依赖的模块不允许卸,否则依赖者悬空。
本章与站内既有内容的分工
第 2 章连续两节构成内核的运行骨架;站内无模块生命周期篇章。
| 主题 | 站内既有内容 | 本节做什么 |
|---|---|---|
| 注册与拓扑 | 2.1 模块注册与依赖拓扑 | 给排序加上执行:四阶段生命周期 + 热装卸 |
| 脚本热重载 | 卷四 6 脚本热重载与域重载 | 热装卸是「模块层」的重载,脚本热重载是「代码层」的,第 4 卷深入 |
| 编辑器启动 | 站内无 | 本节的 BootManager 是编辑器主进程启动的最小实现 |
四阶段生命周期,两个方向
BootManager 在 ModuleRegistry 之上叠加行为,核心是两个循环:
- boot():
buildOrder()算一次,然后按序对每个模块依次init、start,加进#running运行集。有环、或已启动过,都拒绝——幂等是一种美德,双击启动菜单不该二启。 - shutdown():对
buildOrder()的结果逆序,依次stop、shutdown,移出运行集。
事件都被记进 #events,这是最有价值的部分:它把「顺序对不对」变成可断言的时序,而不是靠日志肉眼看。测试里断言 b.shutdown 在 a.shutdown 之前发生,就是靠读事件序列。
对标模块与扩展的生命周期
Unreal 模块提供启动与关闭回调,并可按需加载。是否能安全卸载还取决于资源、引用和回调的清理。Unreal Engine Modules
Unity 的程序集引用和脚本域重载属于不同层面。Godot 插件可在进入与退出场景树时注册及清理编辑器贡献。Cocos Creator 扩展的启停也应与代码替换、状态迁移分别讨论。helio 示例验证的是依赖顺序和生命周期回调。
可运行产物:7 条用例钉住启动序与热装卸
下面 src/module-boot.ts 层级 L1,完整可编译,命令 node --test test/02-2-module-boot-shutdown.test.ts:
// file: src/module-boot.ts
// tier: L1
// verify: node --test test/02-2-module-boot-shutdown.test.ts
//
// 插件化内核(第二章):启动、关闭与热装卸。
// BootManager 在 ModuleRegistry 的拓扑排序之上定义四阶段生命周期
// (init/start 按拓扑序、stop/shutdown 逆序),并支持运行期装载/卸载:
// - load:新模块不能是某个已运行模块的依赖,否则已运行模块需重启;
// - unload:仍被运行模块依赖的模块不允许卸载。
import type { ModuleDef, ModuleRegistry } from './module-registry.ts';
export type Phase = 'init' | 'start' | 'stop' | 'shutdown';
export interface BootEvent {
module: string;
phase: Phase;
}
export class BootManager {
readonly #registry: ModuleRegistry;
#running = new Set<string>();
#events: BootEvent[] = [];
#booted = false;
constructor(registry: ModuleRegistry) { this.#registry = registry; }
running(): string[] { return [...this.#running]; }
events(): BootEvent[] { return [...this.#events]; }
/** 启动:先拓扑排序,再按序 init + start。有环或已启动则拒绝。 */
boot(): boolean {
const order = this.#registry.buildOrder();
if (!order || this.#booted) return false;
for (const id of order) {
this.#events.push({ module: id, phase: 'init' });
this.#events.push({ module: id, phase: 'start' });
this.#running.add(id);
}
this.#booted = true;
return true;
}
/** 关闭:逆序 stop + shutdown,清空运行集。 */
shutdown(): void {
const order = this.#registry.buildOrder() ?? [];
for (const id of [...order].reverse()) {
if (!this.#running.has(id)) continue;
this.#events.push({ module: id, phase: 'stop' });
this.#events.push({ module: id, phase: 'shutdown' });
this.#running.delete(id);
}
this.#booted = false;
}
/** 运行期装载:注册模块,只对本次新增的模块 init/start。 */
load(def: ModuleDef): boolean {
if (!this.#booted) return this.#registry.register(def);
if (!this.#registry.register(def)) return false;
// 新模块不能是某个已运行模块的依赖,否则已运行模块不会重启、顺序就乱了
const blocking = this.#registry.dependentsOf(def.id).find((d) => this.#running.has(d));
if (blocking) {
this.#registry.unregister(def.id);
return false;
}
const order = this.#registry.buildOrder();
if (!order) { this.#registry.unregister(def.id); return false; }
for (const id of order) {
if (this.#running.has(id)) continue;
this.#events.push({ module: id, phase: 'init' });
this.#events.push({ module: id, phase: 'start' });
this.#running.add(id);
}
return true;
}
/** 运行期卸载:无运行模块依赖它时逆序收尾并移除。 */
unload(id: string): boolean {
if (!this.#booted) return this.#registry.unregister(id);
if (!this.#running.has(id)) return false;
const dependents = this.#registry.dependentsOf(id).filter((d) => this.#running.has(d));
if (dependents.length > 0) return false;
this.#events.push({ module: id, phase: 'stop' });
this.#events.push({ module: id, phase: 'shutdown' });
this.#running.delete(id);
return this.#registry.unregister(id);
}
}
load 的实现细节值得拆开:它先 register 试探,再检查「是否被已运行模块依赖」,检查不过就 unregister 回滚——试探 + 回滚是这个阶段的主旋律。因为热装载可能失败(环、依赖冲突),内核必须先验证再承诺,失败了要把注册表恢复原状。unload 同样:先看运行集里有没有依赖者,有就拒绝,绝不让一个还在被人用的模块消失。
可运行产物:7 条用例
下面是 test/02-2-module-boot-shutdown.test.ts 层级 L1,命令 node --test test/02-2-module-boot-shutdown.test.ts:
// file: test/02-2-module-boot-shutdown.test.ts
// tier: L1
// verify: node --test test/02-2-module-boot-shutdown.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { ModuleRegistry } from '../src/module-registry.ts';
import { BootManager } from '../src/module-boot.ts';
function seededRegistry(): ModuleRegistry {
const r = new ModuleRegistry();
r.register({ id: 'a', deps: [] });
r.register({ id: 'b', deps: ['a'] });
r.register({ id: 'c', deps: ['b'] });
return r;
}
test('boot 按拓扑序 init/start,运行集为全部模块', () => {
const m = new BootManager(seededRegistry());
assert.equal(m.boot(), true);
assert.deepEqual(m.running(), ['a', 'b', 'c']);
const phases = m.events().map((e) => `${e.module}:${e.phase}`);
assert.deepEqual(phases, ['a:init', 'a:start', 'b:init', 'b:start', 'c:init', 'c:start']);
});
test('有环时拒绝启动', () => {
const r = new ModuleRegistry();
r.register({ id: 'x', deps: ['y'] });
r.register({ id: 'y', deps: ['x'] });
const m = new BootManager(r);
assert.equal(m.boot(), false);
assert.deepEqual(m.running(), []);
});
test('shutdown 逆序收尾,运行集清空', () => {
const m = new BootManager(seededRegistry());
m.boot();
m.shutdown();
assert.deepEqual(m.running(), []);
const shutdowns = m.events().filter((e) => e.phase === 'shutdown').map((e) => e.module);
assert.deepEqual(shutdowns, ['c', 'b', 'a']);
});
test('boot 幂等:二次启动被拒绝', () => {
const m = new BootManager(seededRegistry());
assert.equal(m.boot(), true);
assert.equal(m.boot(), false);
});
test('load 新模块只启新增部分,不影响已运行模块', () => {
const m = new BootManager(seededRegistry());
m.boot();
assert.equal(m.load({ id: 'd', deps: ['c'] }), true);
assert.deepEqual(m.running(), ['a', 'b', 'c', 'd']);
const afterLoad = m.events().slice(-2).map((e) => e.phase);
assert.deepEqual(afterLoad, ['init', 'start']);
});
test('load 被已运行模块依赖的新模块被拒绝', () => {
const r = new ModuleRegistry();
// a 声明依赖 x,但 x 尚未注册(缺失依赖被忽略,boot 照常成功)
r.register({ id: 'a', deps: ['x'] });
r.register({ id: 'b', deps: ['a'] });
const m = new BootManager(r);
m.boot();
// 现在才装载 x:x 被已运行的 a 依赖,x 本该先于 a 启动,但 a 不会重启,因此拒绝
assert.equal(m.load({ id: 'x', deps: [] }), false);
assert.deepEqual(m.running(), ['a', 'b']);
});
test('unload 有运行依赖者被拒绝,无依赖者可卸载', () => {
const m = new BootManager(seededRegistry());
m.boot();
assert.equal(m.unload('a'), false); // b/c 依赖 a 且都在运行
assert.equal(m.unload('c'), true);
assert.deepEqual(m.running(), ['a', 'b']);
});
本机实测(Node v26.5.0,node --test test/02-2-module-boot-shutdown.test.ts):tests 7、pass 7、fail 0,耗时约 90 ms。
第 6 条是本节最难也是最容易漏的:它构造了一个「运行期才发现被依赖者」的场景——a 早就声明依赖 x,但 x 一直没注册,boot 靠「缺失依赖忽略」照常跑起来;用户中途装了 x,内核必须识破「x 本该先于 a 启动但 a 不会重启」,果断拒绝。这条用例把上一节故意留的「缺失依赖忽略」策略和本节的热装载规则接在一起,是两节内容真正的缝合点。
小结
- 生命周期是两个方向:init/start 按拓扑序,stop/shutdown 逆序——依赖者在先关闭。
#events把顺序变成可断言的时序,测试直接读事件序列而不是看日志。- 热装卸的两条边界来自同一条原则「已启动模块不重启」:新模块不能被已运行模块依赖;仍被依赖的模块不可卸载。实现走试探 + 回滚。
- 下一节把第 2 章的内核放到整个行业里:对标 UE Modules 与 Unity 程序集,看四种插件系统在依赖声明、加载次序、热装载上的真实取舍。
阅读导航:上一节:2.1 模块注册与依赖拓扑 · 下一节:2.3 对标:UE Modules 与 Unity 程序集 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。