3.2 导入流水线:阶段与编排
一次导入不是一步。解一张 PSD:读文件、解压层、合层、缩图、生成 mip、写进缓存——每一步都可能失败,且失败原因各不相同。如果这一切写在一个函数里,错误只说「导入失败」,你根本不知道卡在哪一步。正确做法是把导入拆成有序阶段,阶段间用一份 context 传数据,任一阶段失败就点名它。
本节的 ImportPipeline:
add(stage):追加一个阶段(名字 + 处理函数),链式注册。run(ctx):按注册顺序执行;任一阶段失败即停止,返回{ ok: false, stage, error }。PipelineContext:路径、源资产、导入设置、以及阶段间共享的scratch。
本章与站内既有内容的分工
| 主题 | 站内既有内容 | 本节做什么 |
|---|---|---|
| 缓存与热重载 | helio 2.2 缓存、热重载与增量导入 | 那篇管缓存失效;本节管「一次导入的编排骨架」 |
| 导入器框架 | 3.1 导入器注册与分发 | 分发器选「谁导」,流水线定义「怎么导」 |
| 增量导入 | 2.2 增量导入与脏检测 | needsReimport 的输出喂给流水线跑 |
scratch:阶段间通信而不串扰
阶段之间怎么传数据?两个选择:让阶段 A 的返回直接喂给阶段 B(紧耦合),或者共用一份 scratch(松耦合)。流水线选后者:每个阶段读 ctx.scratch 里前人的成果、写自己的成果——阶段的顺序可以重排,只要它们读写的键不冲突。这是「读源→解码→写缓存」可以复用到纹理/模型/音频共用的原因:骨架一致,每类资产的阶段自己替换。
run 里每个阶段包一层 try/catch:失败立刻返回 { ok: false, stage, error },后续阶段不执行(测试第四条钉住)。「哪一步挂了」比「导入失败」有用得多——属性面板可以精确高亮出错的阶段,而不是让用户猜。
对标导入编排与回调
Unreal Interchange 使用可配置的管线栈处理导入。Unity 的 AssetPostprocessor 提供导入前后等钩子,OnPostprocessAllAssets 则接收一批资产变更。helio 将阶段作为有序任务执行,并在错误中记录当前阶段。示例中的阶段与第三方引擎回调没有一一对应关系。 Unreal Interchange
· Unity AssetPostprocessor
可运行产物:6 条用例
下面 src/import-pipeline.ts 层级 L1,完整可编译,命令 node --test test/03-2-import-pipeline-stages.test.ts:
// file: src/import-pipeline.ts
// tier: L1
// verify: node --test test/03-2-import-pipeline-stages.test.ts
//
// 资产管线(第三章):导入流水线。
// 一次导入不是一步:读源、预处理、转换、后处理、写缓存……每类资产共享
// 骨架、替换肌肉。ImportPipeline 把导入拆成有序阶段,阶段间通过 context
// 传递数据;任何一阶段失败则整条流水线停止,并报告失败发生在哪一阶段——
// 「哪一步挂了」比「导入失败」有用得多。
import type { SourceAsset } from './asset-model.ts';
export interface PipelineContext {
/** 源资产路径。 */
path: string;
/** 源资产(含内容哈希与类型)。 */
source: SourceAsset;
/** 导入设置(来自 meta)。 */
settings: Record<string, unknown>;
/** 阶段间传递的暂存数据。 */
scratch: Record<string, unknown>;
}
export interface Stage {
name: string;
run(ctx: PipelineContext): PipelineContext;
}
export type PipelineOutcome =
| { ok: true; result: PipelineContext }
| { ok: false; stage: string; error: string };
export class ImportPipeline {
readonly #stages: Stage[] = [];
/** 追加一个阶段;返回 this 支持链式。 */
add(stage: Stage): this {
this.#stages.push(stage);
return this;
}
/** 已注册阶段名(按顺序)。 */
stages(): string[] {
return this.#stages.map((s) => s.name);
}
/** 按注册顺序执行全部阶段;任一失败即停止并报告阶段名。 */
run(ctx: PipelineContext): PipelineOutcome {
let current = ctx;
for (const stage of this.#stages) {
try {
current = stage.run(current);
} catch (err) {
return { ok: false, stage: stage.name, error: String(err) };
}
}
return { ok: true, result: current };
}
}
注意 PipelineOutcome 是联合类型而不是「结果对象加个 ok 字段」:ok: false 的分支必然有 stage 和 error,ok: true 的分支必然有 result——调用方用类型守卫(if (out.ok))后,TS 会把多余字段收走,类型系统替你保证失败分支一定带着失败信息。
可运行产物:6 条用例
下面是 test/03-2-import-pipeline-stages.test.ts 层级 L1,命令 node --test test/03-2-import-pipeline-stages.test.ts:
// file: test/03-2-import-pipeline-stages.test.ts
// tier: L1
// verify: node --test test/03-2-import-pipeline-stages.test.ts
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { ImportPipeline, type PipelineContext } from '../src/import-pipeline.ts';
import { makeSourceAsset } from '../src/asset-model.ts';
const base = (): PipelineContext => ({
path: 'tex/hero.png',
source: makeSourceAsset('tex/hero.png', 'h1', 10, 0),
settings: {},
scratch: {},
});
test('空流水线直接通过,context 原样返回', () => {
const p = new ImportPipeline();
const out = p.run(base());
assert.equal(out.ok, true);
if (out.ok) assert.deepEqual(out.result.scratch, {});
});
test('阶段按注册顺序执行', () => {
const p = new ImportPipeline();
const order: string[] = [];
p.add({ name: 'read', run: (c) => { order.push('read'); return c; } });
p.add({ name: 'convert', run: (c) => { order.push('convert'); return c; } });
p.add({ name: 'write', run: (c) => { order.push('write'); return c; } });
p.run(base());
assert.deepEqual(order, ['read', 'convert', 'write']);
});
test('阶段通过 scratch 传递数据', () => {
const p = new ImportPipeline();
p.add({
name: 'decode',
run: (c) => ({ ...c, scratch: { ...c.scratch, pixels: 4096 } }),
});
p.add({
name: 'summarize',
run: (c) => ({ ...c, scratch: { ...c.scratch, note: `pixels=${c.scratch.pixels}` } }),
});
const out = p.run(base());
assert.equal(out.ok, true);
if (out.ok) assert.equal(out.result.scratch.note, 'pixels=4096');
});
test('阶段失败 → 报告失败阶段名与错误,后续不执行', () => {
const p = new ImportPipeline();
let ranAfter = false;
p.add({ name: 'decode', run: () => { throw new Error('格式不支持'); } });
p.add({ name: 'write', run: (c) => { ranAfter = true; return c; } });
const out = p.run(base());
assert.equal(out.ok, false);
if (!out.ok) {
assert.equal(out.stage, 'decode');
assert.match(out.error, /格式不支持/);
}
assert.equal(ranAfter, false);
});
test('add 返回 this,支持链式注册', () => {
const p = new ImportPipeline();
p.add({ name: 'a', run: (c) => c })
.add({ name: 'b', run: (c) => c });
assert.deepEqual(p.stages(), ['a', 'b']);
});
test('全部阶段成功 → ok true,context 带上最终 scratch', () => {
const p = new ImportPipeline();
p.add({ name: 'read', run: (c) => c });
p.add({ name: 'finalize', run: (c) => ({ ...c, scratch: { ...c.scratch, done: true } }) });
const out = p.run(base());
assert.equal(out.ok, true);
if (out.ok) assert.equal(out.result.scratch.done, true);
});
本机实测(Node v26.5.0,node --test test/03-2-import-pipeline-stages.test.ts):tests 6、pass 6、fail 0,耗时约 35 ms。
第二条钉住保序,第三条钉住 scratch 传数据,第四条是失败定位的完整验证——stage 精确到 decode,error 带着原始信息,且 write 阶段的标志位没有被置上(后续不执行)。
小结
- 一次导入拆成有序阶段:读源、预处理、转换、后处理、写缓存。
- 阶段间用
scratch传数据:松耦合、顺序可重排。 - 失败点名:
{ ok: false, stage, error },后续阶段不执行。 PipelineOutcome联合类型让类型系统保证失败分支带信息。- 下一节给导入器加扩展机制:可扩展导入器:插件与接管——
supports谓词、优先级路由、id 全局唯一。
阅读导航:上一节:3.1 导入器注册与分发 · 下一节:3.3 可扩展导入器:插件与接管 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。