-
Notifications
You must be signed in to change notification settings - Fork 322
Expand file tree
/
Copy pathstream.test.ts
More file actions
914 lines (788 loc) · 26.8 KB
/
stream.test.ts
File metadata and controls
914 lines (788 loc) · 26.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ShapeStream, isChangeMessage, Message, Row } from '../src'
import { snakeCamelMapper } from '../src/column-mapper'
import { resolveInMacrotask } from './support/test-helpers'
describe(`ShapeStream`, () => {
const shapeUrl = `https://example.com/v1/shape`
let aborter: AbortController
beforeEach(() => {
aborter = new AbortController()
})
afterEach(() => aborter.abort())
it(`should attach specified headers to requests`, async () => {
const eventTarget = new EventTarget()
const requestArgs: Array<RequestInit | undefined> = []
const fetchWrapper = (
...args: Parameters<typeof fetch>
): Promise<Response> => {
requestArgs.push(args[1])
eventTarget.dispatchEvent(new Event(`fetch`))
return Promise.resolve(Response.error())
}
const aborter = new AbortController()
const stream = new ShapeStream({
url: shapeUrl,
params: {
table: `foo`,
},
signal: aborter.signal,
fetchClient: fetchWrapper,
headers: {
Authorization: `my-token`,
'X-Custom-Header': `my-value`,
},
})
const unsub = stream.subscribe(() => unsub())
await new Promise((resolve) =>
eventTarget.addEventListener(`fetch`, resolve, { once: true })
)
expect(requestArgs[0]).toMatchObject({
headers: {
Authorization: `my-token`,
'X-Custom-Header': `my-value`,
},
})
})
it(`should sort query parameters for stable URLs`, async () => {
const eventTarget = new EventTarget()
const requestedUrls: Array<string> = []
const fetchWrapper = (
...args: Parameters<typeof fetch>
): Promise<Response> => {
requestedUrls.push(args[0].toString())
eventTarget.dispatchEvent(new Event(`fetch`))
return Promise.resolve(Response.error())
}
const aborter = new AbortController()
const stream = new ShapeStream({
url: shapeUrl,
params: {
table: `foo`,
where: `a=1`,
columns: [`id`],
},
handle: `potato`,
signal: aborter.signal,
fetchClient: fetchWrapper,
})
const unsub = stream.subscribe(() => unsub())
await new Promise((resolve) =>
eventTarget.addEventListener(`fetch`, resolve, { once: true })
)
expect(requestedUrls[0].split(`?`)[1]).toEqual(
`columns=%22id%22&handle=potato&log=full&offset=-1&table=foo&where=a%3D1`
)
})
it(`should start requesting only after first subscription`, async () => {
const eventTarget = new EventTarget()
const fetchWrapper = (): Promise<Response> => {
eventTarget.dispatchEvent(new Event(`fetch`))
return Promise.resolve(Response.error())
}
const aborter = new AbortController()
const stream = new ShapeStream({
url: shapeUrl,
params: {
table: `foo`,
where: `a=1`,
columns: [`id`],
},
handle: `potato`,
signal: aborter.signal,
fetchClient: fetchWrapper,
})
// should not fire any fetch requests
await new Promise<void>((resolve, reject) => {
eventTarget.addEventListener(`fetch`, reject, { once: true })
setTimeout(() => resolve(), 100)
})
// should fire fetch immediately after subbing
const startedStreaming = new Promise<void>((resolve, reject) => {
eventTarget.addEventListener(`fetch`, () => resolve(), {
once: true,
})
setTimeout(() => reject(`timed out`), 100)
})
const unsub = stream.subscribe(() => unsub())
await startedStreaming
})
it(`should correctly serialize objects into query params`, async () => {
const eventTarget = new EventTarget()
const requestedUrls: Array<string> = []
const fetchWrapper = (
...args: Parameters<typeof fetch>
): Promise<Response> => {
requestedUrls.push(args[0].toString())
eventTarget.dispatchEvent(new Event(`fetch`))
return Promise.resolve(Response.error())
}
const aborter = new AbortController()
const stream = new ShapeStream({
url: shapeUrl,
params: {
table: `foo`,
where: `a=$1 and b=$2`,
columns: [`id`],
params: {
'1': `test1`,
'2': `test2`,
},
},
handle: `potato`,
signal: aborter.signal,
fetchClient: fetchWrapper,
})
const unsub = stream.subscribe(() => unsub())
await new Promise((resolve) =>
eventTarget.addEventListener(`fetch`, resolve, { once: true })
)
expect(requestedUrls[0].split(`?`)[1]).toEqual(
`columns=%22id%22&handle=potato&log=full&offset=-1¶ms%5B1%5D=test1¶ms%5B2%5D=test2&table=foo&where=a%3D%241+and+b%3D%242`
)
})
it(`should correctly serialize where clause param array to query params`, async () => {
const eventTarget = new EventTarget()
const requestedUrls: Array<string> = []
const fetchWrapper = (
...args: Parameters<typeof fetch>
): Promise<Response> => {
requestedUrls.push(args[0].toString())
eventTarget.dispatchEvent(new Event(`fetch`))
return Promise.resolve(Response.error())
}
const aborter = new AbortController()
const stream = new ShapeStream({
url: shapeUrl,
params: {
table: `foo`,
where: `a=$1 and b=$2`,
columns: [`id`],
params: [`test1`, `test2`],
},
handle: `potato`,
signal: aborter.signal,
fetchClient: fetchWrapper,
})
const unsub = stream.subscribe(() => unsub())
await new Promise((resolve) =>
eventTarget.addEventListener(`fetch`, resolve, { once: true })
)
expect(requestedUrls[0].split(`?`)[1]).toEqual(
`columns=%22id%22&handle=potato&log=full&offset=-1¶ms%5B1%5D=test1¶ms%5B2%5D=test2&table=foo&where=a%3D%241+and+b%3D%242`
)
})
it(`should encode columns with columnMapper`, async () => {
const eventTarget = new EventTarget()
const requestedUrls: Array<string> = []
const fetchWrapper = (
...args: Parameters<typeof fetch>
): Promise<Response> => {
requestedUrls.push(args[0].toString())
eventTarget.dispatchEvent(new Event(`fetch`))
return Promise.resolve(Response.error())
}
const aborter = new AbortController()
const stream = new ShapeStream({
url: shapeUrl,
params: {
table: `foo`,
columns: [`userId`, `createdAt`],
},
signal: aborter.signal,
fetchClient: fetchWrapper,
columnMapper: snakeCamelMapper(),
})
const unsub = stream.subscribe(() => unsub())
await new Promise((resolve) =>
eventTarget.addEventListener(`fetch`, resolve, { once: true })
)
const url = new URL(requestedUrls[0])
// columns should be encoded from app format (camelCase) to db format (snake_case)
// and quoted for safe serialization
expect(url.searchParams.get(`columns`)).toEqual(`"user_id","created_at"`)
})
it(`should encode where clause with columnMapper`, async () => {
const eventTarget = new EventTarget()
const requestedUrls: Array<string> = []
const fetchWrapper = (
...args: Parameters<typeof fetch>
): Promise<Response> => {
requestedUrls.push(args[0].toString())
eventTarget.dispatchEvent(new Event(`fetch`))
return Promise.resolve(Response.error())
}
const aborter = new AbortController()
const stream = new ShapeStream({
url: shapeUrl,
params: {
table: `foo`,
where: `userId = $1`,
},
signal: aborter.signal,
fetchClient: fetchWrapper,
columnMapper: snakeCamelMapper(),
})
const unsub = stream.subscribe(() => unsub())
await new Promise((resolve) =>
eventTarget.addEventListener(`fetch`, resolve, { once: true })
)
const url = new URL(requestedUrls[0])
// where clause should be encoded from app format (camelCase) to db format (snake_case)
expect(url.searchParams.get(`where`)).toEqual(`user_id = $1`)
})
it(`should quote columns even when columnMapper is not provided`, async () => {
const eventTarget = new EventTarget()
const requestedUrls: Array<string> = []
const fetchWrapper = (
...args: Parameters<typeof fetch>
): Promise<Response> => {
requestedUrls.push(args[0].toString())
eventTarget.dispatchEvent(new Event(`fetch`))
return Promise.resolve(Response.error())
}
const aborter = new AbortController()
const stream = new ShapeStream({
url: shapeUrl,
params: {
table: `foo`,
columns: [`user_id`, `created_at`],
},
signal: aborter.signal,
fetchClient: fetchWrapper,
})
const unsub = stream.subscribe(() => unsub())
await new Promise((resolve) =>
eventTarget.addEventListener(`fetch`, resolve, { once: true })
)
const url = new URL(requestedUrls[0])
// columns should be quoted for safe serialization
expect(url.searchParams.get(`columns`)).toEqual(`"user_id","created_at"`)
})
it(`should handle columns with special characters`, async () => {
const eventTarget = new EventTarget()
const requestedUrls: Array<string> = []
const fetchWrapper = (
...args: Parameters<typeof fetch>
): Promise<Response> => {
requestedUrls.push(args[0].toString())
eventTarget.dispatchEvent(new Event(`fetch`))
return Promise.resolve(Response.error())
}
const aborter = new AbortController()
const stream = new ShapeStream({
url: shapeUrl,
params: {
table: `foo`,
columns: [`normal`, `has,comma`, `has"quote`],
},
signal: aborter.signal,
fetchClient: fetchWrapper,
})
const unsub = stream.subscribe(() => unsub())
await new Promise((resolve) =>
eventTarget.addEventListener(`fetch`, resolve, { once: true })
)
const url = new URL(requestedUrls[0])
// columns with special characters should be properly quoted and escaped
expect(url.searchParams.get(`columns`)).toEqual(
`"normal","has,comma","has""quote"`
)
})
it(`should decode data columns with columnMapper`, async () => {
const receivedMessages: Message<Row>[] = []
// Mock response with db column names (snake_case)
const mockResponseData = [
{
key: `"public"."test"/"1"`,
value: { user_id: `123`, created_at: `2025-01-01` },
headers: { operation: `insert` },
},
{
headers: { control: `up-to-date` },
},
]
const fetchWrapper = (): Promise<Response> => {
// Use resolveInMacrotask to prevent infinite microtask loops
return resolveInMacrotask(
new Response(JSON.stringify(mockResponseData), {
status: 200,
headers: {
'content-type': `application/json`,
'electric-handle': `test-handle`,
'electric-offset': `0_0`,
'electric-cursor': `1`,
'electric-up-to-date': `true`,
'electric-schema': JSON.stringify({
user_id: { type: `text` },
created_at: { type: `text` },
}),
},
})
)
}
const stream = new ShapeStream({
url: shapeUrl,
params: {
table: `foo`,
columns: [`userId`, `createdAt`],
},
signal: aborter.signal,
fetchClient: fetchWrapper,
columnMapper: snakeCamelMapper(),
})
const unsub = stream.subscribe((messages) => {
receivedMessages.push(...messages)
})
// Wait for messages to be processed
await new Promise((resolve) => setTimeout(resolve, 100))
unsub()
aborter.abort()
// Find the change message
const changeMessage = receivedMessages.find(isChangeMessage)
expect(changeMessage).toBeDefined()
// Verify column names were decoded from snake_case to camelCase
expect(changeMessage!.value).toHaveProperty(`userId`)
expect(changeMessage!.value).toHaveProperty(`createdAt`)
expect((changeMessage!.value as Record<string, unknown>).userId).toBe(`123`)
expect((changeMessage!.value as Record<string, unknown>).createdAt).toBe(
`2025-01-01`
)
// Verify original db column names are not present
expect(changeMessage!.value).not.toHaveProperty(`user_id`)
expect(changeMessage!.value).not.toHaveProperty(`created_at`)
})
it(`should detect fast retry loops, clear caches, and eventually throw`, async () => {
// Simulate a misconfigured proxy that always returns 409, causing a tight
// retry loop that should trigger cache clearing and eventually an error.
let requestCount = 0
let caughtError: Error | null = null
const warnSpy = vi.spyOn(console, `warn`).mockImplementation(() => {})
const fetchMock = (
..._args: Parameters<typeof fetch>
): Promise<Response> => {
requestCount++
return Promise.resolve(
new Response(`[]`, {
status: 409,
headers: {
'content-type': `application/json`,
'electric-handle': `handle-${requestCount}`,
},
})
)
}
const stream = new ShapeStream({
url: shapeUrl,
params: { table: `test` },
signal: aborter.signal,
fetchClient: fetchMock,
subscribe: false,
onError: (error) => {
caughtError = error
},
})
stream.subscribe(() => {})
await vi.waitFor(
() => {
expect(caughtError).not.toBe(null)
},
{ timeout: 15_000 }
)
expect(caughtError!.message).toContain(`fast retry loop`)
expect(caughtError!.message).toContain(`caches were cleared`)
expect(caughtError!.message).toContain(`proxy`)
expect(caughtError!.message).toContain(`troubleshooting`)
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining(`Clearing client-side caches`),
expect.any(Error)
)
warnSpy.mockRestore()
})
it(`should reset fast-loop state when onError triggers a retry`, async () => {
// Verifies that fast-loop detection doesn't permanently block a stream
// after onError returns retry options. The consecutive count must reset
// so the retried stream gets a fresh chance to sync.
let requestCount = 0
let errorCount = 0
let lastError: Error | null = null
const warnSpy = vi.spyOn(console, `warn`).mockImplementation(() => {})
const fetchMock = (
..._args: Parameters<typeof fetch>
): Promise<Response> => {
requestCount++
// After the first onError retry, return a successful response
// to prove the stream actually gets a fresh chance
if (errorCount >= 1) {
return Promise.resolve(
new Response(
JSON.stringify([
{
key: `test-1`,
value: { id: `1` },
headers: {
operation: `insert`,
relation: [`public`, `test`],
},
offset: `0_0`,
},
{
headers: { control: `up-to-date` },
offset: `0_0`,
},
]),
{
status: 200,
headers: {
'content-type': `application/json`,
'electric-handle': `good-handle`,
'electric-offset': `0_0`,
'electric-schema': `{"id":{"type":"text"}}`,
},
}
)
)
}
// Return 409 to trigger fast-loop detection
return Promise.resolve(
new Response(`[]`, {
status: 409,
headers: {
'content-type': `application/json`,
'electric-handle': `handle-${requestCount}`,
},
})
)
}
const stream = new ShapeStream({
url: shapeUrl,
params: { table: `test` },
signal: aborter.signal,
fetchClient: fetchMock,
subscribe: false,
onError: (error) => {
errorCount++
lastError = error
// Return retry options — this should reset fast-loop state
return { params: { table: `test` } }
},
})
let gotData = false
stream.subscribe((messages) => {
if (messages.some((m) => `key` in m)) {
gotData = true
}
})
// The stream should: detect fast loop → throw → onError retries →
// fast-loop state resets → successful sync with good data
await vi.waitFor(
() => {
expect(gotData).toBe(true)
},
{ timeout: 15_000 }
)
expect(lastError).not.toBe(null)
expect(lastError!.message).toContain(`fast retry loop`)
warnSpy.mockRestore()
})
it(`should not trigger fast-loop detection when offset advances rapidly`, async () => {
// Normal rapid syncing with advancing offsets should never be flagged
// as a fast loop, even if many requests happen within the detection window.
let requestCount = 0
const warnSpy = vi.spyOn(console, `warn`).mockImplementation(() => {})
const fetchMock = (
..._args: Parameters<typeof fetch>
): Promise<Response> => {
requestCount++
const offset = `${requestCount}_0`
// Return data pages with advancing offsets, then up-to-date
if (requestCount <= 10) {
return Promise.resolve(
new Response(
JSON.stringify([
{
key: `row-${requestCount}`,
value: { id: `${requestCount}` },
headers: {
operation: `insert`,
relation: [`public`, `test`],
},
offset,
},
]),
{
status: 200,
headers: {
'content-type': `application/json`,
'electric-handle': `my-handle`,
'electric-offset': offset,
'electric-schema': `{"id":{"type":"text"}}`,
},
}
)
)
}
// After 10 pages, return up-to-date
return Promise.resolve(
new Response(
JSON.stringify([
{ headers: { control: `up-to-date` }, offset: `10_0` },
]),
{
status: 200,
headers: {
'content-type': `application/json`,
'electric-handle': `my-handle`,
'electric-offset': `10_0`,
'electric-schema': `{"id":{"type":"text"}}`,
},
}
)
)
}
const stream = new ShapeStream({
url: shapeUrl,
params: { table: `test` },
signal: aborter.signal,
fetchClient: fetchMock,
subscribe: false,
})
stream.subscribe(() => {})
// Wait for the stream to reach up-to-date
await vi.waitFor(
() => {
expect(stream.isUpToDate).toBe(true)
},
{ timeout: 5_000 }
)
// Should have made many rapid requests without triggering fast-loop detection
expect(requestCount).toBeGreaterThan(5)
expect(warnSpy).not.toHaveBeenCalledWith(
expect.stringContaining(`fast retry loop`)
)
warnSpy.mockRestore()
})
it(`should not trigger fast-loop detection during live polling`, async () => {
// Once up-to-date, the stream enters live polling mode. Rapid live
// requests must not be flagged as a fast loop.
const liveAborter = new AbortController()
let requestCount = 0
const warnSpy = vi.spyOn(console, `warn`).mockImplementation(() => {})
const fetchMock = async (
..._args: Parameters<typeof fetch>
): Promise<Response> => {
requestCount++
// Stop after enough cycles to prove no fast-loop detection
if (requestCount >= 12) {
liveAborter.abort()
}
// Yield to prevent the tight loop from starving the event loop
await new Promise((r) => setTimeout(r, 1))
// Always return up-to-date to keep the stream in live mode.
// Include electric-cursor for live requests.
return new Response(
JSON.stringify([{ headers: { control: `up-to-date` }, offset: `0_0` }]),
{
status: 200,
headers: {
'content-type': `application/json`,
'electric-handle': `my-handle`,
'electric-offset': `0_0`,
'electric-schema': `{"id":{"type":"text"}}`,
'electric-cursor': `${requestCount}`,
},
}
)
}
const stream = new ShapeStream({
url: shapeUrl,
params: { table: `test` },
signal: liveAborter.signal,
fetchClient: fetchMock,
subscribe: true,
onError: () => {},
})
stream.subscribe(() => {})
// Wait for the stream to complete several live polling cycles then abort
await vi.waitFor(
() => {
expect(requestCount).toBeGreaterThanOrEqual(10)
},
{ timeout: 5_000 }
)
expect(warnSpy).not.toHaveBeenCalledWith(
expect.stringContaining(`fast retry loop`)
)
warnSpy.mockRestore()
})
it(`should apply exponential backoff on onError retries for persistent 4xx errors`, async () => {
// When onError always returns {} on a persistent 4xx error, the retry
// delay should increase exponentially rather than retrying immediately.
const requestTimestamps: number[] = []
const warnSpy = vi.spyOn(console, `warn`).mockImplementation(() => {})
const fetchMock = (
..._args: Parameters<typeof fetch>
): Promise<Response> => {
requestTimestamps.push(Date.now())
return Promise.resolve(new Response(`Forbidden`, { status: 403 }))
}
const stream = new ShapeStream({
url: shapeUrl,
params: { table: `test` },
signal: aborter.signal,
fetchClient: fetchMock,
subscribe: false,
onError: () => ({}),
})
stream.subscribe(() => {})
// Wait for enough retries so we can compare early vs late gaps
await vi.waitFor(
() => {
expect(requestTimestamps.length).toBeGreaterThanOrEqual(6)
},
{ timeout: 15_000 }
)
// Verify gaps between requests grow over time (exponential backoff).
// Compare the sum of the first half vs the second half of gaps to be
// robust against jitter on any individual gap.
const gaps = requestTimestamps
.slice(1)
.map((t, i) => t - requestTimestamps[i]!)
const mid = Math.floor(gaps.length / 2)
const earlySum = gaps.slice(0, mid).reduce((a, b) => a + b, 0)
const lateSum = gaps.slice(mid).reduce((a, b) => a + b, 0)
expect(lateSum).toBeGreaterThan(earlySum)
warnSpy.mockRestore()
})
it(`should tear down immediately when aborted during onError backoff`, async () => {
// When the stream is in the middle of a backoff delay and the user
// aborts, it should tear down promptly rather than waiting for the timer.
let requestCount = 0
const warnSpy = vi.spyOn(console, `warn`).mockImplementation(() => {})
const fetchMock = (
..._args: Parameters<typeof fetch>
): Promise<Response> => {
requestCount++
return Promise.resolve(new Response(`Forbidden`, { status: 403 }))
}
const localAborter = new AbortController()
const stream = new ShapeStream({
url: shapeUrl,
params: { table: `test` },
signal: localAborter.signal,
fetchClient: fetchMock,
subscribe: false,
onError: () => ({}),
})
stream.subscribe(() => {})
// Wait for at least one retry so we know backoff is active
await vi.waitFor(
() => {
expect(requestCount).toBeGreaterThanOrEqual(2)
},
{ timeout: 5_000 }
)
const countBeforeAbort = requestCount
// Abort the stream
localAborter.abort()
// Give a tick for teardown
await resolveInMacrotask(undefined)
// No more requests should have been made after abort
expect(requestCount).toBe(countBeforeAbort)
warnSpy.mockRestore()
})
it(`should warn on 2nd+ onError retry attempt`, async () => {
// The stream should log a console.warn starting from the 2nd retry
// to help developers diagnose persistent error loops.
const warnSpy = vi.spyOn(console, `warn`).mockImplementation(() => {})
let requestCount = 0
const fetchMock = (
..._args: Parameters<typeof fetch>
): Promise<Response> => {
requestCount++
return Promise.resolve(new Response(`Forbidden`, { status: 403 }))
}
const stream = new ShapeStream({
url: shapeUrl,
params: { table: `test` },
signal: aborter.signal,
fetchClient: fetchMock,
subscribe: false,
onError: () => ({}),
})
stream.subscribe(() => {})
// Wait for enough retries to trigger the warning
await vi.waitFor(
() => {
expect(requestCount).toBeGreaterThanOrEqual(3)
},
{ timeout: 15_000 }
)
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining(`onError retry backoff`)
)
warnSpy.mockRestore()
})
it(`should clean up abort listeners after onError backoff timer expires`, async () => {
// When the backoff timer expires normally (not via abort), the abort
// listener must be removed to prevent closure accumulation on
// long-lived streams with many recoverable errors.
let requestCount = 0
const warnSpy = vi.spyOn(console, `warn`).mockImplementation(() => {})
const addSpy = vi.fn()
const removeSpy = vi.fn()
const localAborter = new AbortController()
const originalAdd = localAborter.signal.addEventListener.bind(
localAborter.signal
)
const originalRemove = localAborter.signal.removeEventListener.bind(
localAborter.signal
)
localAborter.signal.addEventListener = (
...args: Parameters<typeof localAborter.signal.addEventListener>
) => {
addSpy(...args)
return originalAdd(...args)
}
localAborter.signal.removeEventListener = (
...args: Parameters<typeof localAborter.signal.removeEventListener>
) => {
removeSpy(...args)
return originalRemove(...args)
}
const fetchMock = (
..._args: Parameters<typeof fetch>
): Promise<Response> => {
requestCount++
return Promise.resolve(new Response(`Forbidden`, { status: 403 }))
}
const stream = new ShapeStream({
url: shapeUrl,
params: { table: `test` },
signal: localAborter.signal,
fetchClient: fetchMock,
subscribe: false,
onError: () => ({}),
})
stream.subscribe(() => {})
// Wait for several retries so multiple backoff timers expire normally
await vi.waitFor(
() => {
expect(requestCount).toBeGreaterThanOrEqual(4)
},
{ timeout: 15_000 }
)
localAborter.abort()
// Each backoff cycle should have added AND removed an abort listener.
// The remove count should match the add count (minus 1 for the final
// cycle that was interrupted by abort, where { once: true } handles cleanup).
const abortAdds = addSpy.mock.calls.filter(
(args: unknown[]) => args[0] === `abort`
).length
const abortRemoves = removeSpy.mock.calls.filter(
(args: unknown[]) => args[0] === `abort`
).length
expect(abortAdds).toBeGreaterThanOrEqual(3)
expect(abortRemoves).toBeGreaterThanOrEqual(abortAdds - 1)
warnSpy.mockRestore()
})
})