oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

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