Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import * as fc from 'fast-check'
3import { ShapeStream } from '../src'
4import { expiredShapesCache } from '../src/expired-shapes-cache'
5import { upToDateTracker } from '../src/up-to-date-tracker'
6
7// ─── Response Factories ─────────────────────────────────────────────
8//
9// Each factory generates a valid Electric protocol response. A
10// monotonically increasing sequence number keeps offsets and cursors
11// unique across the test run, preventing stale-response detection
12// from firing unexpectedly. All factories accept a `handle` parameter
13// so that responses stay consistent after 409 rotations.
14
15let responseSeq = 0
16
17function nextSeq(): number {
18 return ++responseSeq
19}
20
21/** All Electric headers — valid for both live and non-live requests. */
22function allHeaders(handle: string): Record<string, string> {
23 const seq = responseSeq // use current seq without incrementing
24 return {
25 'electric-handle': handle,
26 'electric-offset': `${seq}_0`,
27 'electric-schema': `{"id":"int4"}`,
28 'electric-cursor': `cursor-${seq}`,
29 }
30}
31
32/** Valid 200 with one data message. Resets the error retry counter. */
33function make200WithData(handle: string): Response {
34 const seq = nextSeq()
35 return new Response(
36 JSON.stringify([
37 {
38 offset: `${seq}_0`,
39 value: { id: seq },
40 headers: {
41 operation: `insert`,
42 lsn: `${seq}`,
43 op_position: 0,
44 txids: [`${seq}`],
45 },
46 key: `key-${seq}`,
47 },
48 ]),
49 { status: 200, headers: allHeaders(handle) }
50 )
51}
52
53/** 200 with a single `update` operation followed by up-to-date. */
54function make200WithUpdate(handle: string): Response {
55 const seq = nextSeq()
56 return new Response(
57 JSON.stringify([
58 {
59 offset: `${seq}_0`,
60 value: { id: seq, title: `updated-${seq}` },
61 old_value: { title: `prev-${seq}` },
62 headers: {
63 operation: `update`,
64 lsn: `${seq}`,
65 op_position: 1,
66 last: true,
67 txids: [`${seq}`],
68 },
69 key: `key-${seq}`,
70 },
71 { headers: { control: `up-to-date` } },
72 ]),
73 {
74 status: 200,
75 headers: { ...allHeaders(handle), 'electric-up-to-date': `` },
76 }
77 )
78}
79
80/** 200 with a single `delete` operation followed by up-to-date. */
81function make200WithDelete(handle: string): Response {
82 const seq = nextSeq()
83 return new Response(
84 JSON.stringify([
85 {
86 offset: `${seq}_0`,
87 value: { id: seq },
88 headers: {
89 operation: `delete`,
90 lsn: `${seq}`,
91 op_position: 0,
92 last: true,
93 },
94 key: `key-${seq}`,
95 },
96 { headers: { control: `up-to-date` } },
97 ]),
98 {
99 status: 200,
100 headers: { ...allHeaders(handle), 'electric-up-to-date': `` },
101 }
102 )
103}
104
105/** 200 with a mixed batch (insert + update + delete + up-to-date). */
106function make200MixedBatch(handle: string): Response {
107 const seq = nextSeq()
108 return new Response(
109 JSON.stringify([
110 {
111 offset: `${seq}_0`,
112 value: { id: seq },
113 headers: { operation: `insert`, lsn: `${seq}`, op_position: 0 },
114 key: `ins-${seq}`,
115 },
116 {
117 offset: `${seq}_1`,
118 value: { id: seq, title: `t` },
119 headers: { operation: `update`, lsn: `${seq}`, op_position: 1 },
120 key: `upd-${seq}`,
121 },
122 {
123 offset: `${seq}_2`,
124 value: { id: seq },
125 headers: {
126 operation: `delete`,
127 lsn: `${seq}`,
128 op_position: 2,
129 last: true,
130 },
131 key: `del-${seq}`,
132 },
133 { headers: { control: `up-to-date` } },
134 ]),
135 {
136 status: 200,
137 headers: { ...allHeaders(handle), 'electric-up-to-date': `` },
138 }
139 )
140}
141
142/**
143 * 200 with a stray `snapshot-end` control message (orphan snapshot_mark).
144 * The client should tolerate unknown snapshot marks — no snapshot was
145 * requested, so the tracker should ignore it gracefully.
146 */
147function make200StraySnapshotEnd(handle: string): Response {
148 const seq = nextSeq()
149 return new Response(
150 JSON.stringify([
151 {
152 headers: {
153 control: `snapshot-end`,
154 xmin: `${seq * 10}`,
155 xmax: `${seq * 10 + 50}`,
156 xip_list: [],
157 snapshot_mark: 999000 + seq, // never requested
158 },
159 },
160 { headers: { control: `up-to-date` } },
161 ]),
162 {
163 status: 200,
164 headers: { ...allHeaders(handle), 'electric-up-to-date': `` },
165 }
166 )
167}
168
169/**
170 * 200 with an unknown control message type. Forward-compatibility:
171 * the client should ignore unknown controls rather than crash.
172 */
173function make200UnknownControl(handle: string): Response {
174 nextSeq()
175 return new Response(
176 JSON.stringify([
177 { headers: { control: `future-unknown-${nextSeq()}` } },
178 { headers: { control: `up-to-date` } },
179 ]),
180 {
181 status: 200,
182 headers: { ...allHeaders(handle), 'electric-up-to-date': `` },
183 }
184 )
185}
186
187/**
188 * 200 with an op carrying a snapshot_mark that wasn't requested. The
189 * SnapshotTracker's shouldRejectMessage() must handle unknown marks.
190 */
191function make200OpWithOrphanSnapshotMark(handle: string): Response {
192 const seq = nextSeq()
193 return new Response(
194 JSON.stringify([
195 {
196 offset: `${seq}_0`,
197 value: { id: seq },
198 headers: {
199 operation: `insert`,
200 lsn: `${seq}`,
201 op_position: 0,
202 snapshot_mark: 888000 + seq,
203 },
204 key: `orphan-${seq}`,
205 },
206 { headers: { control: `up-to-date` } },
207 ]),
208 {
209 status: 200,
210 headers: { ...allHeaders(handle), 'electric-up-to-date': `` },
211 }
212 )
213}
214
215/**
216 * 200 body is a JSON string (not an array). Client should throw
217 * FetchError (non-array response body) → retryable via #backoffAndRetry.
218 */
219function make200StringBody(handle: string): Response {
220 nextSeq()
221 return new Response(JSON.stringify(`just a string, not an array`), {
222 status: 200,
223 headers: allHeaders(handle),
224 })
225}
226
227/** 429 Too Many Requests with Retry-After. Propagates to shape-level retry. */
228function make429(): Response {
229 return new Response(
230 JSON.stringify({ message: `Too many requests — try again later` }),
231 {
232 status: 429,
233 headers: {
234 'content-type': `application/json`,
235 'retry-after': `0`,
236 },
237 }
238 )
239}
240
241/** 503 Service Unavailable with Retry-After. Propagates to shape-level retry. */
242function make503(): Response {
243 return new Response(
244 JSON.stringify({ code: `database_unreachable`, error: `DB unreachable` }),
245 {
246 status: 503,
247 headers: {
248 'content-type': `application/json`,
249 'retry-after': `0`,
250 },
251 }
252 )
253}
254
255/** 500 Internal Server Error. Propagates to shape-level retry. */
256function make500(): Response {
257 return new Response(JSON.stringify({ message: `Unexpected error` }), {
258 status: 500,
259 headers: { 'content-type': `application/json` },
260 })
261}
262
263/** 404 Not Found. Non-retryable 4xx (like 400) in the fetch backoff layer. */
264function make404(): Response {
265 return new Response(JSON.stringify({ message: `Shape not found` }), {
266 status: 404,
267 headers: { 'content-type': `application/json` },
268 })
269}
270
271/** Valid 200 with up-to-date control message. Resets the error retry counter. */
272function make200UpToDate(handle: string): Response {
273 nextSeq()
274 return new Response(
275 JSON.stringify([{ headers: { control: `up-to-date` } }]),
276 {
277 status: 200,
278 headers: { ...allHeaders(handle), 'electric-up-to-date': `` },
279 }
280 )
281}
282
283/** Valid 200 with empty body []. Does NOT reset the error retry counter. */
284function make200Empty(handle: string): Response {
285 nextSeq()
286 return new Response(JSON.stringify([]), {
287 status: 200,
288 headers: allHeaders(handle),
289 })
290}
291
292/** 204 No Content. Resets the error retry counter. */
293function make204(handle: string): Response {
294 nextSeq()
295 return new Response(null, {
296 status: 204,
297 headers: allHeaders(handle),
298 })
299}
300
301/** 400 Bad Request. Bypasses backoff, goes straight to onError. */
302function make400(): Response {
303 return new Response(`Bad Request`, {
304 status: 400,
305 statusText: `Bad Request`,
306 })
307}
308
309/**
310 * 409 Conflict (shape rotation). Caught by #requestShape internally —
311 * does NOT go through onError, does NOT affect the retry counter.
312 * Returns a unique new handle so that subsequent responses avoid
313 * stale-cache detection.
314 */
315function make409(newHandle: string): Response {
316 return new Response(
317 JSON.stringify([{ headers: { control: `must-refetch` } }]),
318 {
319 status: 409,
320 headers: {
321 'electric-handle': newHandle,
322 'content-type': `application/json`,
323 },
324 }
325 )
326}
327
328/**
329 * 409 Conflict without a handle header. Simulates a proxy stripping
330 * the header. Must always produce a unique retry URL via cache buster.
331 */
332function make409NoHandle(): Response {
333 return new Response(
334 JSON.stringify([{ headers: { control: `must-refetch` } }]),
335 {
336 status: 409,
337 headers: {
338 'content-type': `application/json`,
339 },
340 }
341 )
342}
343
344/** Valid headers but non-array body. Throws FetchError → onError. */
345function makeMalformed200(handle: string): Response {
346 nextSeq()
347 return new Response(JSON.stringify({ error: `not an array` }), {
348 status: 200,
349 headers: allHeaders(handle),
350 })
351}
352
353/**
354 * 200 OK but missing required Electric headers.
355 * Throws MissingHeadersError which is NOT retryable — terminates immediately.
356 */
357function make200MissingHeaders(): Response {
358 return new Response(JSON.stringify([]), {
359 status: 200,
360 headers: {},
361 })
362}
363
364// ─── Fetch Gate ─────────────────────────────────────────────────────
365//
366// A controllable mock fetch that blocks each request until the test
367// provides a response. This gives the test full control over the
368// server response sequence while letting ShapeStream drive the
369// request timing naturally.
370
371class FetchGate {
372 private _requestCount = 0
373 private _fetchResolve: ((r: Response) => void) | null = null
374 private _onRequest: (() => void) | null = null
375
376 /** Last two request URLs — used to verify no identity loops. */
377 lastUrl: string | null = null
378 prevUrl: string | null = null
379
380 /** Maximum URL length seen across all requests. */
381 maxUrlLength = 0
382
383 get requestCount(): number {
384 return this._requestCount
385 }
386
387 get hasPendingRequest(): boolean {
388 return this._fetchResolve !== null
389 }
390
391 readonly fetchClient = async (
392 input: RequestInfo | URL,
393 init?: RequestInit
394 ): Promise<Response> => {
395 if (init?.signal?.aborted) return Response.error()
396 this._requestCount++
397
398 const urlStr = input.toString()
399 this.prevUrl = this.lastUrl
400 this.lastUrl = urlStr
401 this.maxUrlLength = Math.max(this.maxUrlLength, urlStr.length)
402
403 if (this._onRequest) {
404 const cb = this._onRequest
405 this._onRequest = null
406 cb()
407 }
408
409 return new Promise<Response>((resolve) => {
410 this._fetchResolve = resolve
411 init?.signal?.addEventListener(
412 `abort`,
413 () => {
414 if (this._fetchResolve === resolve) {
415 this._fetchResolve = null
416 resolve(Response.error())
417 }
418 },
419 { once: true }
420 )
421 })
422 }
423
424 waitForRequest(): Promise<void> {
425 if (this._fetchResolve) return Promise.resolve()
426 return new Promise<void>((resolve) => {
427 this._onRequest = resolve
428 })
429 }
430
431 provideResponse(response: Response): void {
432 if (!this._fetchResolve) throw new Error(`No pending fetch request`)
433 const resolve = this._fetchResolve
434 this._fetchResolve = null
435 resolve(response)
436 }
437}
438
439// ─── Test System (Real) ─────────────────────────────────────────────
440
441interface StreamReal {
442 gate: FetchGate
443 stream: ShapeStream
444 subscriberError: Error | null
445 currentHandle: string
446 respond(response: Response): Promise<void>
447 cleanup(): void
448}
449
450/**
451 * Yield to the event loop until the gate has a pending request
452 * (stream processed the response and is blocked on next fetch)
453 * or the stream terminated (subscriber error set).
454 */
455async function waitUntilSettled(
456 gate: FetchGate,
457 errorRef: { error: Error | null },
458 maxYields = 200
459): Promise<void> {
460 for (let i = 0; i < maxYields; i++) {
461 await new Promise((r) => setTimeout(r, 0))
462 if (gate.hasPendingRequest || errorRef.error !== null) return
463 }
464 throw new Error(
465 `Stream did not settle: no pending request and no subscriber error after ${maxYields} yields`
466 )
467}
468
469/** Reset all shared state to prevent cross-iteration pollution. */
470function resetSharedState(): void {
471 responseSeq = 0
472 localStorage.clear()
473 expiredShapesCache.clear()
474 upToDateTracker.clear()
475}
476
477async function createStreamReal(): Promise<StreamReal> {
478 resetSharedState()
479
480 const initialHandle = `test-handle`
481 const gate = new FetchGate()
482 const aborter = new AbortController()
483 const errorRef = { error: null as Error | null }
484 const handleRef = { current: initialHandle }
485
486 const stream = new ShapeStream({
487 url: `https://example.com/v1/shape`,
488 params: { table: `test` },
489 fetchClient: gate.fetchClient,
490 signal: aborter.signal,
491 subscribe: true,
492 onError: () => ({}), // always retry — the scenario under test
493 // Zero-delay backoff with no internal retries so 5xx/429 responses
494 // propagate to the shape-level #backoffAndRetry loop on every call.
495 // The fetch-layer backoff is covered by unit tests; here we want to
496 // stress the higher-level state machine.
497 backoffOptions: {
498 initialDelay: 0,
499 maxDelay: 0,
500 multiplier: 1,
501 maxRetries: 0,
502 },
503 })
504
505 stream.subscribe(
506 () => {},
507 (err: Error) => {
508 errorRef.error = err
509 }
510 )
511
512 // Wait for the first fetch, then bootstrap into live mode
513 await gate.waitForRequest()
514 gate.provideResponse(make200UpToDate(initialHandle))
515 await waitUntilSettled(gate, errorRef)
516
517 return {
518 gate,
519 stream,
520 get subscriberError() {
521 return errorRef.error
522 },
523 get currentHandle() {
524 return handleRef.current
525 },
526 set currentHandle(h: string) {
527 handleRef.current = h
528 },
529 async respond(response: Response) {
530 await gate.waitForRequest()
531 gate.provideResponse(response)
532 await waitUntilSettled(gate, errorRef)
533 },
534 cleanup() {
535 aborter.abort()
536 },
537 }
538}
539
540// ─── Model ──────────────────────────────────────────────────────────
541
542interface StreamModel {
543 consecutiveErrors: number
544 terminated: boolean
545}
546
547const MAX_CONSECUTIVE_ERROR_RETRIES = 50
548const MAX_URL_LENGTH = 2000
549
550/**
551 * Invariants checked after every command. These catch historical bugs
552 * like URL identity loops (bug #1), `-next` suffix growth (bug #3),
553 * and handle/offset mismatches (bug #10).
554 */
555function assertGlobalInvariants(r: StreamReal): void {
556 expect(r.gate.maxUrlLength).toBeLessThan(MAX_URL_LENGTH)
557
558 if (!r.subscriberError && r.stream.isUpToDate) {
559 expect(r.stream.lastSyncedAt()).toBeDefined()
560 }
561}
562
563/**
564 * Asserts that a 409 response produced a unique retry URL, catching
565 * identity-loop bugs where the retry URL matches the pre-409 URL.
566 */
567function assert409ProducedUniqueUrl(
568 r: StreamReal,
569 prevUrl: string | null
570): void {
571 expect(r.subscriberError).toBeNull()
572 assertGlobalInvariants(r)
573 if (prevUrl) {
574 expect(r.gate.lastUrl).not.toBe(prevUrl)
575 }
576}
577
578// ─── Commands ───────────────────────────────────────────────────────
579//
580// Each command represents one server response. The model predicts
581// the expected state change, and assertions verify the real system
582// matches. fast-check generates adversarial sequences and shrinks
583// failures to minimal reproductions.
584
585/**
586 * Shared logic for successful responses that reset the consecutive error
587 * counter and should not produce a subscriber error.
588 */
589async function runSuccessResponse(
590 m: StreamModel,
591 r: StreamReal,
592 response: Response
593): Promise<void> {
594 m.consecutiveErrors = 0
595 await r.respond(response)
596 expect(r.subscriberError).toBeNull()
597 assertGlobalInvariants(r)
598}
599
600/** 200 with data — counter resets to 0 */
601class Respond200DataCmd implements fc.AsyncCommand<StreamModel, StreamReal> {
602 check(m: Readonly<StreamModel>): boolean {
603 return !m.terminated
604 }
605 async run(m: StreamModel, r: StreamReal): Promise<void> {
606 await runSuccessResponse(m, r, make200WithData(r.currentHandle))
607 }
608 toString(): string {
609 return `Respond200Data`
610 }
611}
612
613/** 200 with up-to-date control — counter resets to 0 */
614class Respond200UpToDateCmd
615 implements fc.AsyncCommand<StreamModel, StreamReal>
616{
617 check(m: Readonly<StreamModel>): boolean {
618 return !m.terminated
619 }
620 async run(m: StreamModel, r: StreamReal): Promise<void> {
621 await runSuccessResponse(m, r, make200UpToDate(r.currentHandle))
622 }
623 toString(): string {
624 return `Respond200UpToDate`
625 }
626}
627
628/**
629 * 200 with empty body [] — does NOT reset counter.
630 * The counter reset in #onMessages is gated by `if (batch.length === 0) return`.
631 */
632class Respond200EmptyCmd implements fc.AsyncCommand<StreamModel, StreamReal> {
633 check(m: Readonly<StreamModel>): boolean {
634 return !m.terminated
635 }
636 async run(_m: StreamModel, r: StreamReal): Promise<void> {
637 await r.respond(make200Empty(r.currentHandle))
638 expect(r.subscriberError).toBeNull()
639 assertGlobalInvariants(r)
640 }
641 toString(): string {
642 return `Respond200Empty`
643 }
644}
645
646/** 204 No Content — counter resets to 0 */
647class Respond204Cmd implements fc.AsyncCommand<StreamModel, StreamReal> {
648 check(m: Readonly<StreamModel>): boolean {
649 return !m.terminated
650 }
651 async run(m: StreamModel, r: StreamReal): Promise<void> {
652 await runSuccessResponse(m, r, make204(r.currentHandle))
653 }
654 toString(): string {
655 return `Respond204`
656 }
657}
658
659/**
660 * Shared logic for error responses that increment the consecutive error
661 * counter and may terminate the stream after MAX_CONSECUTIVE_ERROR_RETRIES.
662 */
663async function runRetryableErrorResponse(
664 m: StreamModel,
665 r: StreamReal,
666 response: Response
667): Promise<void> {
668 m.consecutiveErrors++
669 const shouldTerminate = m.consecutiveErrors > MAX_CONSECUTIVE_ERROR_RETRIES
670 if (shouldTerminate) m.terminated = true
671
672 await r.respond(response)
673
674 if (shouldTerminate) {
675 expect(r.subscriberError).not.toBeNull()
676 } else {
677 expect(r.subscriberError).toBeNull()
678 assertGlobalInvariants(r)
679 }
680}
681
682/** 400 Bad Request — counter increments, may terminate at >50 */
683class Respond400Cmd implements fc.AsyncCommand<StreamModel, StreamReal> {
684 check(m: Readonly<StreamModel>): boolean {
685 return !m.terminated
686 }
687 async run(m: StreamModel, r: StreamReal): Promise<void> {
688 await runRetryableErrorResponse(m, r, make400())
689 }
690 toString(): string {
691 return `Respond400`
692 }
693}
694
695/**
696 * 409 Conflict — caught internally by #requestShape, does NOT go
697 * through onError, does NOT affect the retry counter. Rotates to
698 * a unique handle so subsequent responses avoid stale-cache detection.
699 */
700class Respond409Cmd implements fc.AsyncCommand<StreamModel, StreamReal> {
701 check(m: Readonly<StreamModel>): boolean {
702 return !m.terminated
703 }
704 async run(_m: StreamModel, r: StreamReal): Promise<void> {
705 const prevUrl = r.gate.lastUrl
706 const newHandle = `handle-${nextSeq()}`
707 await r.respond(make409(newHandle))
708 r.currentHandle = newHandle
709 assert409ProducedUniqueUrl(r, prevUrl)
710 }
711 toString(): string {
712 return `Respond409`
713 }
714}
715
716/** Malformed 200 (non-array body) — counter increments, may terminate */
717class RespondMalformed200Cmd
718 implements fc.AsyncCommand<StreamModel, StreamReal>
719{
720 check(m: Readonly<StreamModel>): boolean {
721 return !m.terminated
722 }
723 async run(m: StreamModel, r: StreamReal): Promise<void> {
724 await runRetryableErrorResponse(m, r, makeMalformed200(r.currentHandle))
725 }
726 toString(): string {
727 return `RespondMalformed200`
728 }
729}
730
731/**
732 * 200 with missing Electric headers — throws MissingHeadersError which
733 * is NOT retryable. Stream terminates immediately regardless of counter.
734 */
735class RespondMissingHeadersCmd
736 implements fc.AsyncCommand<StreamModel, StreamReal>
737{
738 check(m: Readonly<StreamModel>): boolean {
739 return !m.terminated
740 }
741 async run(m: StreamModel, r: StreamReal): Promise<void> {
742 m.terminated = true
743 await r.respond(make200MissingHeaders())
744 expect(r.subscriberError).not.toBeNull()
745 }
746 toString(): string {
747 return `RespondMissingHeaders`
748 }
749}
750
751/**
752 * 409 Conflict without a handle header (proxy stripped it).
753 * Handled by creating a random cache buster. Does NOT affect
754 * the retry counter — same as normal 409.
755 */
756class Respond409NoHandleCmd
757 implements fc.AsyncCommand<StreamModel, StreamReal>
758{
759 check(m: Readonly<StreamModel>): boolean {
760 return !m.terminated
761 }
762 async run(_m: StreamModel, r: StreamReal): Promise<void> {
763 const prevUrl = r.gate.lastUrl
764 await r.respond(make409NoHandle())
765 // Simulates server recovery after the proxy-stripped-handle 409:
766 // the next response must carry a fresh handle, not an empty string.
767 r.currentHandle = `handle-recovered-${nextSeq()}`
768 assert409ProducedUniqueUrl(r, prevUrl)
769 }
770 toString(): string {
771 return `Respond409NoHandle`
772 }
773}
774
775/** 200 with a single update operation — counter resets to 0 */
776class Respond200UpdateCmd implements fc.AsyncCommand<StreamModel, StreamReal> {
777 check(m: Readonly<StreamModel>): boolean {
778 return !m.terminated
779 }
780 async run(m: StreamModel, r: StreamReal): Promise<void> {
781 await runSuccessResponse(m, r, make200WithUpdate(r.currentHandle))
782 }
783 toString(): string {
784 return `Respond200Update`
785 }
786}
787
788/** 200 with a single delete operation — counter resets to 0 */
789class Respond200DeleteCmd implements fc.AsyncCommand<StreamModel, StreamReal> {
790 check(m: Readonly<StreamModel>): boolean {
791 return !m.terminated
792 }
793 async run(m: StreamModel, r: StreamReal): Promise<void> {
794 await runSuccessResponse(m, r, make200WithDelete(r.currentHandle))
795 }
796 toString(): string {
797 return `Respond200Delete`
798 }
799}
800
801/** 200 with a mixed batch (insert + update + delete + up-to-date) */
802class Respond200MixedBatchCmd
803 implements fc.AsyncCommand<StreamModel, StreamReal>
804{
805 check(m: Readonly<StreamModel>): boolean {
806 return !m.terminated
807 }
808 async run(m: StreamModel, r: StreamReal): Promise<void> {
809 await runSuccessResponse(m, r, make200MixedBatch(r.currentHandle))
810 }
811 toString(): string {
812 return `Respond200MixedBatch`
813 }
814}
815
816/**
817 * 200 with a stray snapshot-end control (orphan snapshot_mark).
818 * Client should tolerate it — counter resets on the trailing up-to-date.
819 */
820class Respond200StraySnapshotEndCmd
821 implements fc.AsyncCommand<StreamModel, StreamReal>
822{
823 check(m: Readonly<StreamModel>): boolean {
824 return !m.terminated
825 }
826 async run(m: StreamModel, r: StreamReal): Promise<void> {
827 await runSuccessResponse(m, r, make200StraySnapshotEnd(r.currentHandle))
828 }
829 toString(): string {
830 return `Respond200StraySnapshotEnd`
831 }
832}
833
834/** 200 with an unknown control message type — counter resets on trailing up-to-date. */
835class Respond200UnknownControlCmd
836 implements fc.AsyncCommand<StreamModel, StreamReal>
837{
838 check(m: Readonly<StreamModel>): boolean {
839 return !m.terminated
840 }
841 async run(m: StreamModel, r: StreamReal): Promise<void> {
842 await runSuccessResponse(m, r, make200UnknownControl(r.currentHandle))
843 }
844 toString(): string {
845 return `Respond200UnknownControl`
846 }
847}
848
849/**
850 * 200 with an operation carrying an orphan snapshot_mark. The
851 * SnapshotTracker must gracefully accept unknown marks.
852 */
853class Respond200OrphanSnapshotMarkCmd
854 implements fc.AsyncCommand<StreamModel, StreamReal>
855{
856 check(m: Readonly<StreamModel>): boolean {
857 return !m.terminated
858 }
859 async run(m: StreamModel, r: StreamReal): Promise<void> {
860 await runSuccessResponse(
861 m,
862 r,
863 make200OpWithOrphanSnapshotMark(r.currentHandle)
864 )
865 }
866 toString(): string {
867 return `Respond200OrphanSnapshotMark`
868 }
869}
870
871/**
872 * 200 with a JSON string body (not an array). Throws FetchError —
873 * behaves as retryable error (same shape as RespondMalformed200Cmd).
874 */
875class Respond200StringBodyCmd
876 implements fc.AsyncCommand<StreamModel, StreamReal>
877{
878 check(m: Readonly<StreamModel>): boolean {
879 return !m.terminated
880 }
881 async run(m: StreamModel, r: StreamReal): Promise<void> {
882 await runRetryableErrorResponse(m, r, make200StringBody(r.currentHandle))
883 }
884 toString(): string {
885 return `Respond200StringBody`
886 }
887}
888
889/**
890 * 429 Too Many Requests. With `maxRetries: 0`, the fetch-backoff layer
891 * rethrows immediately, so the shape-level retry counter ticks.
892 */
893class Respond429Cmd implements fc.AsyncCommand<StreamModel, StreamReal> {
894 check(m: Readonly<StreamModel>): boolean {
895 return !m.terminated
896 }
897 async run(m: StreamModel, r: StreamReal): Promise<void> {
898 await runRetryableErrorResponse(m, r, make429())
899 }
900 toString(): string {
901 return `Respond429`
902 }
903}
904
905/** 503 Service Unavailable — retryable, counter ticks at shape level. */
906class Respond503Cmd implements fc.AsyncCommand<StreamModel, StreamReal> {
907 check(m: Readonly<StreamModel>): boolean {
908 return !m.terminated
909 }
910 async run(m: StreamModel, r: StreamReal): Promise<void> {
911 await runRetryableErrorResponse(m, r, make503())
912 }
913 toString(): string {
914 return `Respond503`
915 }
916}
917
918/** 500 Internal Server Error — retryable, counter ticks at shape level. */
919class Respond500Cmd implements fc.AsyncCommand<StreamModel, StreamReal> {
920 check(m: Readonly<StreamModel>): boolean {
921 return !m.terminated
922 }
923 async run(m: StreamModel, r: StreamReal): Promise<void> {
924 await runRetryableErrorResponse(m, r, make500())
925 }
926 toString(): string {
927 return `Respond500`
928 }
929}
930
931/** 404 Not Found — 4xx, non-retryable at fetch layer, ticks at shape layer. */
932class Respond404Cmd implements fc.AsyncCommand<StreamModel, StreamReal> {
933 check(m: Readonly<StreamModel>): boolean {
934 return !m.terminated
935 }
936 async run(m: StreamModel, r: StreamReal): Promise<void> {
937 await runRetryableErrorResponse(m, r, make404())
938 }
939 toString(): string {
940 return `Respond404`
941 }
942}
943
944/**
945 * 409 with the same handle as the current one.
946 */
947class Respond409SameHandleCmd
948 implements fc.AsyncCommand<StreamModel, StreamReal>
949{
950 check(m: Readonly<StreamModel>): boolean {
951 return !m.terminated
952 }
953 async run(_m: StreamModel, r: StreamReal): Promise<void> {
954 const prevUrl = r.gate.lastUrl
955 await r.respond(make409(r.currentHandle))
956 assert409ProducedUniqueUrl(r, prevUrl)
957 }
958 toString(): string {
959 return `Respond409SameHandle`
960 }
961}
962
963// ─── Scenario Tests ────────────────────────────────────────────────
964
965describe(`ShapeStream targeted scenario tests`, () => {
966 it(`409 publishes only a synthetic must-refetch control message`, async () => {
967 resetSharedState()
968
969 const initialHandle = `test-handle`
970 const gate = new FetchGate()
971 const aborter = new AbortController()
972 const errorRef = { error: null as Error | null }
973 const receivedBatches: unknown[][] = []
974
975 const stream = new ShapeStream({
976 url: `https://example.com/v1/shape`,
977 params: { table: `test` },
978 fetchClient: gate.fetchClient,
979 signal: aborter.signal,
980 subscribe: true,
981 onError: () => ({}),
982 })
983
984 stream.subscribe(
985 (msgs) => {
986 receivedBatches.push(msgs)
987 },
988 (err: Error) => {
989 errorRef.error = err
990 }
991 )
992
993 // Bootstrap into live mode
994 await gate.waitForRequest()
995 gate.provideResponse(make200UpToDate(initialHandle))
996 await waitUntilSettled(gate, errorRef)
997
998 receivedBatches.length = 0
999
1000 // Send a 409 — client resets and publishes a synthetic must-refetch
1001 await gate.waitForRequest()
1002 gate.provideResponse(make409(`new-handle`))
1003 await waitUntilSettled(gate, errorRef)
1004
1005 // Subscriber should receive only the synthetic must-refetch control
1006 // message — no data rows from the raw 409 response body
1007 expect(receivedBatches).toHaveLength(1)
1008 expect(receivedBatches[0]).toEqual([
1009 { headers: { control: `must-refetch` } },
1010 ])
1011
1012 aborter.abort()
1013 })
1014
1015 it(`consecutive 409s with the same handle produce unique retry URLs`, async () => {
1016 const real = await createStreamReal()
1017 try {
1018 // Advance to a non-initial offset so the first 409 reset is visible
1019 await real.respond(make200WithData(real.currentHandle))
1020
1021 // First 409 with same handle — URL changes because offset resets to -1
1022 const urlBefore = real.gate.lastUrl
1023 await real.respond(make409(real.currentHandle))
1024 expect(real.gate.lastUrl).not.toBe(urlBefore)
1025
1026 // Second 409 with same handle — offset is already -1, handle unchanged.
1027 // Without a cache buster, the retry URL would be identical.
1028 const urlAfterFirstRetry = real.gate.lastUrl
1029 await real.respond(make409(real.currentHandle))
1030 expect(real.gate.lastUrl).not.toBe(urlAfterFirstRetry)
1031 } finally {
1032 real.cleanup()
1033 }
1034 })
1035})
1036
1037// ─── Property Tests ─────────────────────────────────────────────────
1038
1039describe(`ShapeStream model-based property tests`, () => {
1040 const PBT_NUM_RUNS = Number(process.env.PBT_NUM_RUNS ?? `200`)
1041 const PBT_TIMEOUT_MS = Number(process.env.PBT_TIMEOUT_MS ?? `120000`)
1042 const PBT_MAX_COMMANDS = Number(process.env.PBT_MAX_COMMANDS ?? `80`)
1043 const PBT_SEED = process.env.PBT_SEED
1044 ? Number(process.env.PBT_SEED)
1045 : undefined
1046 const PBT_PATH = process.env.PBT_PATH
1047
1048 it(
1049 `bounded retry: any mix of server responses respects the retry limit and counter resets`,
1050 async () => {
1051 await fc.assert(
1052 fc.asyncProperty(
1053 fc.commands(
1054 [
1055 fc.constant(new Respond200DataCmd()),
1056 fc.constant(new Respond200UpToDateCmd()),
1057 fc.constant(new Respond200EmptyCmd()),
1058 fc.constant(new Respond204Cmd()),
1059 fc.constant(new Respond200UpdateCmd()),
1060 fc.constant(new Respond200DeleteCmd()),
1061 fc.constant(new Respond200MixedBatchCmd()),
1062 fc.constant(new Respond200StraySnapshotEndCmd()),
1063 fc.constant(new Respond200UnknownControlCmd()),
1064 fc.constant(new Respond200OrphanSnapshotMarkCmd()),
1065 fc.constant(new Respond400Cmd()),
1066 fc.constant(new Respond404Cmd()),
1067 fc.constant(new Respond429Cmd()),
1068 fc.constant(new Respond500Cmd()),
1069 fc.constant(new Respond503Cmd()),
1070 fc.constant(new Respond409Cmd()),
1071 fc.constant(new Respond409SameHandleCmd()),
1072 fc.constant(new Respond409NoHandleCmd()),
1073 fc.constant(new RespondMalformed200Cmd()),
1074 fc.constant(new Respond200StringBodyCmd()),
1075 fc.constant(new RespondMissingHeadersCmd()),
1076 ],
1077 { maxCommands: PBT_MAX_COMMANDS }
1078 ),
1079 async (cmds) => {
1080 const real = await createStreamReal()
1081 const model: StreamModel = {
1082 consecutiveErrors: 0,
1083 terminated: false,
1084 }
1085 try {
1086 await fc.asyncModelRun(() => ({ model, real }), cmds)
1087 } finally {
1088 real.cleanup()
1089 }
1090 }
1091 ),
1092 {
1093 numRuns: PBT_NUM_RUNS,
1094 ...(PBT_SEED !== undefined ? { seed: PBT_SEED } : {}),
1095 ...(PBT_PATH ? { path: PBT_PATH } : {}),
1096 verbose: true,
1097 }
1098 )
1099 },
1100 PBT_TIMEOUT_MS
1101 )
1102})