docs(canvas): explain recovery encoding and history replay evidence

This commit is contained in:
2026-11-12 00:13:52 +08:00
parent da00490ded
commit af8e2fe76b
8 changed files with 187 additions and 1 deletions
+11
View File
@@ -1,11 +1,19 @@
/**
* 恢复图像 JSON 的有界差分与纯回放。差分不是业务 Change,不携带用户命令/网络操作身份。
* 校验摘要覆盖精确 JSON 字节,因此对象键顺序改变时直接替换子树,不能只保值而改序。
*/
import type { Json } from '../canvas-core/types.ts';
import { fault, validJson } from '../canvas-core/values.ts';
/** 对象路径段为字符串,数组路径段为非负整数;空路径表示整份根值。 */
type Path = readonly (string | number)[];
/** set 替换子树,splice 修改数组尾/区间;不提供任意执行代码或隐式创建路径。 */
export type JournalPatch = {op:'set';path:Path;value:Json}|{op:'splice';path:Path;start:number;deleteCount:number;items:Json[]};
/** Exact JSON property order is retained because recovery checksums cover serialized bytes. */
/** 生成至多10000项差分;超限返回 null,让存储层选择完整图像,不返回被截断的补丁。 */
export function diffJournal(before:Json,after:Json):JournalPatch[]|null {
const patches:JournalPatch[]=[];
/** 相同身份立即跳过;数组递归共同前缀并 splice 长度差,对象仅同键同序时逐字段递归。 */
function visit(a:Json,b:Json,path:(string|number)[]){
if(a===b||patches.length>10000)return;
if(Array.isArray(a)&&Array.isArray(b)){
@@ -26,12 +34,14 @@ export function diffJournal(before:Json,after:Json):JournalPatch[]|null {
visit(before,after,[]);return patches.length>10000?null:patches;
}
/** Copy only changed ancestors; never mutate the preceding checkpoint or another patch's input. */
/** 逐补丁重放到私有结果,每次仅复制受影响祖先;原 checkpoint 和其它已持有值不被改动。 */
export function applyJournal(before:Json,patches:readonly JournalPatch[]):Json {
if(!Array.isArray(patches)||patches.length>10000)throw fault('corrupt_recovery_delta');
let result=before;
for(const patch of patches){
if(!patch||!['set','splice'].includes(patch.op)||!Array.isArray(patch.path)||patch.path.length>64||patch.path.some((key:unknown)=>typeof key!=='string'&&(typeof key!=='number'||!Number.isSafeInteger(key)||key<0)))throw fault('corrupt_recovery_delta');
if(patch.op==='set'?!validJson(patch.value):!Array.isArray(patch.items)||!validJson(patch.items))throw fault('corrupt_recovery_delta');
/** 验证路径自有属性/数组下标后递归替换,set/splice 终点另外校验 JSON 与区间边界。 */
function replace(value:Json,depth:number):Json {
if(depth===patch.path.length){
if(patch.op==='set')return patch.value;
@@ -41,6 +51,7 @@ export function applyJournal(before:Json,patches:readonly JournalPatch[]):Json {
const key=patch.path[depth];
if(!value||typeof value!=='object'||!Object.hasOwn(value,key)||(Array.isArray(value)?typeof key!=='number'||key>=value.length:typeof key!=='string'))throw fault('corrupt_recovery_delta');
const copy=Array.isArray(value)?[...value]:{...value};
// 安全定义自有键,避免 __proto__ 等路径变成赋值副作用;也保留已存在键的次序。
Object.defineProperty(copy,key,{value:replace((value as Record<string|number,Json>)[key],depth+1),enumerable:true,writable:true,configurable:true});return copy;
}
result=replace(result,0);