feat(canvas): compact mutable batches with conditional wire projections
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
import type { Change, Document, ElementRecord, Id, OperationIntent } from '../canvas-core/types.ts';
|
||||
import { applyChanges } from '../canvas-core/document.ts';
|
||||
import { equal, fault, freeze } from '../canvas-core/values.ts';
|
||||
import { compressChanges, type LedgerSnapshot } from './ledger.ts';
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const wireBytes = (value: unknown) => encoder.encode(JSON.stringify(value)).byteLength;
|
||||
|
||||
export type WireOperation = { readonly id: Id; readonly changes: readonly Change[] };
|
||||
const sameMap = <T>(a: ReadonlyMap<Id, T>, b: ReadonlyMap<Id, T>) => a.size === b.size && [...a].every(([id, value]) => b.has(id) && equal(value, b.get(id)));
|
||||
|
||||
/** Pure projection for an already-selected mutable segment. Original ledger/history records never change. */
|
||||
export function projectBatch(intents: readonly OperationIntent[], acknowledged: Document, ledger: LedgerSnapshot, participants: readonly Id[]): readonly WireOperation[] {
|
||||
const scope = new Set(participants);
|
||||
const ordered = intents.map(({ id, changes }) => ({ id, changes }));
|
||||
if (intents.length < 2) return ordered;
|
||||
const elements = new Map<Id, ElementRecord>();
|
||||
const canvases = new Map(acknowledged.canvases.has(acknowledged.projectId) ? [[acknowledged.projectId, acknowledged.canvases.get(acknowledged.projectId)!]] : []);
|
||||
const tombstones = new Map<Id, number>(), seen = new Set<Id>();
|
||||
for (const intent of intents) {
|
||||
const record = ledger.operations.get(intent.id);
|
||||
// A missing/unknown baseline, frozen identity, or blocked intent cannot be guessed away.
|
||||
if (!record || record.phase !== 'pending' || record.requestId || record.blockers.length || !equal(record.intent.changes, intent.changes)) return ordered;
|
||||
for (const change of intent.changes) {
|
||||
const id = change.kind === 'field' ? change.target.id : change.id;
|
||||
if (change.kind === 'canvas') { const canvas = acknowledged.canvases.get(id); if (canvas) canvases.set(id, canvas); continue; }
|
||||
if (seen.has(id)) continue;
|
||||
seen.add(id);
|
||||
const element = acknowledged.elements.get(id), presence = record.basePresence[id];
|
||||
if (!Object.hasOwn(record.basePresence, id) || (presence !== 'absent' && presence !== 'exists') || (presence === 'exists') !== !!element) return ordered;
|
||||
if (element) elements.set(id, element);
|
||||
if (acknowledged.tombstones.has(id)) tombstones.set(id, acknowledged.tombstones.get(id)!);
|
||||
}
|
||||
}
|
||||
const sparse: Document = { projectId: acknowledged.projectId, elements, canvases, tombstones };
|
||||
const raw = intents.flatMap(intent => intent.changes);
|
||||
// Check the original conditional chain before any transformation can remove a check.
|
||||
const original = applyChanges(sparse, raw);
|
||||
const compacted = compressChanges(raw, { preserveLifecycle: true, preserveChecks: true });
|
||||
if (!compacted.length) return ordered;
|
||||
// Protocol 2 requires a nonempty change list per logical ID. Prefix IDs get an explicit
|
||||
// conditional no-op; the final ID carries the composed effect. All IDs remain deduplicated.
|
||||
const guards: Change[] = [];
|
||||
let candidates = 0;
|
||||
for (const element of elements.values()) if (scope.has(element.ownerCanvasId)) {
|
||||
if (++candidates > 8) break;
|
||||
for (const key of ['title', 'text']) {
|
||||
const present = Object.hasOwn(element.data, key), value = element.data[key] ?? null;
|
||||
guards.push({ kind: 'field', target: { id: element.id, incarnation: element.incarnation }, field: `data.${key}`, before: value, after: value, beforePresent: present, afterPresent: present });
|
||||
}
|
||||
}
|
||||
const root = canvases.get(acknowledged.projectId);
|
||||
// A child canvas no-op would touch its parent. Never silently widen the selected claims.
|
||||
if (root && root.parent === null && scope.has(root.id)) guards.push({ kind: 'canvas', id: root.id, before: root, after: root });
|
||||
let guard: Change | undefined, guardBytes = Infinity;
|
||||
for (const candidate of guards) { const bytes = wireBytes(candidate); if (bytes < guardBytes) { guard = candidate; guardBytes = bytes; } }
|
||||
if (!guard) return ordered;
|
||||
const projected = intents.map((intent, index) => ({ id: intent.id, changes: index === intents.length - 1 ? compacted : [guard!] }));
|
||||
if (projected.reduce((count, operation) => count + operation.changes.length, 0) > 10_000 || wireBytes(projected) >= wireBytes(ordered)) return ordered;
|
||||
const result = applyChanges(sparse, projected.flatMap(operation => operation.changes));
|
||||
if (!sameMap(original.elements, result.elements) || !sameMap(original.canvases, result.canvases) || !sameMap(original.tombstones, result.tombstones)) throw fault('batch_projection_mismatch');
|
||||
return freeze(projected);
|
||||
}
|
||||
Reference in New Issue
Block a user