feat(canvas): batch mutable document operations with durable coverage
This commit is contained in:
@@ -15,6 +15,7 @@ export type SchedulerOptions = {
|
||||
createId(): Id;
|
||||
participants(intent: OperationIntent): readonly Id[];
|
||||
compile(intent: OperationIntent, requestId: Id): CompiledRequest;
|
||||
compileBatch?: (intents: readonly OperationIntent[], requestId: Id) => CompiledRequest;
|
||||
submit(request: FrozenRequest, signal: AbortSignal): Promise<OperationStatus>;
|
||||
query(request: FrozenRequest, signal: AbortSignal): Promise<OperationStatus>;
|
||||
supportsRequest?: (request: FrozenRequest) => boolean;
|
||||
@@ -35,6 +36,8 @@ export function createScheduler(options: SchedulerOptions) {
|
||||
const retry = createMinHeap<{ id: Id; dueAt: number; sequence: number; token: number }>((a, b) => a.dueAt - b.dueAt || a.sequence - b.sequence);
|
||||
const tokens = new Map<Id, number>(), active = new Map<Id, { controller: AbortController; promise: Promise<void>; kind: FrozenRequest['kind'] }>();
|
||||
const holds = new Set<symbol>();
|
||||
const ordered: { id: Id; sequence: number }[] = [];
|
||||
let scheduledPump: Promise<void> | undefined;
|
||||
const laneWaiters = new Map<NonNullable<FrozenRequest['kind']>, Set<Id>>(), deferredRetries = new Map<Id, { id: Id; dueAt: number; sequence: number; token: number }>();
|
||||
let timer: unknown, pumpTimer: unknown, enqueueSequence = 0, stopped = true, closed = false, pumping = false;
|
||||
const delay = (attempt: number) => Math.max(1, options.retryDelay?.(attempt) ?? Math.min(30_000, 500 * 2 ** Math.min(attempt, 6)));
|
||||
@@ -53,12 +56,38 @@ export function createScheduler(options: SchedulerOptions) {
|
||||
if (!record) return;
|
||||
if (!indexed.has(id)) {
|
||||
indexed.add(id);
|
||||
let lo = 0, hi = ordered.length;
|
||||
while (lo < hi) { const mid = (lo + hi) >>> 1; if (ordered[mid].sequence < record.intent.sequence) lo = mid + 1; else hi = mid; }
|
||||
ordered.splice(lo, 0, { id, sequence: record.intent.sequence });
|
||||
for (const dependency of record.intent.dependencies) {
|
||||
const set = dependents.get(dependency) ?? new Set<Id>(); set.add(id); dependents.set(dependency, set);
|
||||
}
|
||||
}
|
||||
enqueue(id);
|
||||
}
|
||||
/** Only a contiguous mutable document prefix may share a request. Task barriers stay visible. */
|
||||
function batch(first: OperationIntent, canvases: Set<Id>): readonly OperationIntent[] {
|
||||
const selected = [first], ids = new Set([first.id]);
|
||||
if (!options.compileBatch || first.operationType !== 'document.change' || first.operationSchemaVersion !== 1) return selected;
|
||||
let lo = 0, hi = ordered.length, changeCount = first.changes.length;
|
||||
while (lo < hi) { const mid = (lo + hi) >>> 1; if (ordered[mid].sequence <= first.sequence) lo = mid + 1; else hi = mid; }
|
||||
const ledger = options.getLedger();
|
||||
for (let i = lo; i < ordered.length && selected.length < 64; i++) {
|
||||
const record = ledger.operations.get(ordered[i].id);
|
||||
if (!record || record.phase !== 'pending' || record.requestId || record.blockers.length || record.intent.operationType !== 'document.change' || record.intent.operationSchemaVersion !== 1) break;
|
||||
if (record.intent.dependencies.some(id => !ids.has(id) && ledger.operations.get(id)?.phase !== 'resolved')) break;
|
||||
const scope = options.participants(record.intent);
|
||||
// Independent canvas lanes keep independent failure and retry boundaries.
|
||||
if (!scope.length || !scope.some(id => canvases.has(id)) || scope.some(id => claims.has(id)) || changeCount + record.intent.changes.length > 10_000) break;
|
||||
selected.push(record.intent); ids.add(record.intent.id); changeCount += record.intent.changes.length;
|
||||
for (const id of scope) canvases.add(id);
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
function requestPump() {
|
||||
if (!options.compileBatch) { pump(); return; }
|
||||
if (!scheduledPump) scheduledPump = Promise.resolve().then(() => { scheduledPump = undefined; pump(); });
|
||||
}
|
||||
function own(request: FrozenRequest) {
|
||||
for (const canvas of request.canvasIds) {
|
||||
const prior = claims.get(canvas);
|
||||
@@ -144,7 +173,7 @@ export function createScheduler(options: SchedulerOptions) {
|
||||
const id = ready.pop(); if (!id) break;
|
||||
queued.delete(id);
|
||||
const record = options.getLedger().operations.get(id);
|
||||
if (!record || record.phase !== 'pending' || record.blockers.length || record.intent.dependencies.some(dependency => options.getLedger().operations.get(dependency)?.phase !== 'resolved')) continue;
|
||||
if (!record || record.phase !== 'pending' || record.requestId || record.blockers.length || record.intent.dependencies.some(dependency => options.getLedger().operations.get(dependency)?.phase !== 'resolved')) continue;
|
||||
try {
|
||||
if (!canRun(record.intent.operationType)) {
|
||||
const set = laneWaiters.get(record.intent.operationType) ?? new Set<Id>(); set.add(id); laneWaiters.set(record.intent.operationType, set); continue;
|
||||
@@ -156,9 +185,11 @@ export function createScheduler(options: SchedulerOptions) {
|
||||
for (const canvas of occupied) { const set = waiters.get(canvas) ?? new Set<Id>(); set.add(id); waiters.set(canvas, set); }
|
||||
continue;
|
||||
}
|
||||
const requestId = options.createId(), compiled = options.compile(record.intent, requestId);
|
||||
if (canvases.length !== compiled.canvasIds.length || canvases.some(canvas => !compiled.canvasIds.includes(canvas))) throw fault('participant_mismatch');
|
||||
options.mutate(ledger => ledger.freeze({ id: requestId, operationIds: [id], ...compiled }));
|
||||
const scope = new Set(canvases), intents = batch(record.intent, scope);
|
||||
const participants = [...scope].sort();
|
||||
const requestId = options.createId(), compiled = intents.length > 1 ? options.compileBatch!(intents, requestId) : options.compile(record.intent, requestId);
|
||||
if (participants.length !== compiled.canvasIds.length || participants.some(canvas => !compiled.canvasIds.includes(canvas))) throw fault('participant_mismatch');
|
||||
options.mutate(ledger => ledger.freeze({ ...compiled, id: requestId, operationIds: intents.map(intent => intent.id) }));
|
||||
own(options.getLedger().requests.get(requestId)!); launch(requestId, 'submit');
|
||||
} catch (error) { options.mutate(ledger => ledger.block(id, [(error as Error).message || 'compile_failed'])); report(error); }
|
||||
}
|
||||
@@ -182,7 +213,7 @@ export function createScheduler(options: SchedulerOptions) {
|
||||
}
|
||||
pump();
|
||||
},
|
||||
notify(operationIds: readonly Id[]) { for (const id of operationIds) index(id); pump(); },
|
||||
notify(operationIds: readonly Id[]) { for (const id of operationIds) index(id); requestPump(); },
|
||||
/** Acquire synchronously, then settle(): already admitted work completes with its original identity. */
|
||||
hold() {
|
||||
if (closed) throw fault('scheduler_closed');
|
||||
@@ -210,7 +241,13 @@ export function createScheduler(options: SchedulerOptions) {
|
||||
pump();
|
||||
},
|
||||
getClaims: () => readMap(claims),
|
||||
async settle() { while (active.size) await Promise.all([...active.values()].map(item => item.promise)); },
|
||||
async settle() {
|
||||
do {
|
||||
if (scheduledPump) await scheduledPump;
|
||||
if (active.size) await Promise.all([...active.values()].map(item => item.promise));
|
||||
if (!stopped && !holds.size && pumpTimer !== undefined) { clock.clearTimer(pumpTimer); pumpTimer = undefined; pump(); }
|
||||
} while (scheduledPump || active.size || (!stopped && !holds.size && pumpTimer !== undefined));
|
||||
},
|
||||
stop() { closed = true; stopped = true; if (timer !== undefined) clock.clearTimer(timer); if (pumpTimer !== undefined) clock.clearTimer(pumpTimer); timer = pumpTimer = undefined; for (const item of active.values()) item.controller.abort(); },
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user