-
Notifications
You must be signed in to change notification settings - Fork 113
Expand file tree
/
Copy pathhttp.test.ts
More file actions
989 lines (909 loc) · 38.2 KB
/
Copy pathhttp.test.ts
File metadata and controls
989 lines (909 loc) · 38.2 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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
import { describe, expect, it, vi } from 'vitest';
import { ApiError, InterruptError, RequestTimeoutError, TransportError } from './errors.js';
import type { DebugEvent } from './http.js';
import { HttpClient, REQUEST_TIMEOUT_DEFAULT_MS, buildUrl, parseRetryAfter } from './http.js';
import { VERSION } from '../version.js';
function jsonResponse(body: unknown, init: ResponseInit = {}): Response {
return new Response(JSON.stringify(body), {
status: 200,
headers: { 'content-type': 'application/json' },
...init,
});
}
function errorEnvelopeResponse(status: number, code: string, init: ResponseInit = {}): Response {
return jsonResponse(
{
error: {
code,
message: `Error ${code}`,
nextAction: 'do something',
requestId: 'req_1',
details: {},
},
},
{ status, ...init },
);
}
function makeClient(
fetchImpl: typeof fetch,
options: {
apiKey?: string | null;
onDebug?: (e: DebugEvent) => void;
onServerVersion?: (info: { minVersion?: string }) => void;
maxResponseBytes?: number;
} = {},
): HttpClient {
const apiKey = 'apiKey' in options ? (options.apiKey ?? undefined) : 'sk-test';
return new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey,
fetchImpl,
sleep: () => Promise.resolve(),
random: () => 0,
onDebug: options.onDebug,
onServerVersion: options.onServerVersion,
maxResponseBytes: options.maxResponseBytes,
});
}
describe('response size guard (maxResponseBytes)', () => {
it('rejects a response whose Content-Length exceeds the cap', async () => {
// jsonResponse sets a real Content-Length; a 50-byte cap is well under it.
const fetchImpl = vi.fn().mockResolvedValue(jsonResponse({ blob: 'x'.repeat(500) }));
const client = makeClient(fetchImpl as unknown as typeof fetch, { maxResponseBytes: 50 });
const err = await client.get('/tests').catch((e: unknown) => e);
expect(err).toBeInstanceOf(ApiError);
expect((err as ApiError).code).toBe('PAYLOAD_TOO_LARGE');
expect((err as ApiError).exitCode).toBe(5);
expect((err as ApiError).getDetail('maxBytes')).toBe(50);
});
it('rejects an over-cap chunked response that has no Content-Length', async () => {
// A body built from a ReadableStream carries no Content-Length, so only the
// streaming byte-counter can catch it.
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(encoder.encode('{"data":"'));
controller.enqueue(encoder.encode('y'.repeat(500)));
controller.enqueue(encoder.encode('"}'));
controller.close();
},
});
const fetchImpl = vi
.fn()
.mockResolvedValue(
new Response(stream, { status: 200, headers: { 'content-type': 'application/json' } }),
);
const client = makeClient(fetchImpl as unknown as typeof fetch, { maxResponseBytes: 50 });
const err = await client.get('/tests').catch((e: unknown) => e);
expect(err).toBeInstanceOf(ApiError);
expect((err as ApiError).code).toBe('PAYLOAD_TOO_LARGE');
});
it('reads a within-cap response unchanged', async () => {
const fetchImpl = vi.fn().mockResolvedValue(jsonResponse({ ok: true, items: [1, 2, 3] }));
const client = makeClient(fetchImpl as unknown as typeof fetch, {
maxResponseBytes: 1_000_000,
});
const body = await client.get<{ ok: boolean; items: number[] }>('/tests');
expect(body).toEqual({ ok: true, items: [1, 2, 3] });
});
});
describe('CLIENT_TOO_OLD (426)', () => {
it('is not retried — fails fast with the typed error', async () => {
const fetchImpl = vi.fn().mockResolvedValue(errorEnvelopeResponse(426, 'CLIENT_TOO_OLD'));
const client = makeClient(fetchImpl as unknown as typeof fetch);
const err = await client.get('/me').catch((e: unknown) => e);
expect(err).toBeInstanceOf(ApiError);
expect((err as ApiError).code).toBe('CLIENT_TOO_OLD');
expect((err as ApiError).exitCode).toBe(14);
expect(fetchImpl).toHaveBeenCalledTimes(1); // no retry
});
});
describe('onServerVersion hook', () => {
it('fires with the parsed floor header on a 2xx response', async () => {
const onServerVersion = vi.fn();
const fetchImpl = vi.fn().mockResolvedValue(
jsonResponse(
{ ok: true },
{
headers: {
'content-type': 'application/json',
'x-testsprite-cli-min-version': '1.0.0',
},
},
),
);
const client = makeClient(fetchImpl as unknown as typeof fetch, { onServerVersion });
await client.get('/me');
expect(onServerVersion).toHaveBeenCalledWith({ minVersion: '1.0.0' });
});
it('fires on a non-2xx response too (the floor header rides on every response)', async () => {
const onServerVersion = vi.fn();
const fetchImpl = vi.fn().mockResolvedValue(
errorEnvelopeResponse(404, 'NOT_FOUND', {
headers: {
'content-type': 'application/json',
'x-testsprite-cli-min-version': '1.0.0',
},
}),
);
const client = makeClient(fetchImpl as unknown as typeof fetch, { onServerVersion });
await client.get('/tests/missing').catch(() => undefined);
expect(onServerVersion).toHaveBeenCalledWith({ minVersion: '1.0.0' });
});
it('does not fire when the floor header is absent', async () => {
const onServerVersion = vi.fn();
const fetchImpl = vi.fn().mockResolvedValue(jsonResponse({ ok: true }));
const client = makeClient(fetchImpl as unknown as typeof fetch, { onServerVersion });
await client.get('/me');
expect(onServerVersion).not.toHaveBeenCalled();
});
});
describe('buildUrl', () => {
it('handles trailing slashes and absolute paths', () => {
expect(buildUrl('https://api.example.com/api/cli/v1', '/me')).toBe(
'https://api.example.com/api/cli/v1/me',
);
expect(buildUrl('https://api.example.com/api/cli/v1/', 'me')).toBe(
'https://api.example.com/api/cli/v1/me',
);
});
it('serializes query params and skips undefined values', () => {
const url = buildUrl('https://api.example.com/api/cli/v1', '/tests', {
pageSize: 50,
cursor: undefined,
type: 'frontend',
});
const parsed = new URL(url);
expect(parsed.searchParams.get('pageSize')).toBe('50');
expect(parsed.searchParams.get('cursor')).toBeNull();
expect(parsed.searchParams.get('type')).toBe('frontend');
});
});
describe('parseRetryAfter', () => {
it('returns undefined for null/empty headers', () => {
expect(parseRetryAfter(null)).toBeUndefined();
expect(parseRetryAfter('')).toBeUndefined();
});
it('parses integer seconds', () => {
expect(parseRetryAfter('5')).toBe(5);
expect(parseRetryAfter('0')).toBe(0);
});
it('parses HTTP-date headers (positive)', () => {
const future = new Date(Date.now() + 10_000).toUTCString();
const value = parseRetryAfter(future);
expect(value).toBeGreaterThanOrEqual(9);
expect(value).toBeLessThanOrEqual(11);
});
it('clamps past dates to 0', () => {
expect(parseRetryAfter(new Date(Date.now() - 60_000).toUTCString())).toBe(0);
});
it('returns undefined for unparseable headers', () => {
expect(parseRetryAfter('not-a-thing')).toBeUndefined();
});
});
describe('HttpClient happy path', () => {
it('returns parsed JSON and propagates x-api-key + x-request-id', async () => {
const fetchImpl = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
const headers = new Headers(init?.headers);
expect(headers.get('x-api-key')).toBe('sk-test');
expect(headers.get('authorization')).toBeNull();
expect(headers.get('x-request-id')).toMatch(/^cli_/);
expect(input.toString()).toBe('https://api.example.com/api/cli/v1/me');
return jsonResponse({ userId: 'u1' });
});
const client = makeClient(fetchImpl as unknown as typeof fetch);
const body = await client.get<{ userId: string }>('/me');
expect(body.userId).toBe('u1');
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
it('sends User-Agent header as testsprite-cli/<version>', async () => {
const fetchImpl = vi.fn(async (_input: string | URL | Request, init?: RequestInit) => {
const headers = new Headers(init?.headers);
expect(headers.get('user-agent')).toBe(`testsprite-cli/${VERSION}`);
expect(headers.get('user-agent')).toMatch(/^testsprite-cli\/\S+$/);
return jsonResponse({});
});
const client = makeClient(fetchImpl as unknown as typeof fetch);
await client.get('/me');
});
it('honors a caller-supplied requestId', async () => {
const fetchImpl = vi.fn(async (_input: string | URL | Request, init?: RequestInit) => {
const headers = new Headers(init?.headers);
expect(headers.get('x-request-id')).toBe('caller-supplied');
return jsonResponse({});
});
const client = makeClient(fetchImpl as unknown as typeof fetch);
await client.get('/me', { requestId: 'caller-supplied' });
});
it('throws AUTH_REQUIRED locally when no key is configured', async () => {
const fetchImpl = vi.fn();
const client = makeClient(fetchImpl as unknown as typeof fetch, { apiKey: null });
await expect(client.get('/me')).rejects.toMatchObject({
code: 'AUTH_REQUIRED',
exitCode: 3,
});
expect(fetchImpl).not.toHaveBeenCalled();
});
});
describe('HttpClient — 200 response with a non-JSON body', () => {
function htmlResponse(status = 200): Response {
return new Response('<!DOCTYPE html><html><body>Login</body></html>', {
status,
headers: { 'content-type': 'text/html' },
});
}
it('throws a typed INTERNAL ApiError (not a raw SyntaxError) with the requestId and details', async () => {
const fetchImpl = vi.fn(async () => htmlResponse());
const client = makeClient(fetchImpl as unknown as typeof fetch);
let caught: unknown;
try {
await client.get('/me');
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(ApiError);
const apiErr = caught as ApiError;
expect(apiErr.code).toBe('INTERNAL');
expect(apiErr.exitCode).toBe(1);
expect(apiErr.requestId).toMatch(/^cli_/);
expect(apiErr.message).toContain('non-JSON response');
expect(apiErr.nextAction).toContain('TESTSPRITE_API_URL');
expect(apiErr.details).toMatchObject({ httpStatus: 200, contentType: 'text/html' });
expect(String(apiErr.details.parseError)).toContain('JSON');
});
it('does not retry a malformed 200 body (single fetch call)', async () => {
const fetchImpl = vi.fn(async () => htmlResponse());
const client = makeClient(fetchImpl as unknown as typeof fetch);
await expect(client.get('/me')).rejects.toBeInstanceOf(ApiError);
// A non-JSON success body is a hard config error, not a transient transport
// failure — it must not burn the retry budget.
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
it('handles an empty 200 body the same way', async () => {
const fetchImpl = vi.fn(
async () =>
new Response('', { status: 200, headers: { 'content-type': 'application/json' } }),
);
const client = makeClient(fetchImpl as unknown as typeof fetch);
await expect(client.get('/me')).rejects.toMatchObject({ code: 'INTERNAL', exitCode: 1 });
});
});
describe('HttpClient error mapping', () => {
it('does not retry AUTH_INVALID and exits 3', async () => {
const fetchImpl = vi.fn(async () => errorEnvelopeResponse(401, 'AUTH_INVALID'));
const client = makeClient(fetchImpl as unknown as typeof fetch);
await expect(client.get('/me')).rejects.toBeInstanceOf(ApiError);
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
it('does not retry NOT_FOUND', async () => {
const fetchImpl = vi.fn(async () => errorEnvelopeResponse(404, 'NOT_FOUND'));
const client = makeClient(fetchImpl as unknown as typeof fetch);
await expect(client.get('/projects/x')).rejects.toMatchObject({
code: 'NOT_FOUND',
exitCode: 4,
});
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
it('retries CONFLICT once then propagates', async () => {
const fetchImpl = vi.fn(async () => errorEnvelopeResponse(409, 'CONFLICT'));
const client = makeClient(fetchImpl as unknown as typeof fetch);
await expect(client.get('/me')).rejects.toMatchObject({ code: 'CONFLICT', exitCode: 6 });
expect(fetchImpl).toHaveBeenCalledTimes(2);
});
it('retries INTERNAL once then propagates', async () => {
const fetchImpl = vi.fn(async () => errorEnvelopeResponse(500, 'INTERNAL'));
const client = makeClient(fetchImpl as unknown as typeof fetch);
await expect(client.get('/me')).rejects.toMatchObject({ code: 'INTERNAL', exitCode: 1 });
expect(fetchImpl).toHaveBeenCalledTimes(2);
});
it('retries RATE_LIMITED up to 3 times honoring Retry-After', async () => {
const sleepCalls: number[] = [];
const fetchImpl = vi.fn(async () =>
errorEnvelopeResponse(429, 'RATE_LIMITED', { headers: { 'retry-after': '2' } }),
);
const client = new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey: 'sk-test',
fetchImpl: fetchImpl as unknown as typeof fetch,
sleep: ms => {
sleepCalls.push(ms);
return Promise.resolve();
},
});
await expect(client.get('/me')).rejects.toMatchObject({
code: 'RATE_LIMITED',
exitCode: 11,
});
expect(fetchImpl).toHaveBeenCalledTimes(3);
expect(sleepCalls).toEqual([2000, 2000]);
});
it('retries UNAVAILABLE up to 4 times with bounded backoff', async () => {
const fetchImpl = vi.fn(async () => errorEnvelopeResponse(503, 'UNAVAILABLE'));
const client = makeClient(fetchImpl as unknown as typeof fetch);
await expect(client.get('/me')).rejects.toMatchObject({
code: 'UNAVAILABLE',
exitCode: 10,
});
expect(fetchImpl).toHaveBeenCalledTimes(4);
});
it('retries transport errors then propagates as TransportError', async () => {
const fetchImpl = vi.fn(async () => {
throw new Error('ECONNRESET');
});
const client = makeClient(fetchImpl as unknown as typeof fetch);
await expect(client.get('/me')).rejects.toBeInstanceOf(TransportError);
expect(fetchImpl).toHaveBeenCalledTimes(4);
});
it('does not retry transport errors for keyless writes', async () => {
const fetchImpl = vi.fn(async () => {
throw new Error('ECONNRESET');
});
const client = makeClient(fetchImpl as unknown as typeof fetch);
await expect(client.post('/projects', { body: { name: 'Checkout' } })).rejects.toBeInstanceOf(
TransportError,
);
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
it('retries transport errors for writes with an idempotency key', async () => {
const fetchImpl = vi.fn(async () => {
throw new Error('ECONNRESET');
});
const client = makeClient(fetchImpl as unknown as typeof fetch);
await expect(
client.post('/projects', {
body: { name: 'Checkout' },
headers: { 'Idempotency-Key': 'op_123' },
}),
).rejects.toBeInstanceOf(TransportError);
expect(fetchImpl).toHaveBeenCalledTimes(4);
});
it('does not retry AbortError', async () => {
const fetchImpl = vi.fn(async () => {
const err = new Error('aborted');
err.name = 'AbortError';
throw err;
});
const client = makeClient(fetchImpl as unknown as typeof fetch);
await expect(client.get('/me')).rejects.toMatchObject({ name: 'AbortError' });
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
it('falls back to INTERNAL for malformed error bodies', async () => {
const fetchImpl = vi.fn(async () => new Response('not json', { status: 500 }));
const client = makeClient(fetchImpl as unknown as typeof fetch);
await expect(client.get('/me')).rejects.toMatchObject({ code: 'INTERNAL' });
});
});
describe('HttpClient debug events', () => {
it('emits request → response on success', async () => {
const events: DebugEvent[] = [];
const fetchImpl = vi.fn(async () => jsonResponse({ ok: true }));
const client = makeClient(fetchImpl as unknown as typeof fetch, {
onDebug: e => events.push(e),
});
await client.get('/me');
expect(events.map(e => e.kind)).toEqual(['request', 'response']);
expect(events[0]?.method).toBe('GET');
expect(events[1]?.status).toBe(200);
});
it('emits error → retry → request → error sequence on retry', async () => {
const events: DebugEvent[] = [];
let count = 0;
const fetchImpl = vi.fn(async () => {
count += 1;
if (count === 1) return errorEnvelopeResponse(500, 'INTERNAL');
return jsonResponse({ ok: true });
});
const client = makeClient(fetchImpl as unknown as typeof fetch, {
onDebug: e => events.push(e),
});
await client.get('/me');
expect(events.map(e => e.kind)).toEqual(['request', 'error', 'retry', 'request', 'response']);
});
it('debug events never include the api key', async () => {
const events: DebugEvent[] = [];
const fetchImpl = vi.fn(async () => jsonResponse({ ok: true }));
const client = makeClient(fetchImpl as unknown as typeof fetch, {
apiKey: 'sk-secret-0123456789',
onDebug: e => events.push(e),
});
await client.get('/me');
const serialized = JSON.stringify(events);
expect(serialized).not.toContain('sk-secret');
expect(serialized).not.toContain('x-api-key');
});
});
describe('HttpClient transport-edge statuses', () => {
it.each([408, 502, 504] as const)(
'%d with no envelope retries up to MAX_ATTEMPTS_TRANSPORT and propagates as TransportError',
async status => {
const fetchImpl = vi.fn(async () => new Response('proxy gateway html', { status }));
const client = makeClient(fetchImpl as unknown as typeof fetch);
await expect(client.get('/me')).rejects.toBeInstanceOf(TransportError);
expect(fetchImpl).toHaveBeenCalledTimes(4);
},
);
it('does not retry bare transport-edge responses for keyless writes', async () => {
const fetchImpl = vi.fn(async () => new Response('proxy gateway html', { status: 502 }));
const client = makeClient(fetchImpl as unknown as typeof fetch);
await expect(client.post('/projects', { body: { name: 'Checkout' } })).rejects.toBeInstanceOf(
TransportError,
);
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
it('retries bare transport-edge responses for writes with an idempotency key', async () => {
const fetchImpl = vi.fn(async () => new Response('proxy gateway html', { status: 502 }));
const client = makeClient(fetchImpl as unknown as typeof fetch);
await expect(
client.post('/projects', {
body: { name: 'Checkout' },
headers: { 'idempotency-key': 'op_123' },
}),
).rejects.toBeInstanceOf(TransportError);
expect(fetchImpl).toHaveBeenCalledTimes(4);
});
it('502 carrying our envelope still maps to its catalog code', async () => {
const body = {
error: {
code: 'INTERNAL',
message: 'oops',
nextAction: 'retry',
requestId: 'req',
details: {},
},
};
const fetchImpl = vi.fn(
async () =>
new Response(JSON.stringify(body), {
status: 502,
headers: { 'content-type': 'application/json' },
}),
);
const client = makeClient(fetchImpl as unknown as typeof fetch);
await expect(client.get('/me')).rejects.toMatchObject({ code: 'INTERNAL' });
// INTERNAL retries once → two attempts total
expect(fetchImpl).toHaveBeenCalledTimes(2);
});
});
// ---------------------------------------------------------------------------
// Per-request timeout tests
// ---------------------------------------------------------------------------
describe('HttpClient per-request timeout', () => {
/**
* Make a client whose fetch never resolves (stalled TCP simulation).
* We set a short requestTimeoutMs so the test completes quickly.
*/
function makeTimingClient(requestTimeoutMs: number): HttpClient {
const fetchImpl = vi.fn(async (_input: unknown, init?: { signal?: AbortSignal }) => {
// Simulate a stalled connection: wait for the abort signal to fire.
return new Promise<Response>((_resolve, reject) => {
const signal = init?.signal;
if (signal?.aborted) {
const reason = signal.reason;
// AbortSignal.timeout() sets reason to a DOMException with name 'TimeoutError'
const err = new Error(reason?.message ?? 'aborted');
err.name = reason?.name ?? 'TimeoutError';
reject(err);
return;
}
signal?.addEventListener('abort', () => {
const reason = signal.reason;
const err = new Error(reason?.message ?? 'aborted');
err.name = reason?.name ?? 'TimeoutError';
reject(err);
});
});
});
return new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey: 'sk-test',
fetchImpl: fetchImpl as unknown as typeof fetch,
sleep: () => Promise.resolve(),
random: () => 0,
requestTimeoutMs,
});
}
it('throws RequestTimeoutError when fetch stalls past the per-request timeout', async () => {
const client = makeTimingClient(50); // 50ms timeout for fast test
await expect(client.get('/me')).rejects.toBeInstanceOf(RequestTimeoutError);
});
it('RequestTimeoutError has exit code 7 and the timeout in the message', async () => {
const client = makeTimingClient(50);
const err = await client.get('/me').catch(e => e);
expect(err).toBeInstanceOf(RequestTimeoutError);
expect((err as RequestTimeoutError).exitCode).toBe(7);
expect((err as RequestTimeoutError).message).toContain('timed out');
expect((err as RequestTimeoutError).message).toContain('--request-timeout');
expect((err as RequestTimeoutError).timeoutMs).toBe(50);
});
it('does NOT retry when the per-request timeout fires (stall is treated like a one-shot abort)', async () => {
// A stalled fetch aborts; unlike a transport error, the per-request
// timeout should NOT trigger the transport-retry budget (the connection
// is still stalled — retrying won't help in the same second).
let callCount = 0;
const fetchImpl = vi.fn(async (_input: unknown, init?: { signal?: AbortSignal }) => {
callCount += 1;
return new Promise<Response>((_resolve, reject) => {
const signal = (init as RequestInit | undefined)?.signal;
if (signal?.aborted) {
const reason = signal.reason;
const err = new Error(reason?.message ?? 'aborted');
err.name = reason?.name ?? 'TimeoutError';
reject(err);
return;
}
signal?.addEventListener('abort', () => {
const reason = signal.reason;
const err = new Error(reason?.message ?? 'aborted');
err.name = reason?.name ?? 'TimeoutError';
reject(err);
});
});
});
const client = new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey: 'sk-test',
fetchImpl: fetchImpl as unknown as typeof fetch,
sleep: () => Promise.resolve(),
random: () => 0,
requestTimeoutMs: 50, // 50ms timeout
});
const err = await client.get('/me').catch(e => e);
expect(err).toBeInstanceOf(RequestTimeoutError);
// The timeout fires on the first attempt; no retries should occur because
// the abort is re-thrown as RequestTimeoutError, not as a TransportError.
expect(callCount).toBe(1);
});
it('clears the per-attempt timeout after a successful response body is read', async () => {
let capturedSignal: AbortSignal | undefined;
const fetchImpl = vi.fn(async (_input: unknown, init?: RequestInit) => {
capturedSignal = init?.signal ?? undefined;
return jsonResponse({ ok: true });
});
const client = new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey: 'sk-test',
fetchImpl: fetchImpl as unknown as typeof fetch,
sleep: () => Promise.resolve(),
random: () => 0,
requestTimeoutMs: 25,
});
await expect(client.get('/me')).resolves.toEqual({ ok: true });
expect(capturedSignal?.aborted).toBe(false);
await new Promise(resolve => setTimeout(resolve, 50));
expect(capturedSignal?.aborted).toBe(false);
});
it('clears a failed attempt timeout before retry backoff sleeps', async () => {
const attemptSignals: AbortSignal[] = [];
let calls = 0;
const fetchImpl = vi.fn(async (_input: unknown, init?: RequestInit) => {
if (init?.signal) attemptSignals.push(init.signal);
calls += 1;
if (calls === 1) return errorEnvelopeResponse(500, 'INTERNAL');
return jsonResponse({ ok: true });
});
const client = new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey: 'sk-test',
fetchImpl: fetchImpl as unknown as typeof fetch,
sleep: () => new Promise(resolve => setTimeout(resolve, 50)),
random: () => 0,
requestTimeoutMs: 25,
});
await expect(client.get('/me')).resolves.toEqual({ ok: true });
expect(attemptSignals).toHaveLength(2);
expect(attemptSignals.every(signal => signal.aborted === false)).toBe(true);
await new Promise(resolve => setTimeout(resolve, 50));
expect(attemptSignals.every(signal => signal.aborted === false)).toBe(true);
});
it('caller-supplied AbortSignal still propagates as AbortError (not RequestTimeoutError)', async () => {
const controller = new AbortController();
// Abort immediately
controller.abort();
const fetchImpl = vi.fn(async (_input: unknown, init?: { signal?: AbortSignal }) => {
if (init?.signal?.aborted) {
const err = new Error('aborted');
err.name = 'AbortError';
throw err;
}
return new Response('{}', { status: 200 });
});
const client = new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey: 'sk-test',
fetchImpl: fetchImpl as unknown as typeof fetch,
sleep: () => Promise.resolve(),
random: () => 0,
requestTimeoutMs: 120_000,
});
const err = await client.get('/me', { signal: controller.signal }).catch(e => e);
// Should propagate as AbortError, NOT RequestTimeoutError
expect(err).not.toBeInstanceOf(RequestTimeoutError);
expect((err as Error).name).toBe('AbortError');
});
it('preserves RequestTimeoutError when the caller aborts after the request timeout wins', async () => {
const controller = new AbortController();
const fetchImpl = vi.fn(async (_input: unknown, init?: { signal?: AbortSignal }) => {
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => {
const reason = init.signal?.reason;
controller.abort(new Error('caller aborted after timeout'));
const err = new Error(reason?.message ?? 'timed out');
err.name = reason?.name ?? 'TimeoutError';
reject(err);
});
});
});
const client = new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey: 'sk-test',
fetchImpl: fetchImpl as unknown as typeof fetch,
sleep: () => Promise.resolve(),
random: () => 0,
requestTimeoutMs: 1,
});
const err = await client.get('/me', { signal: controller.signal }).catch(e => e);
expect(err).toBeInstanceOf(RequestTimeoutError);
expect((err as RequestTimeoutError).exitCode).toBe(7);
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
it('defaults to REQUEST_TIMEOUT_DEFAULT_MS when no requestTimeoutMs is supplied', () => {
// Verify the default is wired without actually waiting 120s.
// We test via the exported constant rather than exercising the stall.
expect(REQUEST_TIMEOUT_DEFAULT_MS).toBe(120_000);
const client = new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey: 'sk-test',
fetchImpl: vi.fn() as unknown as typeof fetch,
});
// Access the private field via cast to verify it was set correctly.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((client as any).requestTimeoutMs).toBe(REQUEST_TIMEOUT_DEFAULT_MS);
});
it('polling path: caller-supplied short-lived signal fires as AbortError, not RequestTimeoutError', async () => {
// Simulate the polling-path pattern: caller creates a short-deadline
// AbortController (like poll.ts does per iteration), http client has a
// long requestTimeoutMs. The caller abort fires first and should NOT
// be repackaged as RequestTimeoutError.
const controller = new AbortController();
const fetchImpl = vi.fn(async (_input: unknown, init?: { signal?: AbortSignal }) => {
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener('abort', () => {
const reason = init.signal?.reason;
const err = new Error(reason?.message ?? 'caller-aborted');
err.name = reason?.name ?? 'AbortError';
reject(err);
});
// Abort after 10ms (simulating poll's iteration deadline firing first)
setTimeout(() => controller.abort(), 10);
});
});
const client = new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey: 'sk-test',
fetchImpl: fetchImpl as unknown as typeof fetch,
sleep: () => Promise.resolve(),
random: () => 0,
requestTimeoutMs: 120_000, // long per-request timeout — should not fire
});
const err = await client.get('/me', { signal: controller.signal }).catch(e => e);
expect(err).not.toBeInstanceOf(RequestTimeoutError);
expect((err as Error).name).toBe('AbortError');
});
it('classifies a timeout during body read (OK response) as RequestTimeoutError', async () => {
const timeoutErr = Object.assign(new Error('body stalled'), { name: 'TimeoutError' });
const fetchImpl = vi.fn(async () => {
// Resolve the fetch only after the (1ms) per-request timeout has fired, then
// reject the body read — exercises the post-fetch classification path that
// previously let the raw abort escape unclassified.
await new Promise(r => setTimeout(r, 15));
return {
ok: true,
status: 200,
headers: new Headers(),
body: new ReadableStream<Uint8Array>({
start(controller) {
controller.error(timeoutErr);
},
}),
} as unknown as Response;
});
const client = new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey: 'sk-test',
fetchImpl: fetchImpl as unknown as typeof fetch,
sleep: () => Promise.resolve(),
random: () => 0,
requestTimeoutMs: 1,
});
const err = await client.get('/me').catch(e => e);
expect(err).toBeInstanceOf(RequestTimeoutError);
});
it('classifies a timeout during body read (non-OK response) as RequestTimeoutError', async () => {
const timeoutErr = Object.assign(new Error('body stalled'), { name: 'TimeoutError' });
const fetchImpl = vi.fn(async () => {
await new Promise(r => setTimeout(r, 15));
return {
ok: false,
status: 500,
headers: new Headers(),
json: () => Promise.reject(timeoutErr),
} as unknown as Response;
});
const client = new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey: 'sk-test',
fetchImpl: fetchImpl as unknown as typeof fetch,
sleep: () => Promise.resolve(),
random: () => 0,
requestTimeoutMs: 1,
});
const err = await client.get('/me').catch(e => e);
expect(err).toBeInstanceOf(RequestTimeoutError);
});
});
describe('HttpClient shutdown signal (DEV-331 graceful detach)', () => {
/** Stalled fetch that rejects with the effective signal's reason on abort. */
function stalledFetch(callCounter?: { count: number }): typeof fetch {
return vi.fn(async (_input: unknown, init?: { signal?: AbortSignal }) => {
if (callCounter) callCounter.count += 1;
return new Promise<Response>((_resolve, reject) => {
const signal = init?.signal;
const rejectWithReason = (): void => {
const reason: unknown = signal?.reason;
if (reason instanceof Error) {
reject(reason);
return;
}
const err = new Error('aborted');
err.name = 'AbortError';
reject(err);
};
if (signal?.aborted) {
rejectWithReason();
return;
}
signal?.addEventListener('abort', rejectWithReason, { once: true });
});
}) as unknown as typeof fetch;
}
function makeShutdownClient(
shutdownSignal: AbortSignal,
callCounter?: { count: number },
): HttpClient {
return new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey: 'sk-test',
fetchImpl: stalledFetch(callCounter),
sleep: () => Promise.resolve(),
random: () => 0,
shutdownSignal,
});
}
it('aborts an in-flight fetch with the InterruptError reason (no retry, no re-wrap)', async () => {
const counter = { count: 0 };
const shutdown = new AbortController();
const client = makeShutdownClient(shutdown.signal, counter);
const pending = client.get('/runs/run_1');
queueMicrotask(() => shutdown.abort(new InterruptError('SIGINT')));
const err = await pending.catch(e => e);
expect(err).toBeInstanceOf(InterruptError);
expect((err as InterruptError).signal).toBe('SIGINT');
expect((err as InterruptError).exitCode).toBe(130);
expect(counter.count).toBe(1); // never retried
});
it('classifies an anonymous AbortError as the interrupt when the shutdown signal fired', async () => {
// Some runtimes reject with a bare AbortError instead of the abort reason;
// rethrowIfAbort must still classify shutdown-first (never TransportError,
// never RequestTimeoutError).
const shutdown = new AbortController();
const fetchImpl = vi.fn(async (_input: unknown, init?: { signal?: AbortSignal }) => {
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener(
'abort',
() => {
const err = new Error('aborted');
err.name = 'AbortError';
reject(err);
},
{ once: true },
);
});
}) as unknown as typeof fetch;
const client = new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey: 'sk-test',
fetchImpl,
sleep: () => Promise.resolve(),
random: () => 0,
shutdownSignal: shutdown.signal,
});
const pending = client.get('/runs/run_1');
queueMicrotask(() => shutdown.abort(new InterruptError('SIGTERM')));
const err = await pending.catch(e => e);
expect(err).toBeInstanceOf(InterruptError);
expect((err as InterruptError).signal).toBe('SIGTERM');
});
it('skips dispatch entirely when the shutdown signal is already aborted', async () => {
const counter = { count: 0 };
const shutdown = new AbortController();
shutdown.abort(new InterruptError('SIGINT'));
const client = makeShutdownClient(shutdown.signal, counter);
const err = await client.get('/me').catch(e => e);
expect(err).toBeInstanceOf(InterruptError);
expect(counter.count).toBe(0);
});
it('passes an InterruptError from a caller-composed signal through untouched (poll path, no shutdownSignal configured)', async () => {
// The polling loop composes the shutdown signal into its per-iteration
// caller signal; the fetch then rejects with the InterruptError reason
// even though the client itself has no shutdownSignal.
const counter = { count: 0 };
const fetchImpl = stalledFetch(counter);
const client = new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey: 'sk-test',
fetchImpl,
sleep: () => Promise.resolve(),
random: () => 0,
});
const caller = new AbortController();
const pending = client.get('/runs/run_1', { signal: caller.signal });
queueMicrotask(() => caller.abort(new InterruptError('SIGINT')));
const err = await pending.catch(e => e);
expect(err).toBeInstanceOf(InterruptError);
expect(counter.count).toBe(1); // no transport retry
});
});
describe('HttpClient retry-delay sleep bails on shutdown (DEV-331 codex finding 1)', () => {
it('a shutdown during a transport-retry sleep rejects with InterruptError immediately', async () => {
// First fetch throws a transport error → the client schedules a retry
// sleep. The injected sleep NEVER resolves, so only the shutdown race can
// end it — without the bail, the interrupt would wait out the delay
// (e.g. a Retry-After: 60) before surfacing.
const shutdown = new AbortController();
let calls = 0;
const fetchImpl = vi.fn(async () => {
calls += 1;
throw new Error('socket hang up');
}) as unknown as typeof fetch;
const client = new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey: 'sk-test',
fetchImpl,
sleep: () => new Promise<void>(() => {}), // never resolves
random: () => 0,
shutdownSignal: shutdown.signal,
});
const pending = client.get('/me');
// Let the first attempt fail and the retry sleep begin, then interrupt.
await new Promise(resolve => setTimeout(resolve, 10));
shutdown.abort(new InterruptError('SIGINT'));
const err = await pending.catch(e => e);
expect(err).toBeInstanceOf(InterruptError);
expect(calls).toBe(1); // the retry never dispatched
});
it('a shutdown during a RATE_LIMITED Retry-After sleep rejects with InterruptError immediately', async () => {
const shutdown = new AbortController();
let calls = 0;
const fetchImpl = vi.fn(async () => {
calls += 1;
return errorEnvelopeResponse(429, 'RATE_LIMITED', {
headers: { 'content-type': 'application/json', 'retry-after': '60' },
});
}) as unknown as typeof fetch;
const client = new HttpClient({
baseUrl: 'https://api.example.com/api/cli/v1',
apiKey: 'sk-test',
fetchImpl,
sleep: () => new Promise<void>(() => {}), // never resolves
random: () => 0,
shutdownSignal: shutdown.signal,
});
const pending = client.get('/me');
await new Promise(resolve => setTimeout(resolve, 10));
shutdown.abort(new InterruptError('SIGTERM'));
const err = await pending.catch(e => e);
expect(err).toBeInstanceOf(InterruptError);
expect((err as InterruptError).signal).toBe('SIGTERM');
expect(calls).toBe(1);
});
});