// Splitting a push into bounded updates. A single `export({mode:'update'})` is // one opaque blob, so a device with a lot of unsent history (a first sync of a // mature standalone workspace, or a big batch of offline ink) produces one // payload the server rejects for size, and every retry sends the same rejected // blob. Instead we walk the op spans the peer is missing and export them in // batches small enough to accept, in causal order, so each lands as its own // update row and the doc still converges. import type { LoroDoc, PeerID } from 'loro-crdt'; // Ops per chunk. Loro update bytes vary per op, but a few hundred ops stay well // under the server's ~3 MB payload cap even for heavy annotation ops, while // keeping the array short enough for the 500-per-push batch limit. const MAX_OPS_PER_CHUNK = 200; type Frontier = { peer: PeerID; counter: number }; // The updates the peer at `fromFrontiers` still needs from `doc`, as a list of // payloads to push in order. Returns a single export when there is little to // send, and many bounded ones when there is a backlog. An empty result means // the peer is already caught up. export function chunkedUpdates(doc: LoroDoc, fromFrontiers: Frontier[] | undefined): Uint8Array[] { const to = doc.oplogFrontiers(); // A first push (no acked frontier) or a small delta: let Loro pick the // smallest encoding for the whole range in one blob. const forward = fromFrontiers ? doc.findIdSpansBetween(fromFrontiers, to).forward : doc.findIdSpansBetween([], to).forward; const totalOps = forward.reduce((n, s) => n + s.length, 0); // No missing ops: nothing to send. A plain `export` would still emit a // non-empty header here, so decide on op count, not payload bytes. if (totalOps === 0) return []; if (totalOps <= MAX_OPS_PER_CHUNK) { const one = fromFrontiers ? doc.export({ mode: 'update', from: doc.frontiersToVV(fromFrontiers) }) : doc.export({ mode: 'update' }); return [one]; } // Slice the missing spans into op-count-bounded batches, exporting each as // its own update. Spans come back in causal order, so pushing the batches in // order keeps every chunk importable after its predecessors. const payloads: Uint8Array[] = []; let batch: { id: { peer: PeerID; counter: number }; len: number }[] = []; let batchOps = 0; const flush = () => { if (!batch.length) return; payloads.push(doc.export({ mode: 'updates-in-range', spans: batch })); batch = []; batchOps = 0; }; for (const span of forward) { let counter = span.counter; let remaining = span.length; while (remaining > 0) { const take = Math.min(remaining, MAX_OPS_PER_CHUNK - batchOps); batch.push({ id: { peer: span.peer, counter }, len: take }); batchOps += take; counter += take; remaining -= take; if (batchOps >= MAX_OPS_PER_CHUNK) flush(); } } flush(); return payloads; }