docs(canvas): explain import execution and lazy copy source recovery

This commit is contained in:
2026-11-12 00:37:50 +08:00
parent 72e84a6cc1
commit 06a422045f
8 changed files with 163 additions and 0 deletions
+15
View File
@@ -1,8 +1,14 @@
/**
* 复制规划器的合作调度适配,不读live editor getter、不发布文档、不访问网络。
* 完整同步生成器、可恢复语义状态机、lazy输出准备分别提供显式入口,不能把准备完成当成内容已加入。
* 所有时间片都是软目标,持久源/映射/检查点与提交前外部身份复核由调用者负责。
*/
import { createDuplicatePlanner, type DuplicateCheckpoint } from '../canvas-core/duplicate-checkpoint.ts';
import type { Document, Registry, Target } from '../canvas-core/types.ts';
import { planDuplicateSteps, type DuplicateOptions, type DuplicatePlan } from '../canvas-core/duplicate.ts';
import { clone, fault, freeze } from '../canvas-core/values.ts';
/** 可注入取消、每片时间/步数和让出端口;checkpoint在完整规划适配中只报告累计语义步数。 */
export type DuplicateScheduling = {
readonly signal?: AbortSignal;
readonly checkpoint?: (steps:number) => Promise<void>;
@@ -17,13 +23,16 @@ export type DuplicateScheduling = {
* No document publication or network effects. The caller must persist source/mapping and
* revalidate external identities before applying a plan; this is not the import executor.
*/
/** 分片消费完整plan迭代器,每片默认6ms/512步;返回前全部记录已生成并校验,但不执行导入。 */
export async function planDuplicateAsync(document: Document, registry: Registry, selection: readonly Target[], options: DuplicateOptions, scheduling: DuplicateScheduling = {}): Promise<DuplicatePlan> {
const budget = scheduling.frameBudgetMs ?? 6, limit = scheduling.maxStepsPerSlice ?? 512;
if (!Number.isFinite(budget) || budget <= 0 || !Number.isSafeInteger(limit) || limit < 1) throw fault('invalid_copy_budget');
const signal = scheduling.signal, now = scheduling.now ?? (() => performance.now()), yieldTask = scheduling.yieldTask ?? (() => new Promise<void>(resolve => setTimeout(resolve, 0)));
/** 在迭代、checkpoint和yield边界检查取消,避免迟到准备结果被宿主继续采用。 */
const check = () => { if (signal?.aborted) throw fault('copy_aborted'); };
check();
// Capture caller-owned small inputs before the first await. Document/registry are immutable core snapshots.
// 首次await前捕获选区/偏移/预留映射,源document与registry按不可变快照合同使用。
const targets = freeze(clone(selection)), settings: DuplicateOptions = Object.freeze({ createId: options.createId, ...(options.worldOffset ? {worldOffset: freeze(clone(options.worldOffset))} : {}), ...(options.mapping ? {mapping: freeze(clone(options.mapping))} : {}) });
const steps = planDuplicateSteps(document, registry, targets, settings);
let completedSteps=0;
@@ -41,6 +50,7 @@ export async function planDuplicateAsync(document: Document, registry: Registry,
if(scheduling.checkpoint)await scheduling.checkpoint(completedSteps);
check();await yieldTask();
}
// 成功/失败/取消都关闭生成器,释放其持有的源快照/临时索引引用。
} finally {
// Release snapshot references after cancellation or host scheduling failures.
steps.return(undefined as never);
@@ -48,6 +58,7 @@ export async function planDuplicateAsync(document: Document, registry: Registry,
}
/** Resume semantic planning cursors. Source/output validation and derived output caches are rebuilt. */
/** 以完整checkpoint恢复语义游标,仍重做源验证/派生输出缓存,不声称从任意字节零重算。 */
export async function planDuplicateResumable(document:Document,registry:Registry,selection:readonly Target[],options:DuplicateOptions,binding:{sourceToken:string;schemaToken:string;checkpoint?:DuplicateCheckpoint},scheduling:Omit<DuplicateScheduling,'checkpoint'>&{checkpoint?:(state:DuplicateCheckpoint)=>Promise<void>}={}):Promise<DuplicatePlan>{
const budget=scheduling.frameBudgetMs??6,limit=scheduling.maxStepsPerSlice??512,now=scheduling.now??(()=>performance.now()),yieldTask=scheduling.yieldTask??(()=>new Promise<void>(resolve=>setTimeout(resolve,0)));
if(!Number.isFinite(budget)||budget<=0||!Number.isSafeInteger(limit)||limit<1)throw fault('invalid_copy_budget');
@@ -62,18 +73,22 @@ export async function planDuplicateResumable(document:Document,registry:Registry
/** Stop before record conversion: the stable order/mappings are sufficient for seekable lazy output. */
/** 只推进到emit起点:范围/顺序/全部新ID已固定,但尚未转换全部payload,可交lazy source逐条输出。 */
export async function prepareDuplicateStream(document:Document,registry:Registry,selection:readonly Target[],options:DuplicateOptions,binding:{sourceToken:string;schemaToken:string;checkpoint?:DuplicateCheckpoint;topologyOnly?:boolean},scheduling:Omit<DuplicateScheduling,'checkpoint'>&{checkpoint?:(state:DuplicateCheckpoint)=>Promise<void>;checkpointIntervalMs?:number;maxStepsPerCheckpoint?:number}={}):Promise<DuplicateCheckpoint>{
const budget=scheduling.frameBudgetMs??6,limit=scheduling.maxStepsPerSlice??512,now=scheduling.now??(()=>performance.now()),yieldTask=scheduling.yieldTask??(()=>new Promise<void>(resolve=>setTimeout(resolve,0)));
if(!Number.isFinite(budget)||budget<=0||!Number.isSafeInteger(limit)||limit<1)throw fault('invalid_copy_budget');
const check=()=>{if(scheduling.signal?.aborted)throw fault('copy_aborted');};check();
// 检查点保存频率与UI时间片分开:阶段变化、首次分配、工作量/时间阈值或时钟异常均触发保存。
const interval=scheduling.checkpointIntervalMs??0,maxCheckpointSteps=scheduling.maxStepsPerCheckpoint??8192;
if(!Number.isFinite(interval)||interval<0||!Number.isSafeInteger(maxCheckpointSteps)||maxCheckpointSteps<1)throw fault('invalid_copy_budget');
const planner=createDuplicatePlanner(document,registry,selection,options,binding);
// savedSteps等只记录上次已等待checkpoint回调成功的位置,保存耗时不冒充新增规划工作。
let savedPhase:DuplicateCheckpoint['phase']|undefined,savedSteps=binding.checkpoint?.steps??0,savedAllocated=(binding.checkpoint?.elementIds.length??0)+(binding.checkpoint?.canvasIds.length??0),savedAt=now();
while(true){
const start=now();let count=0;
do{check();if(planner.ready()){const state=planner.checkpoint();if(interval&&scheduling.checkpoint){await scheduling.checkpoint(state);check();}return state;}if(planner.step())throw fault('invalid_copy_stream_checkpoint');count++;}while(count<limit&&now()-start<budget);
if(scheduling.checkpoint){
// 避免每次UI让出都必须编码/落盘一个大检查点,同时为长准备保留明确的恢复边界。
const progress=planner.progress(),at=now(),elapsed=at-savedAt;
if(!interval||progress.phase!==savedPhase||!savedAllocated&&progress.allocated>0||!Number.isFinite(elapsed)||elapsed<0||elapsed>=interval||progress.steps-savedSteps>=maxCheckpointSteps){
await scheduling.checkpoint(planner.checkpoint());