oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1// Copied verbatim from Docs (oficina/docs/fixtures/resync-controller.mjs), the first
2// implementation of the live-sync client; Slides is the second, and the
3// extraction to a shared module is slice 4. Only the header name differs:
4// Docs-Seq is Slides-Seq here.
5// fixtures/resync-controller.mjs — the state machine for "the local
6// document has diverged from the server and needs to be rebuilt from
7// server truth," factored out of fixtures/editor-entry.js so it can
8// be driven under plain Node with a stub resync and a fake clock —
9// see fixtures/resync-controller.test.mjs.
10//
11// This is fix round 2's own fix. Round 1's resync() ran once and, on
12// failure, just logged and gave up — its own comment claimed the
13// editor would get "another chance to resync the next time a batch
14// is dropped," which is false: once a batch has already been
15// dropped, the local Y.Doc has already diverged, and every update it
16// produces from then on is encoded relative to content the server
17// never received. core.Handle.Apply does not error on such an
18// update — it has nowhere to attach it, so it returns a real 204 and
19// silently never integrates it. No further 4xx ever arrives to
20// trigger another resync attempt, so one transient resync failure
21// (a dropped connection at exactly the wrong moment, reproduced by
22// the round 2 reviewer by aborting the resync fetch) recreated the
23// silent-204 data loss for the rest of the session. Reproduced again
24// here, deliberately, before this fix: fixtures/resync-controller.
25// test.mjs's own "without retry" case shows attemptResync called
26// exactly once and diverged staying true forever after a failure.
27//
28// The fix: retry the resync itself, with backoff, and again
29// immediately on the browser's own 'online' event — and expose
30// `diverged` so the caller (editor-entry.js) can gate what "saving
31// fine" even means while it is true: a 204 during divergence proves
32// nothing, so no local edit may be treated as saved, and none should
33// even be sent (fix round 2's LOW note: every 204 taken during
34// divergence permanently consumes a maxRetainedUpdates row for
35// nothing).
36//
37// Since then (Slides #27, Docs #88): "relative to content the server
38// never received" was true of the old client id. From the refusal on,
39// the editor writes under a fresh Yjs client id, so what it writes
40// meanwhile depends only on what it touches. Nothing is sent while
41// diverged still; it is kept (editor-entry.js's unsaved) and carried
42// onto the rebuilt document by the resync (carry.mjs), which posts
43// what integrates there, replays a paste that waited for its font when
44// its own updates cannot, and holds back the rest.
45export function createResyncController({
46 attemptResync,
47 onDiverged,
48 onRecovered,
49 // Exponential backoff, capped: 1s, 2s, 4s, 8s, 16s, 30s, 30s, ... —
50 // fast enough to shrug off a one-off blip without the person
51 // noticing, capped low enough that a genuinely offline session
52 // isn't left waiting minutes between attempts once connectivity
53 // does return. The 'online' listener below is the fast path for
54 // that case; backoff is the fallback for everything the browser's
55 // own online/offline signal does not catch (a resync that fails
56 // for a reason other than "no network at all").
57 backoffMs = (attempt) => Math.min(1000 * 2 ** (attempt - 1), 30000),
58 setTimeoutFn = setTimeout,
59 clearTimeoutFn = clearTimeout,
60 addOnlineListener = (fn) => addEventListener('online', fn),
61}) {
62 let diverged = false
63 let resyncing = false
64 let attempt = 0
65 let timer = null
66
67 function scheduleRetry() {
68 attempt++
69 if (timer) clearTimeoutFn(timer)
70 timer = setTimeoutFn(run, backoffMs(attempt))
71 }
72
73 async function run() {
74 // Cancel whatever timer might still be pending, not just forget
75 // it: run() can be entered from three places (a fired timer, an
76 // 'online' event, or reportDivergence() itself calling it
77 // eagerly), and only clearing the local reference without
78 // actually cancelling a still-scheduled OTHER timer would leave
79 // it alive to fire later and trigger an unplanned extra attempt.
80 if (timer) {
81 clearTimeoutFn(timer)
82 timer = null
83 }
84 // A stray trigger or a redundant 'online' event firing after
85 // recovery must not re-run resync against an already-healthy
86 // document — that would silently throw away everything typed
87 // since the last successful resync for no reason.
88 if (!diverged || resyncing) return
89 resyncing = true
90 try {
91 await attemptResync()
92 diverged = false
93 attempt = 0
94 if (onRecovered) onRecovered()
95 } catch (err) {
96 scheduleRetry()
97 } finally {
98 resyncing = false
99 }
100 }
101
102 // reportDivergence is called the moment a batch is known dropped —
103 // before the first resync attempt even starts, per this module's
104 // own header comment ("knowingly diverged" from that instant, not
105 // from whenever the first attempt happens to finish).
106 function reportDivergence() {
107 if (!diverged) {
108 diverged = true
109 attempt = 0
110 if (onDiverged) onDiverged()
111 }
112 run()
113 }
114
115 addOnlineListener(() => {
116 if (diverged) run()
117 })
118
119 return {
120 reportDivergence,
121 get diverged() { return diverged },
122 get resyncing() { return resyncing },
123 }
124}
125