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