docs(canvas): explain compute workers and display resource lifetimes

This commit is contained in:
2026-11-12 00:19:19 +08:00
parent af8e2fe76b
commit b471d88520
12 changed files with 136 additions and 0 deletions
+9
View File
@@ -1,5 +1,10 @@
/**
* 共享合作调度软预算,供导入、复制、恢复编码等逐项计算调用。
* 既按耗时判断,也按工作量兜底,避免粗粒度/倒退时钟让长任务一直不让出;单个不可分步骤仍由调用方限大小。
*/
import {fault} from '../canvas-core/values.ts';
/** 注入时钟、让出任务与目标时间片;它们不改变记录语义或操作身份。 */
export type ImportScheduling = {
now?: () => number;
yieldTask?: () => Promise<void>;
@@ -8,13 +13,16 @@ export type ImportScheduling = {
/** A soft time slice with a work threshold, even when the clock is coarse.
* The caller bounds each indivisible parse/decode operation separately. */
/** 默认6ms软目标;step 不一定产生 Promise,调用方须在返回等待值时真正 await/yield。 */
export function createImportBudget(signal: AbortSignal, options: ImportScheduling = {}) {
const budget = options.frameBudgetMs ?? 6;
if (!Number.isFinite(budget) || budget <= 0) throw fault('invalid_import_budget');
const now = options.now ?? (() => performance.now());
const yieldTask = options.yieldTask ?? (() => new Promise<void>(resolve => setTimeout(resolve, 0)));
// 每128工作单位才读一次时钟,减少高频开销;总量16384强制让出,不能因时间测不准而无限执行。
let started = now(), work = 0, unchecked = 0;
return {
/** 记工作量并按阈值检查取消/时间;达到预算或时间异常时让出,回来再验取消并重置时间片。 */
step(units = 1): Promise<void> | undefined {
work += units;
unchecked += units;
@@ -23,6 +31,7 @@ export function createImportBudget(signal: AbortSignal, options: ImportSchedulin
if (signal.aborted) throw fault('import_aborted');
const elapsed = now() - started;
if (work < 16384 && elapsed >= 0 && elapsed < budget) return;
// 这里的异步边界才实际交出执行权;预算是 cooperative,不能抢占前面已经运行的同步工作。
return (async () => {
await yieldTask();
if (signal.aborted) throw fault('import_aborted');