/** * runtime 表的只读分桶订阅。所有通道共享一个上游监听,依赖签名由表对象身份/布尔值组成, * 不在每个 hook 缓存整份 Root。读取缓存与通知基线分开,提前 getSnapshot 不会吞掉随后应有的通知。 */ import type {Id} from '../canvas-core/types.ts'; import type {EngineSnapshot} from '../canvas-runtime/contracts.ts'; import type {OperationRecord,FrozenRequest} from '../canvas-runtime/ledger.ts'; import type {ResourceRecord} from '../canvas-runtime/resources.ts'; import type {SharedAssetBinding} from '../canvas-runtime/asset-depot.ts'; import {equal} from '../canvas-core/values.ts'; import type {ExternalSource} from './selectors.ts'; /** 单个逻辑操作及它绑定的冻结请求;未知 operation ID 返回 undefined。 */ export type OperationView={readonly operation:OperationRecord;readonly request?:FrozenRequest}|undefined; /** 本地上传资源与共享仓库绑定两个来源槽位;这里仅给元数据,不获取显示 URL。 */ export type AssetMetadata={readonly record:ResourceRecord|undefined;readonly binding:SharedAssetBinding|undefined}; /** pending 按未决操作计数;blocked/unknown 还包含请求层情况,不是互斥的节点数量。 */ export type SyncCounts={readonly pending:number;readonly blocked:number;readonly unknown:number;readonly loading:boolean}; /** 只允许对象身份、布尔值与 undefined 作为本模块依赖,避免重新序列化整个业务表。 */ type Dependencies=readonly(object|boolean|undefined)[]; /** Read-only table projections: one upstream listener, no per-hook Root/table snapshots. */ /** 装配 operation/asset/counts 三类通道,首次订阅连上游,最后一个通道离开后断开。 */ export function createRuntimeSources(source:ExternalSource){ // 每个 group 负责自己的桶更新,上游先推进所有组,再运行去重后的外部通知。 type Group={update(root:EngineSnapshot,notifications:Set<()=>void>):void}; const active=new Set(),identities=new WeakMap();let nextIdentity=0,stop:(()=>void)|undefined; /** 对象用弱身份编号,undefined/布尔值用固定标记;WeakMap 不强留已被替换的表。 */ function signature(values:Dependencies){return values.map(value=>{if(value===undefined)return'u';if(typeof value==='boolean')return value?'t':'f';let id=identities.get(value);if(id===undefined){id=++nextIdentity;identities.set(value,id);}return`o${id}`;}).join(':');} /** 同一根下所有 group 更新完才通知;单监听器抛错不跳过其余监听,最后重抛首错。 */ function changed(){ if(!active.size)return;const root=source.getSnapshot(),notifications=new Set<()=>void>(); for(const group of active)group.update(root,notifications); let failed=false,error:unknown;for(const notify of notifications)try{notify();}catch(caught){if(!failed){failed=true;error=caught;}}if(failed)throw error; } /** 为共享依赖的一类按键查询创建桶。依赖不变跳过计算,失败桶即使签名未变仍可重新尝试。 */ function group(dependencies:(root:EngineSnapshot)=>Dependencies,read:(root:EngineSnapshot,key:K)=>V){ // Direct reads may precede notification, so read caches cannot replace observed baselines. // cached 服务即时读取,observed 是上次通知基线;两者不能合并,否则渲染提前读取会漏通知。 type Bucket={cached:V;cachedSignature:string;observed:V;listeners:Set<()=>void>}; const buckets=new Map(),failed=new Set();let observedSignature:string|undefined; /** 依赖戳改变才重算,并按值复用旧引用,确保外部存储读取身份稳定。 */ function readCached(root:EngineSnapshot,key:K,bucket:Bucket,stamp:string){ if(bucket.cachedSignature!==stamp){const value=read(root,key);if(!equal(bucket.cached,value))bucket.cached=value;bucket.cachedSignature=stamp;} return bucket.cached; } // 只更新有订阅的键;失败时仍通知使用方,让其读取/错误边界重新解释,不造一个成功值。 const owner:Group={update(root,notifications){ const stamp=signature(dependencies(root)),all=stamp!==observedSignature;if(!all&&!failed.size)return;observedSignature=stamp; for(const key of all?buckets.keys():[...failed]){ const bucket=buckets.get(key);if(!bucket)continue; try{const value=readCached(root,key,bucket,stamp);if(!failed.has(key)&&equal(bucket.observed,value))continue;bucket.observed=value;failed.delete(key);}catch{failed.add(key);} for(const notify of bucket.listeners)notifications.add(notify); } }}; /** 每键外部源,未订阅时只留局部选中值,订阅后共享 group 桶;不保留完整根快照。 */ return{forKey(key:K):ExternalSource{ let initialized=false,local:V,localSignature:string; /** 已订阅用桶缓存,否则用当前依赖的局部缓存;读取不推进 observed 通知基线。 */ function getSnapshot(){ const root=source.getSnapshot(),stamp=signature(dependencies(root)),bucket=buckets.get(key);if(bucket)return readCached(root,key,bucket,stamp); if(!initialized||stamp!==localSignature){const value=read(root,key);if(!initialized||!equal(local,value))local=value;localSignature=stamp;initialized=true;} return local; } return Object.freeze({getSnapshot,subscribe(notify:()=>void){ let bucket=buckets.get(key);if(!bucket){const value=getSnapshot();if(!buckets.size)observedSignature=signature(dependencies(source.getSnapshot()));bucket={cached:value,cachedSignature:signature(dependencies(source.getSnapshot())),observed:value,listeners:new Set()};buckets.set(key,bucket);active.add(owner);} const listener=()=>notify();bucket.listeners.add(listener); /** 撤销本订阅;空桶和空组立即删除,失败键也同时清理。 */ const remove=()=>{bucket!.listeners.delete(listener);if(!bucket!.listeners.size){buckets.delete(key);failed.delete(key);}if(!buckets.size){active.delete(owner);observedSignature=undefined;}}; // 首次注册上游失败撤回桶;正常退订只有最后一个活动组离开才停止共享监听。 if(!stop)try{stop=source.subscribe(changed);}catch(error){remove();throw error;} let live=true;return()=>{if(!live)return;live=false;remove();if(!active.size){stop?.();stop=undefined;}}; }}); }}; } // operation 通道只依赖 ledger 两张表,资源/视口变化不应使它重新计算。 const operations=group(root=>[root.runtime.ledger.operations,root.runtime.ledger.requests],(root,id)=>{const operation=root.runtime.ledger.operations.get(id);return operation?Object.freeze({operation,...(operation.requestId?{request:root.runtime.ledger.requests.get(operation.requestId)}:{})}):undefined;}); // asset 通道同时观察本地资源与共享绑定,不把其中一种来源覆盖成另一种。 const assets=group(root=>[root.runtime.resources,root.runtime.assetBindings],(root,id)=>Object.freeze({record:root.runtime.resources.get(id),binding:root.runtime.assetBindings?.get(id)})); let countStamp:string|undefined,projectCounts:SyncCounts,emptyCounts:SyncCounts,canvasCounts=new Map(); /** 同步计数只取操作表、请求表和是否 loading,不因文档几何或历史变化全表重数。 */ const countDependencies=(root:EngineSnapshot):Dependencies=>[root.runtime.ledger.operations,root.runtime.ledger.requests,!!root.runtime.loading]; // 同一依赖戳一次扫描得出项目及各画布计数,多个 canvas hook 共享结果。 const counts=group(countDependencies,(root,canvasId)=>{ const stamp=signature(countDependencies(root)); if(stamp!==countStamp){ /** 空画布也保留项目 loading 标记;每张实际参与画布至多计入一次同一操作。 */ const loading=!!root.runtime.loading,empty=()=>({pending:0,blocked:0,unknown:0,loading}),project=empty(),byCanvas=new Map>(); const scope=(id:Id)=>{let row=byCanvas.get(id);if(!row){row=empty();byCanvas.set(id,row);}return row;}; for(const operation of root.runtime.ledger.operations.values())if(operation.phase!=='resolved'){ // waiting_digest 是正常准备状态,不单凭它显示 blocked;其它 blocked 理由进入阻塞计数。 const ids=operation.intent.canvasIds.length>1?new Set(operation.intent.canvasIds):operation.intent.canvasIds,blocked=operation.phase==='blocked'&&operation.blockers.some(reason=>reason!=='waiting_digest');project.pending++;if(blocked)project.blocked++; for(const id of ids){const row=scope(id);row.pending++;if(blocked)row.blocked++;} } // 请求只统计仍关联未决操作的项。无 retryAt 的请求错误计 blocked,已发出但结果未知计 unknown。 for(const request of root.runtime.ledger.requests.values())if(request.phase!=='resolved'){ let matched=false;const ids=new Set();for(const id of request.operationIds){const operation=root.runtime.ledger.operations.get(id);if(operation&&operation.phase!=='resolved'){matched=true;for(const canvas of operation.intent.canvasIds)ids.add(canvas);}} if(!matched)continue;const blocked=!!request.error&&request.retryAt===undefined,unknown=request.outcome==='unresolved'&&['dispatch-marked','waiting'].includes(request.phase); if(blocked)project.blocked++;if(unknown)project.unknown++;for(const id of ids){const row=scope(id);if(blocked)row.blocked++;if(unknown)row.unknown++;} } projectCounts=Object.freeze(project);emptyCounts=Object.freeze(empty());canvasCounts=new Map([...byCanvas].map(([id,row])=>[id,Object.freeze(row)]));countStamp=stamp; } return canvasId===undefined?projectCounts:canvasCounts.get(canvasId)??emptyCounts; }); // 对外只交派生源工厂,所有任务修改仍必须经 engine/editor。 return Object.freeze({operation:operations.forKey,asset:assets.forKey,counts:(canvasId?:Id)=>counts.forKey(canvasId)}); }