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