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/live-updates.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. onUpdates is awaited, as it is in Docs'
5// copy since its font work: a batch waiting for its font holds the next
6// one behind it, so updates are applied in order and none is dropped.
7// pageLifecycle and what start() does with it — leaving the page closes
8// the stream, coming back from the back/forward cache reopens it and
9// catches up — are Docs' dadf9c1 (#86), copied as written.
10// fixtures/live-updates.mjs — the editor's live-update subscriber,
11// factored out of fixtures/editor-entry.js so its cursor arithmetic
12// and connection policy can be exercised under plain Node with no
13// DOM, no EventSource and no real Y.Doc (fixtures/
14// live-updates.test.mjs). Same shape as save-queue.mjs and
15// resync-controller.mjs, and for the same reason: the control flow
16// being tested does not depend on any of those being real.
17//
18// What it does: an SSE stream tells this tab that the document has
19// content through some seq; this module fetches whatever is newer
20// than its own cursor through the ordinary binary updates endpoint
21// and hands the bytes to its caller. The stream carries no document
22// bytes (see internal/docs/stream.go's own doc comment for why), so
23// everything here is cursor bookkeeping and connection policy.
24//
25// It deliberately owns no DOM. The caller wires visibility and
26// activity events to noteHidden/noteActivity, which keeps this file
27// testable and keeps every listener registration in one place in
28// editor-entry.js.
29
30// IDLE_MS is how long a visible tab with nothing happening keeps its
31// stream open. Platform hibernation is default-on and this app holds
32// one connection per open editor, so a document left open on Friday
33// must not pin its instance awake all weekend (the design spec's §6,
34// and the docs spec's §7.3). Two minutes is well under the server's
35// own five-minute TTL, so an idle tab closes on its own terms rather
36// than waiting to be cut off.
37const IDLE_MS = 120000
38
39// HIDDEN_MS is the same thing for a tab that has been switched away
40// from, and it exists because closing on `hidden` immediately — which
41// is what this module did first — is what a person sees as a flash.
42//
43// The sequence, measured in a real browser rather than reasoned about:
44// tab away, the stream closes; tab back, and the browser paints the
45// document THEN, from what is already in the DOM, which is the version
46// from before you left. The reconnect and its catch-up fetch land 18ms
47// later on a loopback address, and the paragraph visibly rewrites
48// itself. Every tab switch cost one frame of stale text, and no amount
49// of making the reconnect faster removes it, because the paint happens
50// before any round trip can possibly return.
51//
52// So the fix is not to reconnect faster but not to have disconnected.
53// Thirty seconds covers switching between two tabs, which is the whole
54// of the case that flashed, and it is still four times more aggressive
55// than the visible-idle close: a document left open on Friday drops its
56// stream half a minute after you look away, which serves §7.3's
57// hibernation requirement strictly better than the 120s a merely idle
58// visible tab is already allowed.
59const HIDDEN_MS = 30000
60
61// updatesURL is the one place either query string this module (or its
62// caller in editor-entry.js) can ask for gets spelled, so the spelling
63// is pinned by a plain-Node test instead of living twice, inline, in a
64// DOM-bound file this project has no test harness for. handlers.go
65// matches the raw flag as the literal string "1" and nothing else —
66// `raw=true`, `raw=on`, or a bare `raw` all fail silently, with no
67// error and no visible symptom beyond the resync controller refetching
68// the same corrupt snapshot forever — so this is deliberately a pure
69// string builder with no fetch and no DOM, testable by asserting exact
70// output rather than by loading a browser.
71export function updatesURL(base, { since, raw } = {}) {
72 const params = []
73 if (since !== undefined) params.push(`since=${since}`)
74 if (raw) params.push('raw=1')
75 return params.length ? `${base}?${params.join('&')}` : base
76}
77
78// pageLifecycle is the page's own coming and going: pagehide when it is
79// left (navigated away from, or put in the back/forward cache) and
80// pageshow when it comes back from that cache. It is installed once,
81// when this module loads, so it is there before any subscriber exists
82// and so before any stream can be opened (branch review on #86: handlers
83// the editor registered after its first frames missed a page left
84// sooner, or hidden and so running no frames, and its stream stayed
85// open in the cache).
86export function pageLifecycle(target) {
87 const subscribers = new Set()
88 let left = false
89 if (target && typeof target.addEventListener === 'function') {
90 target.addEventListener('pagehide', () => {
91 left = true
92 for (const s of [...subscribers]) s.leave()
93 })
94 target.addEventListener('pageshow', (e) => {
95 const back = left && e && e.persisted
96 left = false
97 if (back) for (const s of [...subscribers]) s.back()
98 })
99 }
100 return {
101 get left() {
102 return left
103 },
104 // subscribe(s) -> unsubscribe. s.leave() and s.back() are called as
105 // the page is left and shown again.
106 subscribe(s) {
107 subscribers.add(s)
108 return () => subscribers.delete(s)
109 },
110 }
111}
112
113const thePage = pageLifecycle(typeof window === 'undefined' ? null : window)
114
115export function createLiveUpdates({
116 initialSeq = 0,
117 // openStream(onEvent, onError) -> { close() }. onEvent receives the
118 // seq an "update" event carried.
119 openStream,
120 // fetchSince(since, { raw }) -> { bytes, seq }. bytes may be empty;
121 // seq is what the server's Slides-Seq header said. raw, when passed
122 // as { raw: true }, is the decode-failure escape hatch: it must
123 // reach the server as the literal query string `raw=1` (handlers.go
124 // matches nothing else), and asks for exactly the doc_updates rows
125 // after `since` with the snapshot lookup skipped entirely — see the
126 // comment on the retry in drain() below for why this exists.
127 fetchSince,
128 onUpdates,
129 onError = () => {},
130 setTimeoutFn = setTimeout,
131 clearTimeoutFn = clearTimeout,
132 idleMs = IDLE_MS,
133 hiddenMs = HIDDEN_MS,
134 // page is the page's lifecycle (pageLifecycle); a test passes its own.
135 page = thePage,
136}) {
137 let cursor = initialSeq
138 let stream = null
139 let idleTimer = null
140 let stopped = false
141
142 // fetching/pending are the whole of the serialization: one request
143 // in flight at a time, and a single bit remembering that something
144 // arrived while it was. Without this a burst of notifications
145 // starts a fetch per event, and their responses race each other
146 // into the Y.Doc.
147 let fetching = false
148 let pending = false
149
150 // One timer, two deadlines. A hidden tab and an idle visible one are
151 // closed by the same mechanism and differ only in how long they get,
152 // so whichever is armed last wins and there is no way for the two to
153 // be pending at once and race each other.
154 function armClose(ms) {
155 if (idleTimer !== null) clearTimeoutFn(idleTimer)
156 idleTimer = setTimeoutFn(() => {
157 idleTimer = null
158 closeStream()
159 }, ms)
160 }
161
162 function armIdle() {
163 armClose(idleMs)
164 }
165
166 function closeStream() {
167 if (idleTimer !== null) {
168 clearTimeoutFn(idleTimer)
169 idleTimer = null
170 }
171 if (!stream) return
172 stream.close()
173 stream = null
174 }
175
176 // openIfClosed is the ONLY place a connection is opened, and every
177 // close above is explicit. Native EventSource reconnection is never
178 // relied on anywhere in this module, and that is load-bearing
179 // rather than fastidious: the browser retries on any server close,
180 // including the idle close this module just chose and the server's
181 // own TTL, so a parked tab would reopen its stream forever and go
182 // on holding a hibernating instance awake. rastrillo's own SSE
183 // handler (jobs/events.go) does rely on native reconnection, which
184 // is right for it — it has no close policy of its own — and is the
185 // one piece of that recipe whose reason does not survive being
186 // moved here.
187 function openIfClosed() {
188 // Never in a page that has been left: it may be in the back/forward
189 // cache, where an open stream holds a connection for nobody.
190 if (stopped || stream || page.left) return
191 stream = openStream(
192 (seq) => {
193 armIdle()
194 // Advisory, never an assignment: this says "there is
195 // something at least this new", and the fetch is what
196 // determines the cursor. A tab that has already seen this
197 // seq — its own write, echoed back — has nothing to do.
198 if (seq > cursor) drain()
199 },
200 (err) => {
201 // A dead stream is a freshness failure, never a save failure:
202 // POST is a different path and edits are still saving, so
203 // this must not reach the save indicator. The connection is
204 // dropped rather than retried on a timer, and the next
205 // activity brings it back.
206 closeStream()
207 onError(err)
208 },
209 )
210 armIdle()
211 }
212
213 async function drain() {
214 if (fetching) {
215 pending = true
216 return
217 }
218 fetching = true
219 try {
220 const from = cursor
221 let res = await fetchSince(from)
222 if (stopped) return
223 try {
224 // Awaited: onUpdates may wait for a font the update introduces
225 // (editor-entry.js), and the next fetch must not be applied
226 // ahead of it. Docs made the same change to its copy.
227 if (res && res.bytes && res.bytes.length) await onUpdates(res.bytes)
228 } catch (decodeErr) {
229 // onUpdates threw: Y.readUpdate hit bytes it could not decode.
230 // The server serves a snapshot without ever calling into the
231 // CRDT core (handlers.go's own comment on raw=1), so it cannot
232 // detect a snapshot corrupted on disk after it was written and
233 // verified — the browser, via this exact throw, is the only
234 // reader that can. Without this retry the resync controller
235 // would refetch the same corrupt bytes forever and the
236 // document would never load. The retry asks for the SAME
237 // range (`from`, unchanged) with the snapshot lookup skipped
238 // entirely, which is the one thing the server has always been
239 // able to serve correctly. A second throw here — from the
240 // retried fetch itself, or from onUpdates on the retried
241 // bytes — is not caught a second time; it falls through to
242 // the outer catch below, which reports it and leaves the
243 // cursor untouched.
244 res = await fetchSince(from, { raw: true })
245 if (stopped) return
246 if (res && res.bytes && res.bytes.length) await onUpdates(res.bytes)
247 }
248 // max, never assignment: a response that overtakes another must
249 // not drag the cursor backwards and cause everything above it
250 // to be fetched and applied a second time.
251 if (res && typeof res.seq === 'number' && res.seq > cursor) cursor = res.seq
252 } catch (err) {
253 // Leave the cursor where it is. Either the bytes were never
254 // received, or they were received twice (plain, then raw) and
255 // neither applied — either way anything else would skip them,
256 // so the next notification (or the connect-time event on the
257 // next reopen) retries from the same place.
258 onError(err)
259 } finally {
260 fetching = false
261 if (pending && !stopped) {
262 pending = false
263 drain()
264 }
265 }
266 }
267
268 // Leaving the page closes the stream at once, rather than leaving it
269 // open in a page nobody is looking at; a page shown again from the
270 // back/forward cache is activity, which reopens it and catches up from
271 // the cursor. Left open, each cached page held one of the browser's six
272 // HTTP/1.1 connections to this host, and after five documents the next
273 // navigation waited about a minute for one (found by the font gate's
274 // generative test in full Chrome, which keeps pages in that cache).
275 let unsubscribe = null
276 const lifecycle = {
277 leave: () => closeStream(),
278 // On the next task, not inside pageshow: WebKit fails a stream opened
279 // while it is still restoring the page (an immediate error, and then
280 // a reconnect of its own that this module no longer holds).
281 back: () => {
282 setTimeoutFn(() => {
283 if (!stopped) openIfClosed()
284 }, 0)
285 },
286 }
287
288 return {
289 start() {
290 stopped = false
291 if (!unsubscribe) unsubscribe = page.subscribe(lifecycle)
292 openIfClosed()
293 },
294
295 // stop is called on teardown and on every resync — the Y.Doc this
296 // was feeding is about to be discarded, so a response still in
297 // flight must not be applied to its replacement.
298 stop() {
299 stopped = true
300 if (unsubscribe) unsubscribe()
301 unsubscribe = null
302 closeStream()
303 },
304
305 // noteOwnSeq records the seq the server assigned to this tab's own
306 // POST, and is where the round trip is saved in the common case.
307 //
308 // The guard is the whole of it: adopt the number only when it is
309 // exactly the next row. If this tab is at 10 and its own write
310 // landed at 43, then rows 11-42 came from somewhere else and have
311 // not been applied here — taking 43 would skip them permanently,
312 // with no later notification able to bring them back, because
313 // every future fetch would ask for what came after 43. Staying at
314 // 10 costs one fetch and loses nothing.
315 noteOwnSeq(seq) {
316 if (typeof seq !== 'number' || !Number.isFinite(seq)) return
317 if (seq === cursor + 1) cursor = seq
318 },
319
320 // noteActivity is any sign of a person: a pointer moving, a
321 // scroll, a key going down, a tab becoming visible, a local edit.
322 // It both defers the idle close and brings a closed stream back.
323 //
324 // "Any activity" is deliberately broad. Visibility, focus and
325 // local edits alone leave the commonest case unhandled — someone
326 // READING a long document on a tab that is already visible and
327 // already focused fires none of them, so the stream would close
328 // on idle and nothing would ever reopen it. That tab is exactly
329 // the watching half of "type in one tab, watch the other", and it
330 // would have gone quietly stale forever.
331 noteActivity() {
332 if (stopped) return
333 if (stream) armIdle()
334 else openIfClosed()
335 },
336
337 // noteHidden is the tab going into the background. It shortens the
338 // deadline rather than closing, so a switch away and back inside
339 // the grace never drops the stream and the tab is already current
340 // when it is painted — see HIDDEN_MS for what the immediate close
341 // looked like to a person.
342 //
343 // Nothing is opened here: a hidden tab with a closed stream stays
344 // closed, because coming back is activity and noteActivity is what
345 // reopens it.
346 noteHidden() {
347 if (stopped || !stream) return
348 armClose(hiddenMs)
349 },
350
351 get cursor() { return cursor },
352 get streaming() { return stream !== null },
353 }
354}
355