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/save-queue.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. The accounting below (one save on the
5// wire at a time, every batch kept until it is acknowledged or refused,
6// flush() a real barrier) replaced the original's single inFlight slot
7// on #27; Docs takes the same fix on fix/save-queue-accounting.
8// fixtures/save-queue.mjs — the editor's save queue, factored out of
9// fixtures/editor-entry.js so its retry/drop logic can be exercised
10// under plain Node with no DOM, no ProseMirror, and no real Y.Doc —
11// see fixtures/save-queue.test.mjs.
12//
13// This is fix round 1's F1 fix. The original inline version in
14// editor-entry.js requeued a failed batch unconditionally: right for
15// a network blip or a 500 (worth retrying), catastrophic for a 4xx
16// (the core has already looked at these exact bytes and refused
17// them — retrying is futile, and worse, the NEXT flush would run
18// Y.mergeUpdates(queue) over the requeued batch plus whatever the
19// person typed since, merging every later edit into a batch that can
20// never be accepted. A ~1.2MB paste that gets 413 would then also
21// carry away everything typed afterwards, forever, with nothing
22// shown on screen — reproduced for real against a running server
23// before this fix went in.
24//
25// The fix: classify the response. A network failure (post() rejects)
26// or a 5xx is retryable — our own fault or a transient one, so the
27// bytes go back on the queue and a retry is scheduled. A 4xx is
28// permanent — the bytes themselves are the problem, so the batch is
29// dropped (never requeued, never merged into) and the failure is
30// reported instead of hidden. Ordinary edits keep flowing through the
31// same queue immediately afterwards, unaffected.
32//
33// post/mergeUpdates/setTimeoutFn are injected rather than imported so
34// the test can drive this with tiny byte arrays, a stub network call,
35// and a fake clock instead of real Yjs updates, a real fetch, and
36// real timers — the control flow being tested does not depend on any
37// of those being real.
38// ── The accounting (Astra, #27) ─────────────────────────────────────
39//
40// The original kept one inFlight slot. A second flush while a save was
41// on the wire started another, overwrote the slot, and the first
42// batch's bytes vanished from pendingBytes() — an unload then beaconed
43// nothing for it — and a flush() after the second save resolved while
44// the first was still outstanding. And flush() resolved on a retry as if
45// it were a save, so the editor moved its stage to a slide the server
46// did not have yet.
47//
48// Now:
49// - one save is on the wire at a time. Whatever is enqueued meanwhile
50// waits in queue and goes, merged, as soon as that save is answered;
51// - every update has a number, and a batch carries the range it holds.
52// The batch on the wire stays in inFlight until its answer, so
53// pendingBytes() is exactly every update not yet acknowledged or
54// refused: the one on the wire and everything queued, merged;
55// - a retry puts its batch back at the front of the queue, numbers and
56// all, and nothing is settled by it;
57// - flush() sends now whatever is queued and resolves only once every
58// update enqueued before the call has been answered for good: true
59// when all of them were saved, false when any was refused. A flush
60// through a retry waits for the retry. A refusal is final: its batch
61// is dropped, as before;
62// - 'ok' is said only when nothing is owed: an answered save with more
63// queued behind it says 'saving'.
64//
65// What this cannot keep: an edit made between a batch leaving and its
66// refusal arriving was written under the same Yjs client, after the
67// refused clocks, and is already queued behind it. Nothing can
68// integrate it, so it is lost with the refused batch.
69// ── A link that is still loading (Paul, Safari, 2026-10-26, Docs #94;
70// branch fix/safari-save-stall here too) ──
71//
72// WebKit refuses every ordinary fetch() and XMLHttpRequest a page starts
73// while its main frame is waiting for a navigation's answer: the promise
74// rejects at once with "TypeError: Load failed", and no request is sent.
75// The page is still on screen and still editable the whole time, and a
76// navigation that is answered with a download, or not answered at all (a
77// link to an instance that is restarting or waking), never takes it away.
78// Every save in that state was refused that way, and this queue, reading
79// a rejection as a network failure, said "Trouble saving. Retrying…" and
80// retried four times a second with requests that never left the browser:
81// the edge logged no POSTs, and a reload, which ends the navigation,
82// cleared it. Chromium sends them. Found in Docs; Slides' queue is the
83// same code.
84//
85// A keepalive request is the one kind WebKit still sends then (measured in
86// WKWebView and Playwright's WebKit: fetch and XHR refused; keepalive fetch
87// and sendBeacon sent), and it is also what a save is: a request that must
88// reach the server whatever the page does next, including leave, which
89// otherwise cancels the save on the wire as the next page commits. So a
90// save goes keepalive. Browsers cap what keepalive requests may carry at
91// 64KiB, in flight at once, so a batch is at most KEEPALIVE_BYTES, half
92// that, leaving the rest for the beacon an unload sends (which leaves out a
93// keepalive save on the wire, pendingBytes). A batch is packed by the sum
94// of its updates' sizes, and a large one goes gzipped (saveRequest), so
95// what is sent is usually smaller still; an edit too large even then (a
96// very large paste) goes as an ordinary request, and is the one save a
97// pending navigation in WebKit can still hold up. The page then says
98// nothing, because nothing has failed (reachable), and retries.
99//
100// One save is on the wire at a time, so a save that is never answered
101// would stop saving for the rest of the page's life, and two things leave
102// one unanswered. A request that hangs (a connection that died without
103// closing) is aborted after saveTimeoutMs — thirty seconds, and a second
104// more for every 8KB it carries, so a large paste on a slow connection is
105// not cut off while it is still uploading — which is a real failure and
106// retried as one. And WebKit never settles the promise of a keepalive
107// request answered while its page was in the back/forward cache — the
108// request completes, the page never hears (measured in WKWebView: leave
109// with a save on the wire, come back, and nothing after it was ever sent,
110// its own timeout included). So the queue does not rely on the promise:
111// a save not answered within answerTimeoutMs, five seconds after its own
112// timeout, is given up and sent again, and resume(), on a page shown again
113// from that cache, sends again at once whatever was on the wire as it
114// left. Sending a save twice costs a row and loses nothing: Yjs integrates
115// an update it already has as nothing.
116export const KEEPALIVE_BYTES = 32 * 1024
117// QUIET_MAX_MS caps the backoff of retries the browser refuses quietly.
118export const QUIET_MAX_MS = 4000
119export const SAVE_TIMEOUT_MS = 30000
120
121export function saveTimeoutMs(bytes) {
122 return SAVE_TIMEOUT_MS + Math.ceil(bytes.byteLength / 8)
123}
124
125export function answerTimeoutMs(bytes) {
126 return saveTimeoutMs(bytes) + 5000
127}
128
129// COMPRESS_FROM is the smallest save worth compressing: below it gzip's
130// own framing costs more than it saves, and keepalive is not in doubt.
131export const COMPRESS_FROM = 1024
132
133// gzip compresses bytes, or answers null where the browser cannot
134// (CompressionStream: Safari 16.4, Chrome 80, Firefox 113). Written to the
135// stream directly, never through a Blob or a Response: while a link the
136// page opened is loading, WebKit fails every Blob read too
137// ("NotReadableError: The I/O read operation failed", measured in
138// WKWebView), which is exactly when this matters.
139export async function gzip(bytes) {
140 if (typeof CompressionStream !== 'function') return null
141 const cs = new CompressionStream('gzip')
142 const writer = cs.writable.getWriter()
143 writer.write(bytes).catch(() => {})
144 writer.close().catch(() => {})
145 const reader = cs.readable.getReader()
146 const chunks = []
147 let size = 0
148 for (;;) {
149 const { done, value } = await reader.read()
150 if (done) break
151 chunks.push(value)
152 size += value.byteLength
153 }
154 const out = new Uint8Array(size)
155 let at = 0
156 for (const c of chunks) {
157 out.set(c, at)
158 at += c.byteLength
159 }
160 return out
161}
162
163// saveRequest is the fetch init for posting a batch, as editor-entry.js
164// sends it. A save of COMPRESS_FROM or more goes gzipped (the server
165// gunzips it, live.go's readPostedUpdate), so that far fewer edits are
166// too large for a keepalive request: pasted text compresses three to five
167// times. Whether it goes keepalive is decided on what is actually sent.
168export async function saveRequest(bytes, { timeoutMs, compress = true } = {}) {
169 const headers = { 'Content-Type': 'application/octet-stream' }
170 let body = bytes
171 if (compress && bytes.byteLength >= COMPRESS_FROM) {
172 const zipped = await gzip(bytes).catch(() => null)
173 if (zipped && zipped.byteLength < bytes.byteLength) {
174 body = zipped
175 headers['Content-Encoding'] = 'gzip'
176 }
177 }
178 const init = {
179 method: 'POST',
180 credentials: 'same-origin',
181 headers,
182 body,
183 keepalive: body.byteLength <= KEEPALIVE_BYTES,
184 }
185 if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') init.signal = AbortSignal.timeout(timeoutMs ?? saveTimeoutMs(body))
186 return init
187}
188
189// REFUSED_GZIP are the answers a server that does not gunzip gives a
190// gzipped save: it reads the compressed bytes as the update and refuses
191// them (Docs answers 400, Slides 422), or refuses the encoding (415).
192const REFUSED_GZIP = new Set([400, 415, 422])
193
194// createPoster is the queue's post: it sends a batch as saveRequest says,
195// and calls onWire(keepalive) as it does. A gzipped save answered with one
196// of REFUSED_GZIP is sent once more as it is, and every later save of this
197// page goes uncompressed, before the queue sees the answer: the queue drops
198// a batch a 4xx answers, so a tab still on this bundle after a rollback to
199// a server that does not gunzip, or behind a hop that strips
200// Content-Encoding, would otherwise lose every save of 1KB or more (Claude
201// Fable on Docs #94, round 2). A batch the server really refuses is
202// refused again, and costs one request more.
203export function createPoster({ url, fetchFn = (...args) => fetch(...args) }) {
204 let plainOnly = false
205 return async function post(bytes, onWire = () => {}) {
206 let init = await saveRequest(bytes, { compress: !plainOnly })
207 onWire(init.keepalive)
208 let res = await fetchFn(url, init)
209 if (init.headers['Content-Encoding'] === 'gzip' && REFUSED_GZIP.has(res.status)) {
210 plainOnly = true
211 init = await saveRequest(bytes, { compress: false })
212 onWire(init.keepalive)
213 res = await fetchFn(url, init)
214 }
215 return res
216 }
217}
218
219// reachable is the probe a save that was refused without an answer is
220// followed by (createSaveQueue's probe): true if a request of either kind
221// gets an answer from url. A keepalive one first, which WebKit still sends
222// while a link the page opened is loading, then an ordinary one, which the
223// browser still sends when keepalive's 64KiB is spent. If either gets an
224// answer the server is there and it was the browser that refused the save,
225// so nothing has failed; only when both fail is the save's failure real.
226export async function reachable(url, fetchFn = fetch) {
227 for (const keepalive of [true, false]) {
228 try {
229 const init = { method: 'HEAD', cache: 'no-store', credentials: 'same-origin', keepalive }
230 if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') init.signal = AbortSignal.timeout(5000)
231 await fetchFn(url, init)
232 return true
233 } catch {
234 // the next kind, then false
235 }
236 }
237 return false
238}
239
240export function createSaveQueue({ post, mergeUpdates, onStatus, debounceMs = 2000, maxBatchBytes = Infinity, answerTimeoutMs = Infinity, probe = null, setTimeoutFn = setTimeout, clearTimeoutFn = clearTimeout }) {
241 // queue is [{ id, update }] not yet sent; inFlight is the batch on the
242 // wire, { lo, hi, bytes, entries }.
243 let queue = []
244 let inFlight = null
245 let timer = null
246 let status = 'ok'
247 let lastId = 0
248 // doneThrough is the highest id answered for good (saved or refused):
249 // ids are answered in order, because one batch is on the wire at a time
250 // and a retried batch goes back in front of everything after it.
251 let doneThrough = 0
252 const refused = [] // [lo, hi] ranges dropped by a 4xx
253 let waiters = [] // { from, to, resolve } from flush()
254 // quiet counts the retries in a row the browser refused while the server
255 // answered the probe: they back off (answered).
256 let quiet = 0
257
258 function report(next) {
259 // 'failed' is sticky: once bytes are known dropped, a later
260 // successful save must not quietly erase that history from
261 // view — the person still needs to know something did not make
262 // it, even after the next paragraph saves fine.
263 if (status === 'failed' && next !== 'failed') return
264 status = next
265 if (onStatus) onStatus(status)
266 }
267
268 function settle() {
269 const still = []
270 for (const w of waiters) {
271 if (doneThrough < w.to) {
272 still.push(w)
273 continue
274 }
275 w.resolve(!refused.some(([lo, hi]) => hi > w.from && lo <= w.to))
276 }
277 waiters = still
278 }
279
280 function schedule(ms) {
281 if (timer) return
282 timer = setTimeoutFn(() => {
283 timer = null
284 send()
285 }, ms)
286 }
287
288 // send puts the queue on the wire, unless a save is there already: it
289 // goes the moment that one is answered.
290 function send() {
291 if (inFlight || !queue.length) return
292 if (timer) {
293 clearTimeoutFn(timer)
294 timer = null
295 }
296 // As many queued updates as fit in maxBatchBytes, and always at least
297 // one: the rest go as soon as this is answered, so a long outage's
298 // worth of typing still goes as keepalive-sized saves.
299 let take = 1
300 let size = queue[0].update.byteLength
301 while (take < queue.length && size + queue[take].update.byteLength <= maxBatchBytes) {
302 size += queue[take].update.byteLength
303 take++
304 }
305 const entries = queue.slice(0, take)
306 queue = queue.slice(take)
307 const bytes = entries.length === 1 ? entries[0].update : mergeUpdates(entries.map(e => e.update))
308 const batch = { lo: entries[0].id, hi: entries[entries.length - 1].id, bytes, entries }
309 inFlight = batch
310 // answerTimeoutMs is a number, or a function of the batch's bytes.
311 const waitMs = typeof answerTimeoutMs === 'function' ? answerTimeoutMs(bytes) : answerTimeoutMs
312 if (Number.isFinite(waitMs)) batch.timer = setTimeoutFn(() => giveUp(batch, 'retrying'), waitMs)
313 // post calls onWire(keepalive) as it puts the batch on the wire, so
314 // pendingBytes can leave out a keepalive save, which outlives the page.
315 const onWire = (keepalive) => { batch.keepalive = !!keepalive }
316 Promise.resolve()
317 .then(() => post(bytes, onWire))
318 .then(r => answered(batch, r), () => answered(batch, null))
319 }
320
321 // giveUp stops waiting for batch, which is put back in front to go
322 // again: after reporting next ('retrying' when it timed out), or with
323 // nothing said when the page has simply been away.
324 function giveUp(batch, next) {
325 if (inFlight !== batch) return
326 inFlight = null
327 if (batch.timer) clearTimeoutFn(batch.timer)
328 queue = batch.entries.concat(queue)
329 if (next) {
330 report(next)
331 schedule(debounceMs)
332 } else {
333 send()
334 }
335 }
336
337 function answered(batch, r) {
338 // An answer for a save already given up is ignored: its updates were
339 // sent again and are settled by that answer.
340 if (inFlight !== batch) return
341 if (batch.timer) clearTimeoutFn(batch.timer)
342 inFlight = null
343 if (r) quiet = 0
344 if (r && r.ok) {
345 doneThrough = batch.hi
346 // 'ok' means nothing is owed. With edits queued behind this save it
347 // is 'saving': they go on the wire just below (Claude Fable, #27:
348 // the line said Saved for a whole round trip with them unsent).
349 report(queue.length ? 'saving' : 'ok')
350 } else if (r && r.status >= 400 && r.status < 500) {
351 // Permanent: drop it. Do not requeue, do not merge later edits
352 // into it — see this module's own header comment.
353 doneThrough = batch.hi
354 refused.push([batch.lo, batch.hi])
355 report('failed')
356 } else {
357 // A network failure or a 5xx: not the bytes' fault, worth
358 // retrying. Back at the front, numbers and all.
359 queue = batch.entries.concat(queue)
360 settle()
361 // A 5xx is the server's answer. A request refused with no answer may
362 // be the browser's doing (WebKit, while a link is loading, or with
363 // keepalive's quota spent), so it is "Trouble saving" only if probe
364 // cannot reach the server either; otherwise the retry goes quietly.
365 // And never after the batch has since been saved.
366 if (r || !probe) {
367 quiet = 0
368 report('retrying')
369 schedule(debounceMs)
370 return
371 }
372 Promise.resolve()
373 .then(() => probe())
374 .then((up) => up, () => false)
375 .then((up) => {
376 if (!up) {
377 quiet = 0
378 if (doneThrough < batch.hi) report('retrying')
379 schedule(debounceMs)
380 return
381 }
382 // The browser is holding saves (a link loading, for as long as
383 // it loads): each retry costs a save and a probe, so they space
384 // out, doubling to QUIET_MAX_MS, until one is answered (Claude
385 // Fable on #94, round 2).
386 quiet++
387 schedule(Math.min(debounceMs * 2 ** quiet, QUIET_MAX_MS))
388 })
389 return
390 }
391 settle()
392 // Whatever waited behind this save goes now.
393 if (queue.length) send()
394 }
395
396 function enqueue(update) {
397 queue.push({ id: ++lastId, update })
398 if (!inFlight) schedule(debounceMs)
399 }
400
401 // flush sends what is queued now and resolves once every update
402 // enqueued before the call has been answered for good: true if all of
403 // them were saved, false if any was refused.
404 function flush() {
405 const to = lastId
406 const from = doneThrough
407 const done = doneThrough >= to
408 ? Promise.resolve(!refused.some(([lo, hi]) => hi > from && lo <= to))
409 : new Promise(resolve => waiters.push({ from, to, resolve }))
410 send()
411 return done
412 }
413
414 // pendingBytes merges whatever is still owed to the server into one
415 // update, for beforeunload to beacon; null when there is nothing to send.
416 // wire says what to do with the batch on the wire: 'all' includes it;
417 // 'plain' only if it did not go keepalive, since a keepalive save
418 // outlives the page and lands anyway; 'none' never. Keepalive saves and
419 // beacons share the browser's 64KiB, so a beacon that repeats a keepalive
420 // save on the wire is refused, and the edits queued behind it with it
421 // (Claude Fable on Docs #94).
422 function pendingBytes({ wire = 'all' } = {}) {
423 const parts = []
424 if (inFlight && (wire === 'all' || (wire === 'plain' && !inFlight.keepalive))) parts.push(inFlight.bytes)
425 for (const e of queue) parts.push(e.update)
426 if (!parts.length) return null
427 return parts.length === 1 ? parts[0] : mergeUpdates(parts)
428 }
429
430 // resume is the page shown again from the back/forward cache: a save
431 // that was on the wire as it left may never be answered, so it goes
432 // again now, and so does anything waiting on a retry's timer.
433 function resume() {
434 if (inFlight) giveUp(inFlight, null)
435 else send()
436 }
437
438 return {
439 enqueue,
440 flush,
441 pendingBytes,
442 resume,
443 // onWire is the batch on the wire: null, 'keepalive', or 'plain' (also
444 // a batch post has not put on the wire yet).
445 get onWire () { return inFlight ? (inFlight.keepalive ? 'keepalive' : 'plain') : null },
446 get status () { return status }
447 }
448}
449