| 1 | // fixtures/save-queue.test.mjs — regression test for fix round 1's |
| 2 | // F1: a permanently-rejected batch used to retry forever AND absorb |
| 3 | // every later edit via Y.mergeUpdates, losing all of it silently. |
| 4 | // Reproduced against a real running server (a ~1.2MB paste got a |
| 5 | // real 413, every later flush also 413'd, and the paste plus both |
| 6 | // subsequent small edits were gone after reload) before the fix in |
| 7 | // save-queue.mjs went in. |
| 8 | // |
| 9 | // Runs under Node's own test runner (node --test), no framework |
| 10 | // added: `post`/`mergeUpdates`/timing are all injected by |
| 11 | // createSaveQueue, so this drives the real retry/drop control flow |
| 12 | // with tiny stand-in byte arrays and a short debounce — no DOM, no |
| 13 | // ProseMirror, no real Y.Doc, no browser needed. |
| 14 | import { test } from 'node:test' |
| 15 | import assert from 'node:assert/strict' |
| 16 | import { gunzipSync } from 'node:zlib' |
| 17 | import { createSaveQueue, createPoster, COMPRESS_FROM, saveRequest, saveTimeoutMs, answerTimeoutMs, reachable, KEEPALIVE_BYTES, SAVE_TIMEOUT_MS } from './save-queue.mjs' |
| 18 | |
| 19 | // A fake mergeUpdates that behaves like Y.mergeUpdates for this |
| 20 | // test's purposes: concatenate, in order, so a merged batch's |
| 21 | // identity is checkable byte-for-byte. |
| 22 | function concatUpdates(updates) { |
| 23 | const out = [] |
| 24 | for (const u of updates) out.push(...u) |
| 25 | return new Uint8Array(out) |
| 26 | } |
| 27 | |
| 28 | // until waits for cond, on real timers, for as long as a loaded machine |
| 29 | // may take (a fixed sleep here failed about one run in twenty), and then a |
| 30 | // little longer, so a call that should not happen has the chance to. |
| 31 | async function until(cond, ms = 5000) { |
| 32 | const end = Date.now() + ms |
| 33 | while (!cond() && Date.now() < end) await new Promise((r) => setTimeout(r, 5)) |
| 34 | await new Promise((r) => setTimeout(r, 30)) |
| 35 | } |
| 36 | |
| 37 | function makePostStub(responses) { |
| 38 | const calls = [] |
| 39 | let i = 0 |
| 40 | return { |
| 41 | calls, |
| 42 | post: async (bytes) => { |
| 43 | calls.push(bytes) |
| 44 | const next = responses[Math.min(i, responses.length - 1)] |
| 45 | i++ |
| 46 | if (next.throws) throw new Error('network failure') |
| 47 | return { ok: next.status < 300, status: next.status } |
| 48 | }, |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | test('a permanent 4xx drops its batch instead of retrying it, and does not poison the next edit', async () => { |
| 53 | const { calls, post } = makePostStub([{ status: 413 }, { status: 204 }]) |
| 54 | const statuses = [] |
| 55 | const q = createSaveQueue({ |
| 56 | post, |
| 57 | mergeUpdates: concatUpdates, |
| 58 | onStatus: (s) => statuses.push(s), |
| 59 | debounceMs: 5, |
| 60 | }) |
| 61 | |
| 62 | const bigPaste = new Uint8Array([9, 9, 9]) |
| 63 | q.enqueue(bigPaste) |
| 64 | await until(() => q.status === 'failed') |
| 65 | |
| 66 | assert.equal(calls.length, 1, 'the oversized batch should be posted exactly once') |
| 67 | assert.deepEqual(calls[0], bigPaste) |
| 68 | assert.equal(q.status, 'failed', 'a permanent rejection must be reported, not swallowed') |
| 69 | assert.equal(q.pendingBytes(), null, 'a dropped batch must not sit in the queue forever') |
| 70 | |
| 71 | // The crux of F1: an edit typed after the permanent rejection must |
| 72 | // reach the server on its own, never merged with the dead batch. |
| 73 | const secondEdit = new Uint8Array([1, 2, 3]) |
| 74 | q.enqueue(secondEdit) |
| 75 | await until(() => calls.length === 2 && q.pendingBytes() === null) |
| 76 | |
| 77 | assert.equal(calls.length, 2, 'the later edit must be posted, not swallowed') |
| 78 | assert.deepEqual(calls[1], secondEdit, 'the later edit must be posted on its own — merging it with the dead 413 batch would 413 it too') |
| 79 | assert.equal(statuses.filter((s) => s === 'failed').length >= 1, true) |
| 80 | assert.equal(q.status, 'failed', "the indicator must stay sticky — a later success must not hide that something was lost") |
| 81 | }) |
| 82 | |
| 83 | test('a network failure or a 5xx is retried, not dropped', async () => { |
| 84 | const { calls, post } = makePostStub([{ throws: true }, { status: 204 }]) |
| 85 | const q = createSaveQueue({ post, mergeUpdates: concatUpdates, debounceMs: 5 }) |
| 86 | |
| 87 | const edit = new Uint8Array([7, 7]) |
| 88 | q.enqueue(edit) |
| 89 | await until(() => calls.length === 2 && q.status === 'ok') |
| 90 | |
| 91 | assert.equal(calls.length, 2, 'a network failure must be retried automatically, not just left queued') |
| 92 | assert.deepEqual(calls[0], edit) |
| 93 | assert.deepEqual(calls[1], edit, 'the retried batch must be the exact same bytes, not lost or duplicated') |
| 94 | assert.equal(q.status, 'ok', 'once the retry lands, nothing was actually lost') |
| 95 | }) |
| 96 | |
| 97 | test('a 500 is retried the same way a network failure is, never dropped', async () => { |
| 98 | const { calls, post } = makePostStub([{ status: 500 }, { status: 204 }]) |
| 99 | const q = createSaveQueue({ post, mergeUpdates: concatUpdates, debounceMs: 5 }) |
| 100 | |
| 101 | q.enqueue(new Uint8Array([4, 4])) |
| 102 | await until(() => calls.length === 2 && q.status === 'ok') |
| 103 | |
| 104 | assert.equal(calls.length, 2, 'a 5xx is our own fault, not the client bytes — it must retry, not drop') |
| 105 | assert.equal(q.status, 'ok') |
| 106 | }) |
| 107 | |
| 108 | // ── The accounting (Astra, on Slides #27) ─────────────────────────── |
| 109 | // The queue kept one inFlight slot. When the debounce fired while a |
| 110 | // save was still on the wire — a slow connection, a big paste — a |
| 111 | // second save went out beside the first and overwrote the slot; the |
| 112 | // first one's answer then cleared it, so pendingBytes() said nothing |
| 113 | // was owed while the second save was still out, and a close in that |
| 114 | // moment beaconed nothing. And a first save that failed after the |
| 115 | // second had gone was retried behind it, out of order. |
| 116 | // |
| 117 | // A post a test answers by hand, and a clock it fires by hand. |
| 118 | function harness(options = {}) { |
| 119 | const posts = [] |
| 120 | const timers = [] |
| 121 | const statuses = [] |
| 122 | const q = createSaveQueue({ |
| 123 | post: (bytes, onWire) => new Promise((resolve, reject) => posts.push({ |
| 124 | bytes: [...bytes], |
| 125 | onWire, |
| 126 | answer: (status) => (status === 0 ? reject(new Error('network failure')) : resolve({ ok: status < 300, status })), |
| 127 | })), |
| 128 | mergeUpdates: concatUpdates, |
| 129 | onStatus: (s) => statuses.push(s), |
| 130 | debounceMs: 1000, |
| 131 | setTimeoutFn: (fn) => { timers.push(fn); return timers.length }, |
| 132 | clearTimeoutFn: () => {}, |
| 133 | ...options, |
| 134 | }) |
| 135 | const tick = () => new Promise((resolve) => setImmediate(resolve)) |
| 136 | // fire runs the debounce timers that are due, as the clock would. |
| 137 | const fire = async () => { for (const fn of timers.splice(0)) fn(); await tick() } |
| 138 | return { q, posts, statuses, tick, fire } |
| 139 | } |
| 140 | const u = (n) => new Uint8Array([n]) |
| 141 | const settled = (p) => { let v = 'pending'; p.then((x) => { v = x }); return () => v } |
| 142 | |
| 143 | test('an edit made while a save is on the wire waits for it, and both stay owed until answered', async () => { |
| 144 | const { q, posts, tick, fire } = harness() |
| 145 | q.enqueue(u(1)) |
| 146 | await fire() |
| 147 | assert.equal(posts.length, 1) |
| 148 | q.enqueue(u(2)) |
| 149 | await fire() |
| 150 | assert.equal(posts.length, 1, 'a second save went on the wire beside the first') |
| 151 | assert.deepEqual([...q.pendingBytes()], [1, 2], 'an update on the wire or queued dropped out of the bytes owed') |
| 152 | posts[0].answer(204) |
| 153 | await tick() |
| 154 | assert.equal(posts.length, 2, 'the queued edit did not go as soon as the first save was answered') |
| 155 | assert.deepEqual(posts[1].bytes, [2]) |
| 156 | assert.deepEqual([...q.pendingBytes()], [2], 'the save still on the wire dropped out of the bytes owed') |
| 157 | posts[1].answer(204) |
| 158 | await tick() |
| 159 | assert.equal(q.pendingBytes(), null) |
| 160 | assert.equal(q.status, 'ok') |
| 161 | }) |
| 162 | |
| 163 | test('a save that fails while a later edit waits is retried first, with the later edit behind it', async () => { |
| 164 | const { q, posts, statuses, tick, fire } = harness() |
| 165 | q.enqueue(u(1)) |
| 166 | await fire() |
| 167 | q.enqueue(u(2)) |
| 168 | await fire() |
| 169 | posts[0].answer(500) |
| 170 | await tick() |
| 171 | assert.deepEqual([...q.pendingBytes()], [1, 2], 'a batch being retried dropped out of the bytes owed') |
| 172 | assert.equal(statuses.at(-1), 'retrying') |
| 173 | assert.equal(posts.length, 1, 'the later edit went to the server ahead of the failed one') |
| 174 | await fire() |
| 175 | assert.deepEqual(posts.map((p) => p.bytes), [[1], [1, 2]], 'the retry must carry the failed edit first, then the later one') |
| 176 | posts[1].answer(204) |
| 177 | await tick() |
| 178 | assert.equal(q.pendingBytes(), null) |
| 179 | assert.equal(q.status, 'ok') |
| 180 | }) |
| 181 | |
| 182 | test('a refusal is final and is never merged into the edit that waited behind it', async () => { |
| 183 | const { q, posts, statuses, tick, fire } = harness() |
| 184 | q.enqueue(u(9)) |
| 185 | await fire() |
| 186 | q.enqueue(u(1)) |
| 187 | await fire() |
| 188 | posts[0].answer(413) |
| 189 | await tick() |
| 190 | assert.equal(statuses.at(-1), 'failed') |
| 191 | assert.equal(posts.length, 2) |
| 192 | assert.deepEqual(posts[1].bytes, [1], 'the refused batch was merged into the next save') |
| 193 | assert.deepEqual([...q.pendingBytes()], [1]) |
| 194 | posts[1].answer(204) |
| 195 | await tick() |
| 196 | assert.equal(q.pendingBytes(), null) |
| 197 | assert.equal(q.status, 'failed', 'the indicator stays sticky') |
| 198 | }) |
| 199 | |
| 200 | test('flush() resolves once every earlier edit is answered: true if saved, false if refused', async () => { |
| 201 | const { q, posts, tick, fire } = harness() |
| 202 | q.enqueue(u(1)) |
| 203 | await fire() |
| 204 | q.enqueue(u(2)) |
| 205 | const both = settled(q.flush()) |
| 206 | await tick() |
| 207 | assert.equal(posts.length, 1, 'flush put a second save on the wire beside the first') |
| 208 | posts[0].answer(204) |
| 209 | await tick() |
| 210 | assert.equal(both(), 'pending', 'flush resolved while an edit made before it was still unsaved') |
| 211 | posts[1].answer(204) |
| 212 | await tick() |
| 213 | assert.equal(both(), true) |
| 214 | q.enqueue(u(5)) |
| 215 | const refused = settled(q.flush()) |
| 216 | await tick() |
| 217 | posts[2].answer(500) |
| 218 | await tick() |
| 219 | assert.equal(refused(), 'pending', 'flush resolved on a 500 as if the bytes were saved') |
| 220 | await fire() |
| 221 | posts[3].answer(413) |
| 222 | await tick() |
| 223 | assert.equal(refused(), false) |
| 224 | }) |
| 225 | |
| 226 | test('the queue says saving, not ok, while an answered save leaves another to send', async () => { |
| 227 | // Claude Fable on #87: A answered with B queued reported 'ok' with B |
| 228 | // still unsent. Docs shows no word for saving, but the queue must not |
| 229 | // say nothing is owed while something is. |
| 230 | const { q, posts, statuses, tick, fire } = harness() |
| 231 | q.enqueue(u(1)) |
| 232 | await fire() |
| 233 | q.enqueue(u(2)) |
| 234 | posts[0].answer(204) |
| 235 | await tick() |
| 236 | assert.equal(statuses.at(-1), 'saving', 'ok was said with a save still owed') |
| 237 | posts[1].answer(204) |
| 238 | await tick() |
| 239 | assert.equal(statuses.at(-1), 'ok') |
| 240 | }) |
| 241 | |
| 242 | // ── A link that is still loading (branch fix/safari-save-stall) ────── |
| 243 | // WebKit sends no ordinary request while the page's main frame waits for |
| 244 | // a navigation, but it does send keepalive ones, which browsers cap at |
| 245 | // 64KiB in flight. So a save is keepalive, and a batch is at most what a |
| 246 | // keepalive save may carry — save-queue.mjs's own comment has the case. |
| 247 | |
| 248 | test('a save is sent keepalive, and given up if it is never answered', async () => { |
| 249 | const random = (n) => crypto.getRandomValues(new Uint8Array(n)) |
| 250 | const small = await saveRequest(random(KEEPALIVE_BYTES)) |
| 251 | assert.equal(small.method, 'POST') |
| 252 | assert.equal(small.credentials, 'same-origin') |
| 253 | assert.equal(small.keepalive, true, 'a save WebKit would refuse while a link loads') |
| 254 | // Over the keepalive budget the browser refuses the request outright, |
| 255 | // so it goes as an ordinary one. |
| 256 | assert.equal((await saveRequest(random(KEEPALIVE_BYTES + 1))).keepalive, false, 'what does not compress is sent as it is') |
| 257 | // A large save on a slow connection is not cut off while it uploads, |
| 258 | // and the queue waits for the request's own timeout before its own. |
| 259 | assert.equal(saveTimeoutMs(new Uint8Array(8 * 1024 * 1024)), SAVE_TIMEOUT_MS + 1024 * 1024) |
| 260 | assert.equal(answerTimeoutMs(new Uint8Array(8)), SAVE_TIMEOUT_MS + 1 + 5000) |
| 261 | const { signal } = await saveRequest(new Uint8Array(1), { timeoutMs: 10 }) |
| 262 | assert.ok(signal, 'a save on the wire forever would stop every save after it') |
| 263 | // AbortSignal.timeout's timer does not hold the event loop open. Node |
| 264 | // 24's test runner keeps it open anyway; Node 22's does not, so with |
| 265 | // nothing else pending it ends the file here and cancels every later |
| 266 | // test. A held timer keeps the loop alive until the signal fires. |
| 267 | await new Promise((resolve) => { |
| 268 | const hold = setTimeout(() => {}, 60_000) |
| 269 | signal.addEventListener('abort', () => { clearTimeout(hold); resolve() }) |
| 270 | }) |
| 271 | assert.equal(signal.reason.name, 'TimeoutError') |
| 272 | }) |
| 273 | |
| 274 | test('a batch carries at most maxBatchBytes, and the rest follow in order once it is answered', async () => { |
| 275 | const { q, posts, statuses, tick, fire } = harness({ maxBatchBytes: 2 }) |
| 276 | for (const n of [1, 2, 3, 4, 5]) q.enqueue(u(n)) |
| 277 | const done = q.flush() |
| 278 | await tick() |
| 279 | assert.equal(posts.length, 1) |
| 280 | assert.deepEqual(posts[0].bytes, [1, 2]) |
| 281 | assert.deepEqual([...q.pendingBytes()], [1, 2, 3, 4, 5], 'everything not yet answered is still owed') |
| 282 | posts[0].answer(204) |
| 283 | await tick() |
| 284 | assert.equal(statuses.at(-1), 'saving') |
| 285 | assert.deepEqual(posts[1].bytes, [3, 4]) |
| 286 | // A retry goes first, with only its own batch. |
| 287 | posts[1].answer(503) |
| 288 | await tick() |
| 289 | assert.equal(statuses.at(-1), 'retrying') |
| 290 | await fire() |
| 291 | assert.deepEqual(posts[2].bytes, [3, 4]) |
| 292 | posts[2].answer(204) |
| 293 | await tick() |
| 294 | assert.deepEqual(posts[3].bytes, [5]) |
| 295 | posts[3].answer(204) |
| 296 | assert.equal(await done, true) |
| 297 | assert.equal(statuses.at(-1), 'ok') |
| 298 | assert.equal(q.pendingBytes(), null) |
| 299 | }) |
| 300 | |
| 301 | test('an update bigger than maxBatchBytes still goes, on its own', async () => { |
| 302 | const { q, posts, tick } = harness({ maxBatchBytes: 2 }) |
| 303 | q.enqueue(new Uint8Array([7, 7, 7])) |
| 304 | q.enqueue(u(8)) |
| 305 | q.flush() |
| 306 | await tick() |
| 307 | assert.deepEqual(posts[0].bytes, [7, 7, 7]) |
| 308 | posts[0].answer(204) |
| 309 | await tick() |
| 310 | assert.deepEqual(posts[1].bytes, [8]) |
| 311 | }) |
| 312 | |
| 313 | // One save is on the wire at a time, so one that is never answered must |
| 314 | // not stop the rest: WebKit drops the promise of a keepalive save answered |
| 315 | // while its page was in the back/forward cache. |
| 316 | test('a save never answered is given up, retried with a real request, and its late answer ignored', async () => { |
| 317 | const { q, posts, statuses, tick, fire } = harness({ answerTimeoutMs: (bytes) => 5000 + bytes.byteLength }) |
| 318 | q.enqueue(u(1)) |
| 319 | await fire() // the debounce |
| 320 | assert.equal(posts.length, 1) |
| 321 | q.enqueue(u(2)) |
| 322 | await fire() // the answer timeout: nobody answered |
| 323 | assert.equal(statuses.at(-1), 'retrying', 'an unanswered save is a failed one') |
| 324 | await fire() // the retry's debounce |
| 325 | assert.equal(posts.length, 2, 'the retry is a real request') |
| 326 | assert.deepEqual(posts[1].bytes, [1, 2]) |
| 327 | posts[0].answer(503) // the lost one, late: nothing to do with anything now |
| 328 | await tick() |
| 329 | assert.equal(posts.length, 2) |
| 330 | assert.equal(statuses.at(-1), 'retrying') |
| 331 | posts[1].answer(204) |
| 332 | await tick() |
| 333 | assert.equal(statuses.at(-1), 'ok') |
| 334 | assert.equal(q.pendingBytes(), null) |
| 335 | }) |
| 336 | |
| 337 | test('resume sends again at once what was on the wire as the page left, without saying it failed', async () => { |
| 338 | const { q, posts, statuses, tick, fire } = harness() |
| 339 | q.enqueue(u(1)) |
| 340 | await fire() |
| 341 | q.enqueue(u(2)) |
| 342 | q.resume() // shown again from the back/forward cache |
| 343 | await tick() |
| 344 | assert.equal(posts.length, 2) |
| 345 | assert.deepEqual(posts[1].bytes, [1, 2]) |
| 346 | assert.ok(!statuses.includes('retrying'), 'nothing failed') |
| 347 | posts[1].answer(204) |
| 348 | await tick() |
| 349 | assert.equal(statuses.at(-1), 'ok') |
| 350 | posts[0].answer(204) // late, and ignored |
| 351 | await tick() |
| 352 | assert.equal(posts.length, 2) |
| 353 | // With nothing on the wire, a retry waiting on its timer goes now. |
| 354 | q.enqueue(u(3)) |
| 355 | await fire() |
| 356 | posts[2].answer(0) |
| 357 | await tick() |
| 358 | q.resume() |
| 359 | await tick() |
| 360 | assert.equal(posts.length, 4) |
| 361 | assert.deepEqual(posts[3].bytes, [3]) |
| 362 | }) |
| 363 | |
| 364 | // Keepalive saves and beacons share the browser's 64KiB. The unload beacon |
| 365 | // repeated the keepalive save on the wire, so with a large one there it was |
| 366 | // refused, and the edits queued behind it were lost (Claude Fable on #94). |
| 367 | test('a keepalive save on the wire is left out of what the unload beacons; a plain one is kept', async () => { |
| 368 | const { q, posts, fire } = harness() |
| 369 | q.enqueue(u(1)) |
| 370 | await fire() |
| 371 | q.enqueue(u(2)) |
| 372 | assert.equal(q.onWire, 'plain', 'not on the wire yet: owed like a plain save') |
| 373 | assert.deepEqual([...q.pendingBytes({ wire: 'plain' })], [1, 2]) |
| 374 | posts[0].onWire(true) |
| 375 | assert.equal(q.onWire, 'keepalive') |
| 376 | assert.deepEqual([...q.pendingBytes({ wire: 'plain' })], [2], 'a keepalive save lands without the page') |
| 377 | assert.deepEqual([...q.pendingBytes()], [1, 2], 'everything still owed, for anything else') |
| 378 | assert.deepEqual([...q.pendingBytes({ wire: 'none' })], [2]) |
| 379 | posts[0].onWire(false) |
| 380 | assert.equal(q.onWire, 'plain') |
| 381 | assert.deepEqual([...q.pendingBytes({ wire: 'plain' })], [1, 2], 'a plain save dies with the page') |
| 382 | posts[0].answer(204) |
| 383 | await new Promise((resolve) => setImmediate(resolve)) |
| 384 | assert.equal(q.onWire, 'plain', 'the queued edit went straight on behind it') |
| 385 | posts[1].onWire(true) |
| 386 | assert.equal(q.pendingBytes({ wire: 'plain' }), null) |
| 387 | }) |
| 388 | |
| 389 | // "Trouble saving" means a request failed. WebKit refuses a save with no |
| 390 | // answer while a link the page opened is loading, and either kind of |
| 391 | // request when keepalive's quota is spent; then the server is still there, |
| 392 | // and the queue retries without saying anything (Claude Fable on #94). |
| 393 | test('a save refused with no answer says retrying only if the server cannot be reached either', async () => { |
| 394 | let up = true |
| 395 | const probes = [] |
| 396 | const { q, posts, statuses, tick, fire } = harness({ probe: () => new Promise((resolve) => probes.push(() => resolve(up))) }) |
| 397 | q.enqueue(u(1)) |
| 398 | await fire() |
| 399 | posts[0].answer(0) // refused, no answer |
| 400 | await tick() |
| 401 | assert.equal(probes.length, 1, 'the refusal is followed by a probe') |
| 402 | probes[0]() |
| 403 | await tick() |
| 404 | assert.ok(!statuses.includes('retrying'), 'the server answered the probe: nothing failed') |
| 405 | await fire() |
| 406 | assert.equal(posts.length, 2, 'and the save is still retried, with a real request') |
| 407 | up = false |
| 408 | posts[1].answer(0) |
| 409 | await tick() |
| 410 | probes[1]() |
| 411 | await tick() |
| 412 | assert.equal(statuses.at(-1), 'retrying', 'nothing reaches the server: that is a real failure') |
| 413 | await fire() |
| 414 | posts[2].answer(503) |
| 415 | await tick() |
| 416 | assert.equal(probes.length, 2, 'a 5xx is an answer, and needs no probe') |
| 417 | assert.equal(statuses.at(-1), 'retrying') |
| 418 | // A probe that answers after the batch has been saved some other way (a |
| 419 | // flush, here) says nothing. |
| 420 | await fire() |
| 421 | posts[3].answer(0) |
| 422 | await tick() |
| 423 | q.flush() |
| 424 | await tick() |
| 425 | posts[4].answer(204) |
| 426 | await tick() |
| 427 | probes[2]() |
| 428 | await tick() |
| 429 | assert.equal(statuses.at(-1), 'ok') |
| 430 | }) |
| 431 | |
| 432 | test('retries the browser refuses while the server answers back off, and reset once one is answered', async () => { |
| 433 | const delays = [] |
| 434 | const timers = [] |
| 435 | const posts = [] |
| 436 | const q = createSaveQueue({ |
| 437 | post: () => new Promise((resolve, reject) => posts.push({ answer: (st) => (st === 0 ? reject(new Error('Load failed')) : resolve({ ok: st < 300, status: st })) })), |
| 438 | mergeUpdates: concatUpdates, |
| 439 | debounceMs: 250, |
| 440 | probe: async () => true, |
| 441 | setTimeoutFn: (fn, ms) => { timers.push(fn); delays.push(ms); return timers.length }, |
| 442 | clearTimeoutFn: () => {}, |
| 443 | }) |
| 444 | const tick = () => new Promise((resolve) => setImmediate(resolve)) |
| 445 | const fire = async () => { for (const fn of timers.splice(0)) fn(); await tick() } |
| 446 | q.enqueue(u(1)) |
| 447 | await fire() |
| 448 | for (let i = 0; i < 6; i++) { |
| 449 | posts.at(-1).answer(0) |
| 450 | await tick() |
| 451 | await tick() |
| 452 | await fire() |
| 453 | } |
| 454 | assert.deepEqual(delays, [250, 500, 1000, 2000, 4000, 4000, 4000], 'doubling, to QUIET_MAX_MS') |
| 455 | posts.at(-1).answer(204) |
| 456 | await tick() |
| 457 | q.enqueue(u(2)) |
| 458 | await fire() |
| 459 | posts.at(-1).answer(0) |
| 460 | await tick() |
| 461 | await tick() |
| 462 | assert.equal(delays.at(-1), 500, 'an answered save starts the backoff again') |
| 463 | }) |
| 464 | |
| 465 | test('reachable tries a keepalive request, then an ordinary one', async () => { |
| 466 | const seen = [] |
| 467 | const fetcher = (refuse) => async (url, init) => { |
| 468 | seen.push(init.keepalive) |
| 469 | assert.equal(url, '/healthz') |
| 470 | assert.equal(init.method, 'HEAD') |
| 471 | if (refuse.includes(init.keepalive)) throw new TypeError('Load failed') |
| 472 | return { ok: true, status: 200 } |
| 473 | } |
| 474 | assert.equal(await reachable('/healthz', fetcher([])), true) |
| 475 | assert.deepEqual(seen.splice(0), [true]) |
| 476 | assert.equal(await reachable('/healthz', fetcher([true])), true, 'keepalive quota spent: an ordinary request still answers') |
| 477 | assert.deepEqual(seen.splice(0), [true, false]) |
| 478 | assert.equal(await reachable('/healthz', fetcher([true, false])), false) |
| 479 | }) |
| 480 | |
| 481 | // A large save goes gzipped, so far fewer are too large for a keepalive |
| 482 | // request (Claude Fable on #94); the server gunzips it. |
| 483 | test('a large save is gzipped, and goes keepalive if what is sent fits', async () => { |
| 484 | const text = new TextEncoder().encode('a pasted paragraph of ordinary prose, '.repeat(2000)) |
| 485 | assert.ok(text.byteLength > 2 * KEEPALIVE_BYTES) |
| 486 | const init = await saveRequest(text) |
| 487 | assert.equal(init.headers['Content-Encoding'], 'gzip') |
| 488 | assert.deepEqual(new Uint8Array(gunzipSync(init.body)), text, 'the server gets back exactly the update') |
| 489 | assert.equal(init.keepalive, true, 'compressed, it fits a keepalive request') |
| 490 | const small = await saveRequest(new Uint8Array(COMPRESS_FROM - 1)) |
| 491 | assert.equal(small.headers['Content-Encoding'], undefined, 'a small save is sent as it is') |
| 492 | assert.equal(small.body.byteLength, COMPRESS_FROM - 1) |
| 493 | }) |
| 494 | |
| 495 | // A server that does not gunzip reads a gzipped save as the update and |
| 496 | // refuses it with a 4xx, and the queue drops a batch a 4xx answers: a tab |
| 497 | // on this bundle after a rollback would lose every save of 1KB or more |
| 498 | // (Claude Fable on #94, round 2). The poster sends it again as it is, and |
| 499 | // stops compressing for the rest of the page. |
| 500 | test('a gzipped save a server refuses is sent again uncompressed, and later saves skip gzip', async () => { |
| 501 | const sent = [] |
| 502 | // main's updatesPost: the compressed bytes are not an update. |
| 503 | const fetchFn = async (url, init) => { |
| 504 | sent.push(init.headers['Content-Encoding'] || 'identity') |
| 505 | return { ok: !init.headers['Content-Encoding'], status: init.headers['Content-Encoding'] ? 400 : 204 } |
| 506 | } |
| 507 | const post = createPoster({ url: '/d/x/updates', fetchFn }) |
| 508 | const text = new TextEncoder().encode('a pasted paragraph of ordinary prose, '.repeat(100)) |
| 509 | const statuses = [] |
| 510 | const q = createSaveQueue({ post, mergeUpdates: concatUpdates, onStatus: (s) => statuses.push(s), debounceMs: 5 }) |
| 511 | q.enqueue(text) |
| 512 | // status starts 'ok', so wait for the answer itself, or for a drop. |
| 513 | await until(() => (sent.length >= 2 && q.pendingBytes() === null) || q.status === 'failed') |
| 514 | assert.deepEqual(sent, ['gzip', 'identity'], 'refused gzipped, then sent as it is') |
| 515 | assert.equal(q.status, 'ok', 'the batch is saved, not dropped') |
| 516 | assert.ok(!statuses.includes('failed')) |
| 517 | q.enqueue(text) |
| 518 | await until(() => sent.length === 3) |
| 519 | assert.deepEqual(sent, ['gzip', 'identity', 'identity'], 'the page remembers') |
| 520 | }) |
| 521 | |
| 522 | test('a refused save that was not gzipped is not sent again', async () => { |
| 523 | let calls = 0 |
| 524 | const post = createPoster({ url: '/u', fetchFn: async () => { calls++; return { ok: false, status: 400 } } }) |
| 525 | assert.equal((await post(new Uint8Array(COMPRESS_FROM - 1))).status, 400) |
| 526 | assert.equal(calls, 1) |
| 527 | // And one the server refuses either way costs one request more, then |
| 528 | // is refused as before. |
| 529 | let both = 0 |
| 530 | const refuses = createPoster({ url: '/u', fetchFn: async () => { both++; return { ok: false, status: 422 } } }) |
| 531 | assert.equal((await refuses(new TextEncoder().encode('x'.repeat(5000)))).status, 422) |
| 532 | assert.equal(both, 2) |
| 533 | }) |
| 534 | |