Files
Endoleap/src/lib/canvas-service/foundry.ts
T

345 lines
34 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Foundry HTTP 与文档增量协议的边界。transport 处理账户绑定、媒体类型与流/字节读取;
* persistence 把逻辑操作编译成固定协议请求,并验证回执身份、覆盖范围和版本。
* 本模块返回 ACK 候选/已应用证明,不直接覆盖 editor 的 working;本地未决操作重放由 runtime 负责。
*/
import { modelStreamType } from './model-stream.ts';
import type { CanvasRecord, Document, ElementRecord, Id, Json, OperationIntent, Registry } from '../canvas-core/types.ts';
import { createDocument, validateDocument } from '../canvas-core/document.ts';
import { equal, fault, freeze, readMap, validJson } from '../canvas-core/values.ts';
import type { AppliedModelProof, CanonicalReadResult, EngineSnapshot, PersistencePort } from '../canvas-runtime/contracts.ts';
import type { FrozenRequest } from '../canvas-runtime/ledger.ts';
import { projectBatch } from '../canvas-runtime/batch-projection.ts';
import type { OperationStatus } from '../canvas-runtime/scheduler.ts';
/** 宿主无关服务请求描述;requestId/expectedVersion 分别映射幂等键与条件版本头。
* body 可为已冻结 JSON 字符串或上传 FormData,responseFormat 只选择预期表示,不改变业务身份。 */
export type ServiceRequest = { readonly responseFormat?:'canvas-v2'|'model-stream-v1'|'asset-bytes-v1'; readonly path: string; readonly method: 'GET' | 'POST'; readonly requestId?: Id; readonly expectedVersion?: number; readonly body?: string | FormData; readonly resourceId?: Id; readonly signal?: AbortSignal };
/** 状态与解释后载荷,特定表示额外提供 bytes 或 stream;retryAfterMs 是服务端重试提示。 */
export type ServiceResponse = { readonly status: number; readonly body: unknown; readonly bytes?:Blob; readonly stream?:AsyncIterable<Uint8Array>; readonly retryAfterMs?: number };
/** 各服务共用的可注入传输端口,测试可模拟;调度、并发和可靠保存不由此类型实现。 */
export type ServiceTransport = (request: ServiceRequest) => Promise<ServiceResponse>;
// 服务协议对账户、工作区、项目、请求等 UUID 身份的语法约束。
const uuid = /^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/i;
/** 检查最外层对象形状;需要完整 JSON/业务校验的路径另行执行,不能把此函数当 schema 校验器。 */
const record = (value: unknown): Record<string, unknown> => { if (!value || Array.isArray(value) || typeof value !== 'object') throw fault('invalid_canonical_response'); return value as Record<string, unknown>; };
/** 只接受实际数组,禁止缺失字段被当作空列表。 */
const list = (value: unknown): unknown[] => { if (!Array.isArray(value)) throw fault('invalid_canonical_response'); return value; };
/** 读取非空字符串身份;是否必须 UUID 由各协议字段的调用处决定。 */
const id = (value: unknown): string => { if (typeof value !== 'string' || !value) throw fault('invalid_canonical_response'); return value; };
/** 将版本对象转只读 Map,键必须 UUID,版本必须安全整数且不低于 minimum。 */
function versions(value: unknown, minimum = 1): ReadonlyMap<Id, number> {
const result = new Map<Id, number>();
for (const [key, version] of Object.entries(record(value))) { if (!uuid.test(key) || typeof version !== 'number' || !Number.isSafeInteger(version) || version < minimum) throw fault('invalid_canonical_version'); result.set(key, version); }
return readMap(result);
}
/** 路径段逐个编码,项目模型读取和操作端点共用同一命名空间。 */
const pathFor = (workspace: Id, canvas: Id) => `workspaces/${encodeURIComponent(workspace)}/materials/${encodeURIComponent(canvas)}/canvas/model`;
/** Credentials stay in the host/session. Every write additionally binds the expected account. */
/** 默认将请求发送到同源代理,凭证留在宿主会话,不塞进请求描述或恢复镜像。
* 发出前与收到后均检查当前身份,带 X-Expected-Account 供服务端复查账户;跨身份响应不能交给旧调用者。
* fetch 在创建时选定;其余 options 在请求时读取,宿主应维持此适配器的账户/路径绑定稳定。 */
export function createFoundryTransport(options: { accountId: Id; isCurrentIdentity(): boolean; fetch?: typeof fetch; basePath?: string }): ServiceTransport {
if (!uuid.test(options.accountId)) throw fault('invalid_account_identity');
const requestFetch = options.fetch ?? globalThis.fetch;
return async input => {
if (!options.isCurrentIdentity()) throw fault('identity_changed');
if (input.expectedVersion !== undefined && (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1)) throw fault('invalid_server_version');
// 禁止缓存和重定向,按表示设置 Accept;FormData 的 boundary 交给浏览器,不能强写 JSON Content-Type。
const response = await requestFetch(`${options.basePath ?? '/api/foundry/'}${input.path}`, { method: input.method, body: input.body, signal: input.signal, credentials: 'same-origin', cache: 'no-store', redirect: 'error', headers: {
Accept: input.responseFormat==='canvas-v2'?'application/vnd.foundry.canvas+json;version=2':input.responseFormat==='model-stream-v1'?modelStreamType:input.responseFormat==='asset-bytes-v1'?'image/*':'application/json', ...(input.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }), ...(input.resourceId ? { 'X-Resource-Id': input.resourceId } : {}), 'X-Expected-Account': options.accountId, ...(input.requestId ? { 'Idempotency-Key': input.requestId } : {}), ...(input.expectedVersion !== undefined ? { 'If-Match': `"${input.expectedVersion}"` } : {}),
} });
if (!options.isCurrentIdentity()) { await response.body?.cancel(); throw fault('identity_changed'); }
// 成功的资源字节读取同时约束 Content-Length 提示和实际累计20MiB,不能只信响应头。
// 分块仍全部保留至 Blob 构造;这是载荷预算,不是总堆内存上限,也不验证摘要或图片解码。
if(input.responseFormat==='asset-bytes-v1'&&response.status===200){
const maximum=20*1024*1024,length=response.headers.get('content-length');
if(length!==null&&(!/^\d+$/.test(length)||Number(length)>maximum)){await response.body?.cancel();throw fault('asset_byte_budget_exceeded');}
if(!response.body)throw fault('asset_bytes_unavailable');
const reader=response.body.getReader(),chunks:Uint8Array<ArrayBuffer>[]= [];let size=0;
/** 读流前后检查取消与身份,避免中途登出/换账户后继续交付原资源字节。 */
const check=()=>{input.signal?.throwIfAborted();if(!options.isCurrentIdentity())throw fault('identity_changed');};
/** 尽力取消 reader 以唤醒挂起的 read;最终释放由 finally 统一完成。 */
const abort=()=>{void reader.cancel().catch(()=>{});};input.signal?.addEventListener('abort',abort,{once:true});
try{while(true){check();const next=await reader.read();check();if(next.done)break;size+=next.value.byteLength;if(size>maximum)throw fault('asset_byte_budget_exceeded');chunks.push(next.value);}}
finally{input.signal?.removeEventListener('abort',abort);await reader.cancel().catch(()=>{});reader.releaseLock();}
return{status:200,body:null,bytes:new Blob(chunks,{type:response.headers.get('content-type')?.split(';')[0].trim()??''})};
}
// 只有明确的 NDJSON 媒体类型与version=1 才交给模型流解释器,其它表示继续走 JSON 回退。
if(input.responseFormat==='model-stream-v1'&&response.status===200&&response.headers.get('content-type')?.split(';')[0].trim()==='application/vnd.foundry.canvas-model+ndjson'){
if(!/;\s*version=1(?:;|$)/.test(response.headers.get('content-type')??'')){await response.body?.cancel();throw fault('unsupported_model_stream');}
if(!response.body)throw fault('incomplete_model_stream');
const body=response.body;
/** 惰性读取字节,每个 await 两侧复查身份;迭代结束、抛错或消费者提前退出都归还 reader 锁。
* NDJSON 内容和字节预算由 model-stream 解释器执行,此处只提供有生命周期边界的字节源。
* reader 在首次迭代时才取得;从不消费此生成器时,不会进入这里的 finally 清理。 */
async function* stream(){
const reader=body.getReader(),abort=()=>{void reader.cancel().catch(()=>{});};input.signal?.addEventListener('abort',abort,{once:true});
try{while(true){input.signal?.throwIfAborted();if(!options.isCurrentIdentity())throw fault('identity_changed');const next=await reader.read();input.signal?.throwIfAborted();if(!options.isCurrentIdentity())throw fault('identity_changed');if(next.done)break;yield next.value;}}
finally{input.signal?.removeEventListener('abort',abort);await reader.cancel().catch(()=>{});reader.releaseLock();}
}
return{status:response.status,body:null,stream:stream()};
}
// 普通 JSON 路径仍整体 response.json;不能借用流式协议的64MiB预算宣称这里也有预解析硬上限。
let body: unknown;
try { body = await response.json(); } catch { throw fault('invalid_canonical_response'); }
if (!options.isCurrentIdentity()) throw fault('identity_changed');
// 当前只解释非负数值秒数;HTTP 日期格式不在该适配路径支持范围,不猜测重试时刻。
const retry = response.headers.get('retry-after'), seconds = retry === null ? NaN : Number(retry);
return { status: response.status, body, ...(Number.isFinite(seconds) && seconds >= 0 ? { retryAfterMs: seconds * 1000 } : {}) };
};
}
/** 模型响应的完整或参与者片段,versions 同时覆盖实际 canvas 与 removed ID;不等于已验证完整文档。 */
type ModelChunk = { projectId: Id; complete: boolean; canvases: readonly CanvasRecord[]; elements: readonly ElementRecord[]; tombstones: ReadonlyMap<Id, number>; versions: ReadonlyMap<Id, number>; removed: readonly Id[] };
/** 验证JSON后复制外部响应,检查模型格式、ID唯一性、owner范围、版本覆盖和墓碑值。
* 跨分区树、端点及组件 schema 的完整一致性留给构建最终 Document 后的 validateDocument。 */
function modelChunk(value: unknown): ModelChunk {
if (!validJson(value)) throw fault('invalid_canonical_response');
const raw = record(JSON.parse(JSON.stringify(value)));
if (raw.documentFormatVersion !== 1) throw fault('unsupported_document_format');
const projectId = id(raw.projectId);
if (!uuid.test(projectId) || typeof raw.complete !== 'boolean') throw fault('invalid_canonical_response');
const canvases = list(raw.canvases) as CanvasRecord[], elements = list(raw.elements) as ElementRecord[], removed = list(raw.removedCanvasIds).map(id), serverVersions = versions(raw.versions), tombstones = new Map<Id, number>();
const canvasIds = new Set<Id>(), elementIds = new Set<Id>();
for (const canvas of canvases) {
record(canvas);
if (!uuid.test(canvas.id) || canvasIds.has(canvas.id) || !serverVersions.has(canvas.id)) throw fault('invalid_canonical_response');
canvasIds.add(canvas.id);
}
for (const element of elements) {
record(element);
if (!element.id || elementIds.has(element.id) || !canvasIds.has(element.ownerCanvasId)) throw fault('invalid_canonical_response');
elementIds.add(element.id);
}
for (const [key, value] of Object.entries(record(raw.tombstones))) { if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) throw fault('invalid_canonical_response'); tombstones.set(key, value); }
// 删除列表不得重复、不得与返回 canvas 重叠,版本表也不得含无归属的额外 ID。
if (new Set(removed).size !== removed.length || removed.some(value => canvasIds.has(value) || !serverVersions.has(value)) || serverVersions.size !== canvasIds.size + removed.length) throw fault('invalid_canonical_response');
return freeze({ projectId, complete: raw.complete, canvases, elements, tombstones: readMap(tombstones), versions: serverVersions, removed });
}
/** 完整读取可返回 ready 或 migration-required,迁移要求不能强制断言为新模型。 */
export type ModelLoad = CanonicalReadResult;
/** 完整 JSON 读取入口,校验旧格式迁移提示或完整新模型;部分片段不能作为初始完整文档采用。 */
export async function loadFoundryModel(transport: ServiceTransport, workspaceId: Id, canvasId: Id, registry: Registry, signal?: AbortSignal): Promise<ModelLoad> {
const response = await transport({ method: 'GET', path: pathFor(workspaceId, canvasId), signal }), body = record(response.body);
// 旧数据迁移范围由 root_id/source_versions 指定,并必须覆盖本次访问画布及根项目。
if (response.status === 409 && body.error === 'canonical_migration_required') {
if (body.document_format_version !== 1) throw fault('unsupported_document_format');
const rootId = id(body.root_id); if (!uuid.test(rootId)) throw fault('invalid_canonical_response');
const sourceVersions=versions(body.source_versions);if(!sourceVersions.has(canvasId)||!sourceVersions.has(rootId))throw fault('project_mismatch');
return freeze({ status: 'migration-required', rootId, sourceVersions });
}
if (response.status !== 200) throw fault(typeof body.error === 'string' ? body.error : 'model_load_failed');
const chunk = modelChunk(body.model);
if (!chunk.complete) throw fault('incomplete_initial_model');
const document = createDocument(chunk.projectId, chunk.canvases, chunk.elements, chunk.tombstones); validateDocument(document, registry);
if(!document.canvases.has(canvasId))throw fault('project_mismatch');
return Object.freeze({ status: 'ready', document, versions: chunk.versions });
}
/** 把HTTP响应转换为请求结果状态,先匹配协议/请求身份。
* applied 要精确覆盖冻结操作集合;accepted 只表示已受理;未知回执保持 unresolved,不能推断未生效。 */
function statusFor(request: FrozenRequest, response: ServiceResponse, query: boolean): OperationStatus {
const body = record(response.body), error = typeof body.error === 'string' ? body.error : undefined;
const matching = body.protocol_version === 2 && body.request_id === request.id;
if (matching && body.status === 'applied' && response.status >= 200 && response.status < 300) {
const covered = list(body.operation_ids).map(id);
if (covered.length !== request.operationIds.length || new Set(covered).size !== covered.length || covered.some(id => !request.operationIds.includes(id))) throw fault('receipt_coverage_mismatch');
if (!validJson(body)) throw fault('invalid_canonical_response');
return freeze({ outcome: 'applied', canonical: JSON.parse(JSON.stringify(body)) as Json });
}
if (matching && body.status === 'accepted' && response.status >= 200 && response.status < 300) return { outcome: 'accepted', retryAfterMs: response.retryAfterMs };
// 终结未生效分支只要求协议/请求匹配和 terminal;不复用 applied 的 HTTP 与操作覆盖校验。
if (matching && body.status === 'not-applied' && body.terminal === true) return { outcome: 'not-applied', error: error ?? 'not_applied' };
// 查询不到回执不等于从未执行,继续使用原请求身份查证;普通4xx未提供终结证据时阻塞。
if (query && response.status === 404 && body.status === 'unknown' && body.request_id === request.id) return { outcome: 'unresolved', error: 'operation_receipt_unknown', retryAfterMs: response.retryAfterMs };
if (response.status >= 400 && response.status < 500) return { outcome: 'unresolved', blocked: true, error: error ?? 'protocol_rejected' };
return { outcome: 'unresolved', error: error ?? 'transport_unknown', retryAfterMs: response.retryAfterMs };
}
/** 发送/查询/解释前交叉核对冻结元数据与请求体:协议、request_id、预期版本、画布集合和操作覆盖一致。
* 不在这里重新编译 payload,重试必须沿用已经保存的精确 body。
* 这是冻结描述的一致性检查,不重新执行每项 change 的 schema、条件或依赖验证。 */
function validateFrozen(request: FrozenRequest) {
let body: Record<string, unknown>;
try { body = record(JSON.parse(request.body)); } catch { throw fault('invalid_frozen_request'); }
const operations = list(body.operations).map(value => id(record(value).id));
if (request.protocolVersion !== 2 || body.protocol_version !== 2 || body.request_id !== request.id || !equal(body.expected_versions, request.expectedVersions) || !equal(Object.keys(request.expectedVersions).sort(), [...request.canvasIds].sort()) || !equal([...operations].sort(), [...request.operationIds].sort())) throw fault('frozen_request_contract_mismatch');
}
/** Operations/conditional fields are sent; full snapshots are only reads and ACK participant views. */
/** 已经协调完成的本地压缩回执,仅保留身份与版本证据;不含可再次合图的原始模型。
* localReceiptVersion 与远端 protocol_version 是独立版本轴,不能拿摘要再次模拟原服务回执。 */
export type FoundryResolvedReceiptSummary={readonly localReceiptFormat:'foundry.reconciled-document';readonly localReceiptVersion:1;readonly protocol_version:2;readonly request_id:Id;readonly status:'applied';readonly operation_ids:readonly Id[];readonly projectId:Id;readonly versions:Readonly<Record<Id,number>>};
// 压缩只允许认识的封闭字段集合;遇到扩展字段保留原回执,避免丢失未知证据。
const receiptKeys=new Set(['protocol_version','request_id','status','operation_ids','model']);
const modelKeys=new Set(['documentFormatVersion','projectId','complete','canvases','elements','tombstones','versions','removedCanvasIds']);
const elementKeys=new Set(['id','incarnation','ownerCanvasId','componentId','dataVersion','structure','geometry','data','source','target','path']);
/** 只检查对象自有可枚举字段,发现任何未知项立即停止有损摘要化。 */
function hasExtraKeys(value:Record<string,unknown>,known:ReadonlySet<string>){for(const key in value)if(Object.hasOwn(value,key)&&!known.has(key))return true;return false;}
/** 识别已经压缩的本地摘要并拒绝重解释;未知摘要版本给出独立解释器错误。 */
function assertRawReceipt(value:unknown){if(value&&typeof value==='object'&&!Array.isArray(value)&&(value as Record<string,unknown>).localReceiptFormat==='foundry.reconciled-document'&&!Object.hasOwn(value,'model')){if((value as Record<string,unknown>).localReceiptVersion!==1)throw fault('receipt_summary_interpreter_unavailable');throw fault('receipt_already_reconciled');}}
/** 绑定一个工作区/根项目的文档协议适配器,支持单/批量增量操作、原请求查询与完整权威读取。
* resolvedReceiptPolicy 默认保留 raw,显式 summary 才安装协调后压缩能力。 */
export function createFoundryPersistence(options: { workspaceId: Id; rootId: Id; registry: Registry; transport: ServiceTransport;resolvedReceiptPolicy?:'raw'|'summary' }): PersistencePort {
if (!uuid.test(options.workspaceId) || !uuid.test(options.rootId)) throw fault('invalid_service_scope');
if(options.resolvedReceiptPolicy!==undefined&&!['raw','summary'].includes(options.resolvedReceiptPolicy))throw fault('invalid_receipt_policy');
const path = pathFor(options.workspaceId, options.rootId);
/** 统一发送/查询已有冻结请求。传输/解释失败保持 unresolved,带可识别错误码时按规则阻塞。
* 不在异常中宣称服务端回滚,也不分配新幂等键来替代原请求。 */
async function execute(request: FrozenRequest, query: boolean, signal: AbortSignal): Promise<OperationStatus> {
try {
validateFrozen(request);
const response = await options.transport({ method: query ? 'GET' : 'POST', path: `${path}/operations${query ? `/${encodeURIComponent(request.id)}` : ''}`, requestId: query ? undefined : request.id, body: query ? undefined : request.body, signal });
return statusFor(request, response, query);
} catch (error) {
const code = (error as { code?: string }).code;
return { outcome: 'unresolved', error: code ?? 'transport_unknown', ...(code && code !== 'invalid_canonical_response' ? { blocked: true } : {}) };
}
}
/** 编译最多64个严格递增的 document.change v1 意图;操作ID不被合成批次ID替换。
* 参与 canvas 版本来自 ACK;仅本批明确新建的 canvas 可用零基线,已存在者缺版本必须拒绝。 */
function compileBatch(intents: readonly OperationIntent[], requestId: Id, snapshot: EngineSnapshot) {
if (!intents.length || intents.length > 64 || snapshot.document.projectId !== options.rootId || !uuid.test(requestId) || new Set(intents.map(intent => intent.id)).size !== intents.length) throw fault('operation_interpreter_unavailable');
for (const intent of intents) if (!uuid.test(intent.id) || intent.operationType !== 'document.change' || intent.operationSchemaVersion !== 1) throw fault('operation_interpreter_unavailable');
if (intents.some((intent, index) => index > 0 && intent.sequence <= intents[index - 1].sequence)) throw fault('invalid_operation_order');
const canvasIds = [...new Set(intents.flatMap(intent => intent.canvasIds))].sort(), expectedVersions: Record<Id, number> = {};
for (const canvas of canvasIds) {
const version = snapshot.runtime.versions.get(canvas);
if (version === undefined && !intents.some(intent => intent.changes.some(change => change.kind === 'canvas' && change.id === canvas && change.before === null && change.after))) throw fault('missing_server_version', [canvas]);
expectedVersions[canvas] = version ?? 0;
}
// The body is the durable coverage mapping. Never replace logical IDs with a synthetic batch ID.
// projectBatch 基于 ACK 与 ledger 合并条件字段,同时保留逻辑覆盖;JSON复制使描述脱离调用方引用。
// 返回值尚不是持久冻结的 body 字符串;保存请求、调度和重试由 runtime 完成。
const payload = JSON.parse(JSON.stringify({ protocol_version: 2, request_id: requestId, expected_versions: expectedVersions, operations: projectBatch(intents, snapshot.runtime.acknowledged, snapshot.runtime.ledger, canvasIds) })) as Json;
if (!validJson(payload)) throw fault('invalid_operation_payload');
return freeze({ protocolVersion: 2, canvasIds, expectedVersions, payload });
}
return Object.freeze({
/** 协议版本能力门,只声明可解释 v2;不是对冻结 body 完整合法性的认证。 */
supportsRequest: (request: FrozenRequest) => request.protocolVersion === 2,
/** 仅在调用方已协调成功且请求resolved/applied后尝试摘要。
* 检查参与版本与已采用结果一致,未知字段/未知组件/额外格式信息一律保留原始回执。
* 此处信任 applied 已经协调采用,不再次逐元素比较 applied.document;摘要不能独立重建文档。 */
...(options.resolvedReceiptPolicy==='summary'?{compactResolvedReceipt(request:FrozenRequest,receipt:Json,applied:import('../canvas-runtime/contracts.ts').CanonicalProposal):Json{
if(request.kind!=='document.change'||request.protocolVersion!==2||request.phase!=='resolved'||request.outcome!=='applied')return receipt;
validateFrozen(request);const body=record(receipt);
if(hasExtraKeys(body,receiptKeys))return receipt;
if(body.protocol_version!==2)return receipt;
if(body.request_id!==request.id||body.status!=='applied')throw fault('receipt_identity_mismatch');
const covered=list(body.operation_ids).map(id);if(covered.length!==request.operationIds.length||new Set(covered).size!==covered.length||covered.some(id=>!request.operationIds.includes(id)))throw fault('receipt_coverage_mismatch');
const model=record(body.model);
if(hasExtraKeys(model,modelKeys)||model.documentFormatVersion!==1||model.projectId!==options.rootId||model.complete!==false)return receipt;
const resultVersions=versions(model.versions);
if(resultVersions.size!==request.canvasIds.length||request.canvasIds.some(id=>!resultVersions.has(id)||(resultVersions.get(id)??0)<=request.expectedVersions[id]||resultVersions.get(id)!==applied.versions.get(id)))return receipt;
// 原始元素含未知类型或扩展字段时可能仍有将来恢复所需信息,不能为了省空间丢掉。
for(const value of list(model.elements)){const element=record(value);if(options.registry.resolve(element as unknown as ElementRecord)!=='known'||hasExtraKeys(element,elementKeys))return receipt;}
const canvasKeys=new Set(['id','parent']),parentKeys=new Set(['canvasId','entryElementId']);
for(const value of list(model.canvases)){const canvas=record(value);if(hasExtraKeys(canvas,canvasKeys)||canvas.parent!==null&&hasExtraKeys(record(canvas.parent),parentKeys))return receipt;}
return freeze({localReceiptFormat:'foundry.reconciled-document',localReceiptVersion:1,protocol_version:2,request_id:request.id,status:'applied',operation_ids:covered,projectId:options.rootId,versions:Object.fromEntries(resultVersions)});
}}:{}),
/** 独立验证请求已生效证据,要求每个参与者版本恰为请求基线+1;返回对后续权威读取的断言。 */
verifyApplied(request:FrozenRequest,receipt:Json){
assertRawReceipt(receipt);
validateFrozen(request);
if(statusFor(request,{status:200,body:receipt},false).outcome!=='applied')throw fault('receipt_identity_mismatch');
const proof=verifyFoundryModelProof(record(receipt).model,request.canvasIds,options.rootId);
for(const [canvas,version]of proof.versions)if(version!==request.expectedVersions[canvas]+1)throw fault('receipt_version_mismatch',[canvas]);
return proof;
},
/** 必须取得本根项目的完整新格式文档;迁移提示返回明确错误,留给迁移流程处理。 */
async read(signal: AbortSignal) {
const loaded=await loadFoundryModel(options.transport,options.workspaceId,options.rootId,options.registry,signal);
if(loaded.status!=='ready')throw fault('canonical_migration_required');
if(loaded.document.projectId!==options.rootId)throw fault('project_mismatch');
return loaded;
},
// 单操作复用批量编译器;submit/query 分别以POST原body和GET原requestId走同一结果解释器。
compile: (intent: OperationIntent, requestId: Id, snapshot: EngineSnapshot) => compileBatch([intent], requestId, snapshot),
compileBatch,
submit: (request: FrozenRequest, signal: AbortSignal) => execute(request, false, signal),
query: (request: FrozenRequest, signal: AbortSignal) => execute(request, true, signal),
/** 从原始回执提取参与者模型,合成新的 ACK 候选;不接受本地已压缩摘要代替原模型。 */
canonical(request: FrozenRequest, status: OperationStatus, snapshot: EngineSnapshot) {
// 按已确认的 applied 结果调用;此处核对身份并组装模型候选,不代替结果解释或版本推进检查。
assertRawReceipt(status.canonical);const body = record(status.canonical);
if (body.request_id !== request.id || body.protocol_version !== 2) throw fault('receipt_identity_mismatch');
return mergeFoundryModel(body.model, request.canvasIds, snapshot, options.registry, options.rootId);
},
});
}
/** Verify coverage independently of the current ACK graph. Only a complete fresh model is adopted. */
/** 在不依赖当前 ACK 图的情况下检查回执覆盖,生成 assertCanonical。
* 随后的完整权威读取不得落后于已生效版本;同版本必须内容相等,更高版本可含后续修改。 */
export function verifyFoundryModelProof(value:unknown,participants:readonly Id[],rootId:Id):AppliedModelProof {
const chunk=modelChunk(value);
if(chunk.projectId!==rootId||chunk.complete||chunk.versions.size!==participants.length||participants.some(id=>!chunk.versions.has(id)))throw fault('receipt_coverage_mismatch');
/** 断言只验证采用读取是否包含既有证据,不在这里把回执片段直接变成新 working。 */
return Object.freeze({versions:chunk.versions,assertCanonical(proposal){
if(proposal.document.projectId!==rootId)throw fault('project_mismatch');
const unchanged=new Set<Id>(),canvases=new Map(chunk.canvases.map(canvas=>[canvas.id,canvas]));
for(const [canvas,version]of chunk.versions){
const fresh=proposal.versions.get(canvas);if(fresh===undefined||fresh<version)throw fault('recovery_read_behind_receipt',[canvas]);
if(fresh!==version)continue;
if(!equal(canvases.get(canvas),proposal.document.canvases.get(canvas)))throw fault('canonical_version_mismatch',[canvas]);
unchanged.add(canvas);
}
// 更高版本跳过逐字段相等检查,允许后续合法修改;同版本(包括删除记录)必须保持既有内容。
// 对仍处于同版本的 canvas 逐元素比较,既不能缺元素也不能多元素;墓碑只能单调推进。
const expected=new Map(chunk.elements.filter(element=>unchanged.has(element.ownerCanvasId)).map(element=>[element.id,element]));
let count=0;for(const element of proposal.document.elements.values())if(unchanged.has(element.ownerCanvasId)){count++;if(!equal(expected.get(element.id),element))throw fault('canonical_version_mismatch',[element.ownerCanvasId]);}
if(count!==expected.size)throw fault('canonical_version_mismatch');
for(const [id,incarnation]of chunk.tombstones)if((proposal.document.tombstones.get(id)??0)<incarnation)throw fault('stale_canonical_lifecycle',[id]);
}});
}
/** Shared participant replacement for document receipts and canonical run events. */
/** 文档回执/普通生成事件的参与者替换:仅替换声明画布及其成员,非参与画布沿用旧 ACK。
* 全树重新验证后返回候选,runtime 另行检查版本推进并叠回本地未决操作。 */
export function mergeFoundryModel(value: unknown, participants: readonly Id[], snapshot: EngineSnapshot, registry: Registry, rootId: Id) {
const chunk = modelChunk(value);
if (chunk.projectId !== rootId || chunk.complete || chunk.versions.size !== participants.length || participants.some(id => !chunk.versions.has(id))) throw fault('receipt_coverage_mismatch');
// 必须从 ACK 构造,不把 working 中尚未确认的本地内容冒充服务端已接纳内容。
const previous = snapshot.runtime.acknowledged, canvases = new Map(previous.canvases), elements = new Map(previous.elements), tombstones = new Map(previous.tombstones), serverVersions = new Map(snapshot.runtime.versions);
// 先全部删除参与 canvas;removed 参与者不在返回列表内,因此保留版本但不重新放回画布记录。
for (const canvas of participants) canvases.delete(canvas);
for (const canvas of chunk.canvases) canvases.set(canvas.id, canvas);
// 先移除旧参与者成员,再加入回执成员;与非参与者现有ID碰撞则拒绝,不能跨范围覆盖。
for (const [id, element] of elements) if (participants.includes(element.ownerCanvasId)) elements.delete(id);
for (const element of chunk.elements) { if (elements.has(element.id)) throw fault('canonical_scope_mismatch', [element.id]); elements.set(element.id, element); }
for (const [id, generation] of chunk.tombstones) tombstones.set(id, Math.max(tombstones.get(id) ?? 0, generation));
for (const [id, version] of chunk.versions) serverVersions.set(id, version);
const document = createDocument(previous.projectId, [...canvases.values()], [...elements.values()], tombstones); validateDocument(document, registry);
return Object.freeze({ document, versions: readMap(serverVersions) });
}
/** A relocated result carries a complete ownership context. Retain later ACKs
* per canvas; validate the combined tree before publishing any ownership change. */
/** 生成结果改变归属时采用带完整树的上下文,但逐 canvas 保留比事件更新的 ACK。
* 同版本不同内容是协议冲突;合并树和墓碑再 validate,不能逐节点发布一半的归属变化。 */
export function mergeFoundryRunContext(value: unknown, snapshot: EngineSnapshot, registry: Registry, rootId: Id) {
const chunk=modelChunk(value);
if(!chunk.complete||chunk.projectId!==rootId)throw fault('invalid_run_context');
const previous=snapshot.runtime.acknowledged,canvases=new Map(previous.canvases),elements=new Map(previous.elements),tombstones=new Map(previous.tombstones),serverVersions=new Map(snapshot.runtime.versions),replace=new Set<Id>();
// 事件版本低于当前ACK则不替换该canvas;相等时先排序核对成员与canvas记录完全一致。
for(const [id,version] of chunk.versions)if(version>=(snapshot.runtime.versions.get(id)??0)){
if(version===snapshot.runtime.versions.get(id)){
const incoming=chunk.elements.filter(element=>element.ownerCanvasId===id).sort((a,b)=>a.id.localeCompare(b.id)),known=[...previous.elements.values()].filter(element=>element.ownerCanvasId===id).sort((a,b)=>a.id.localeCompare(b.id));
if(!equal(chunk.canvases.find(canvas=>canvas.id===id),previous.canvases.get(id))||!equal(incoming,known))throw fault('same_version_context_conflict',[id]);
}
replace.add(id);serverVersions.set(id,version);canvases.delete(id);
}
// 只替换通过版本选择的参与者,加入跨owner元素仍要检测与保留部分的身份碰撞。
for(const canvas of chunk.canvases)if(replace.has(canvas.id))canvases.set(canvas.id,canvas);
for(const [id,element] of elements)if(replace.has(element.ownerCanvasId))elements.delete(id);
for(const element of chunk.elements)if(replace.has(element.ownerCanvasId)){if(elements.has(element.id))throw fault('canonical_scope_mismatch',[element.id]);elements.set(element.id,element);}
// 墓碑取全上下文的逐 ID 最大值,即使对应 canvas 因版本较旧未替换,也不能让生命周期倒退。
for(const [id,generation] of chunk.tombstones)tombstones.set(id,Math.max(tombstones.get(id)??0,generation));
const document=createDocument(rootId,[...canvases.values()],[...elements.values()],tombstones);validateDocument(document,registry);
return Object.freeze({document,versions:readMap(serverVersions)});
}