Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
sync: a fork re-sends its snapshot to peers that join later (PR-4) (#608)
nyblnet9d023f1ab091
diff --git a/kernel/src/sync/session.ts b/kernel/src/sync/session.tsindex f17a356e..3fb47e95 100644--- a/kernel/src/sync/session.ts+++ b/kernel/src/sync/session.ts@@ -405,6 +405,18 @@ export class SyncSession {/** a restored offline fork still owes the room its snapshot */private forkPending = false+ /**+ * This replica carries offline-fork contributions that live only in its doc+ * VALUES + restored registers, never as replayable log ops. `forkPending`+ * drives the ONE broadcast at our own hello and is cleared once the relay has+ * our server snapshot; this stays set for the session, because a peer that+ * joins LATER still can't learn those contributions from the log. Online late+ * joiners recover from the relay's server snapshot, but a same-machine tab+ * joins over BroadcastChannel, which has no replay — so we re-snap each new+ * peer while this holds (see onFrame 'hello').+ */+ private carriesForkState = false+/** the loaded doc arrived carrying collab creds (was saved/shared) */private bornWithCollab = false/** the user opted in this session (saved, or hit "Start live session") */@@ -444,6 +456,7 @@ export class SyncSession {// merge the fork BOTH ways (see docs/collab-design.md)this.state = this.host.engine.fromJSON(this.actor, JSON.parse(JSON.stringify(saved)))this.forkPending = true+ this.carriesForkState = true} else {// no saved state, or state from the pre-composite-key era (v1) — that// scheme collapsed same-id-on-many-slides, so it is discarded and the@@ -670,6 +683,7 @@ export class SyncSession {console.error('[bento-sync] diff failed; recovering via snapshot', err)this.shadow = JSON.stringify(this.store.doc)this.forkPending = true+ this.carriesForkState = truetry {// inlined rather than this.snapshot() — that calls flush(), and flush()// is our caller@@ -693,6 +707,7 @@ export class SyncSession {if (f.a === this.actor) returnswitch (f.t) {case 'hello': {+ const newcomer = !this.peersMap.has(f.a)this.touchPeer(f.a, f.p)// answer so the newcomer learns us + catch them up from our log,// AND tell them our vv so ops they minted before connecting (which@@ -701,6 +716,16 @@ export class SyncSession {this.send({ t: 'need', a: this.actor, vv: this.state.vv })const missing = this.state.missingFor(this.log, f.vv)if (missing.length) this.send({ t: 'ops', a: this.actor, ops: missing })+ // A fork's offline contributions aren't in the log — the log catch-up+ // above can't convey them. We snapshot them ONCE at our own hello, which+ // a peer that joins LATER misses; re-send to each genuinely new peer so+ // a same-machine tab opened later (BroadcastChannel has no replay) still+ // merges our fork. Online peers also get it from the relay snapshot; the+ // merge is idempotent, so a duplicate is harmless.+ if (newcomer && this.carriesForkState) {+ const s = this.snapshot()+ this.send({ t: 'snap', a: this.actor, doc: s.doc, state: s.state })+ }break}case 'ops':@@ -1034,7 +1059,15 @@ export class SyncSession {const view = this.host.captureView?.()try {const res = this.state.mergeSnapshot(this.store.doc, rdoc, rstate)- if (res.changed) this.afterRemoteChange(true, view)+ if (res.changed) {+ this.afterRemoteChange(true, view)+ // We absorbed register-only state a snapshot carried — it isn't in our+ // log, so a peer that joins later can't learn it from our catch-up. Carry+ // it onward: re-snap new peers too (bounded once-per-peer, see 'hello').+ // This is what converges a 3-tab offline chain (A forks, B merges A, C+ // joins asking B) over replay-less BroadcastChannel.+ this.carriesForkState = true+ }} finally {this.applying = false}diff --git a/scripts/test-sync-session.ts b/scripts/test-sync-session.tsindex 167e5eea..280ff7e1 100644--- a/scripts/test-sync-session.ts+++ b/scripts/test-sync-session.ts@@ -405,6 +405,109 @@ H('cumulative offload picks the largest inline assets when the total overflows')ok(!p4.has('svg') && p4.has('png'), 'a raw-SVG asset stays inline (nothing to blob); the offloadable one goes');}+// A fork's offline contributions live only in its doc values + restored+// registers, never as replayable log ops. It snapshots them once at its own+// hello; a peer that joins LATER (a same-machine tab, over replay-less+// BroadcastChannel) misses that and never converges. The fork must re-send its+// snapshot to each genuinely new peer.+H('a fork re-sends its snapshot to a peer that joins later');+{+ // Build a saved FORK file: a shared doc, edited, with the CRDT state stamped+ // in (what an offline-edited copy carries on disk).+ const base = newDoc(); base.docId = `fork-${Math.random().toString(36).slice(2, 8)}`;+ (base as unknown as { collab: { room: string; key: string; on: boolean } }).collab = { room: 'r', key: 'k', on: true };+ const seed = new Store(JSON.parse(JSON.stringify(base)));+ const sseed = new SyncSession(seed);+ seed.commit(() => { seed.doc.title = 'forked offline'; });+ await settle();+ (sseed as unknown as { stampInto: (d: unknown) => void }).stampInto(seed.doc);+ sseed.stop?.();+ const forkFile = JSON.parse(JSON.stringify(seed.doc));+ ok(!!forkFile.collab?.sync, 'the saved fork carries a stamped CRDT state');++ // Open the fork; capture what it sends.+ const A = new Store(JSON.parse(JSON.stringify(forkFile)));+ const sA = new SyncSession(A);+ const sent: Array<{ t: string }> = [];+ sA.addTransport(() => ({ send: (f: { t: string }) => sent.push(f), close() {} }) as never);+ ok((sA as unknown as { carriesForkState: boolean }).carriesForkState === true,+ 'a restored fork knows it carries un-logged state');++ const hello = (a: string) => (sA as unknown as { onFrame: (f: unknown) => void })+ .onFrame({ t: 'hello', a, vv: {}, p: {}, pv: SYNC_V });++ // a brand-new peer announces itself → the fork answers with a snapshot+ sent.length = 0;+ hello('late-tab');+ const snap = sent.find((f) => f.t === 'snap') as undefined | { doc: { title?: string } };+ ok(!!snap, 'the fork answers a new peer’s hello with a snapshot');+ ok(snap?.doc?.title === 'forked offline', 'the snapshot carries the fork’s content');++ // a repeat hello from a peer we already know must NOT re-snap+ sent.length = 0;+ hello('late-tab');+ ok(!sent.some((f) => f.t === 'snap'), 'a repeat hello from a known peer is not re-snapped');++ sA.stop?.();+}++H('a non-fork session does not snap new peers (log catch-up suffices)');+{+ const plain = newDoc(); plain.docId = `plain-${Math.random().toString(36).slice(2, 8)}`;+ const A = new Store(JSON.parse(JSON.stringify(plain)));+ const sA = new SyncSession(A);+ const sent: Array<{ t: string }> = [];+ sA.addTransport(() => ({ send: (f: { t: string }) => sent.push(f), close() {} }) as never);+ ok((sA as unknown as { carriesForkState: boolean }).carriesForkState === false,+ 'a fresh adopt carries no fork state');+ sent.length = 0;+ (sA as unknown as { onFrame: (f: unknown) => void })+ .onFrame({ t: 'hello', a: 'peer2', vv: {}, p: {}, pv: SYNC_V });+ ok(!sent.some((f) => f.t === 'snap'), 'a non-fork does not snap; the op log catches peers up');+ sA.stop?.();+}++// Offline chain: A forks, B merges A's snapshot (so B holds that state only in+// registers), then C joins asking B. B must carry the fork onward — otherwise C,+// a third same-machine tab with no relay replay, never converges.+H('a merged-in fork is carried onward to a third tab (offline chain)');+{+ const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v));+ const docId = `chain-${Math.random().toString(36).slice(2, 8)}`;+ // A: build + open the fork+ const base = newDoc(); base.docId = docId;+ (base as unknown as { collab: { room: string; key: string; on: boolean } }).collab = { room: 'r', key: 'k', on: true };+ const seed = new Store(clone(base)); const sseed = new SyncSession(seed);+ seed.commit(() => { seed.doc.title = 'forked offline'; });+ await settle();+ (sseed as unknown as { stampInto: (d: unknown) => void }).stampInto(seed.doc);+ sseed.stop?.();+ const A = new Store(clone(seed.doc)); const sA = new SyncSession(A);+ const aSent: Array<{ t: string; doc?: unknown; state?: unknown }> = [];+ sA.addTransport(() => ({ send: (f: { t: string }) => aSent.push(f), close() {} }) as never);+ (sA as unknown as { onFrame: (f: unknown) => void }).onFrame({ t: 'hello', a: 'B', vv: {}, p: {}, pv: SYNC_V });+ const aSnap = aSent.find((f) => f.t === 'snap') as undefined | { doc: unknown; state: unknown };+ ok(!!aSnap, 'A offered its fork snapshot');+ sA.stop?.();++ // B: a pristine replica that MERGES A's snapshot (holds the state in registers)+ const pristine = newDoc(); pristine.docId = docId; pristine.title = 'original';+ const B = new Store(clone(pristine)); const sB = new SyncSession(B);+ const bSent: Array<{ t: string; doc?: { title?: string } }> = [];+ sB.addTransport(() => ({ send: (f: { t: string }) => bSent.push(f), close() {} }) as never);+ (sB as unknown as { applySnapshot: (d: unknown, s: unknown) => void }).applySnapshot(aSnap!.doc, aSnap!.state);+ ok(B.doc.title === 'forked offline', 'B merged the fork content');+ ok((sB as unknown as { carriesForkState: boolean }).carriesForkState === true,+ 'B now carries the fork state onward');++ // C: a third tab joins later, asking B — B must re-snap it+ bSent.length = 0;+ (sB as unknown as { onFrame: (f: unknown) => void }).onFrame({ t: 'hello', a: 'C', vv: {}, p: {}, pv: SYNC_V });+ const bSnap = bSent.find((f) => f.t === 'snap') as undefined | { doc?: { title?: string } };+ ok(!!bSnap && bSnap.doc?.title === 'forked offline', 'B re-sends the fork to the third tab');+ sB.stop?.();+}+// A read-only live-viewer copy (store.commit is inert) must still show a// relay-offloaded image. resolveBlobs used to materialise through store.commit,// so the bytes never landed and the picture stayed blank; it now applies them