Repository navigation
Expand file tree
/
Copy pathfetch.ts
More file actions
1340 lines (1228 loc) · 53.4 KB
/
Copy pathfetch.ts
File metadata and controls
1340 lines (1228 loc) · 53.4 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
990
991
992
993
994
995
996
997
998
999
1000
import type { StandardSchemaV1 } from '@standard-schema/spec';
import merge from 'lodash.merge';
import { BreakerError, BreakerState, Circuit, Module, Ratelimit, RatelimitError, Retry, RetryMode, SlidingCountBreaker, TimeoutError } from 'mollitia';
import { CONTEXT, ContextHeader, ContextKey, ContextKeyHttp, ContextKeyHttpRequest, ContextKeyHttpResponse } from '@smooai/logger/Logger';
import { handleSchemaValidation, HumanReadableSchemaError } from '@smooai/utils/validation/standardSchema';
import { contextLogger } from './logger';
import { redactBody, redactHeaders, redactQueryString, redactUrl } from './redact';
export { RatelimitError, TimeoutError } from 'mollitia';
export * from 'mollitia';
declare global {
interface Window {
fetch: typeof fetch;
}
interface Self {
fetch: typeof fetch;
}
// Add declarations for window and self globals
const window: Window & typeof globalThis;
const self: Self & typeof globalThis;
}
/**
* Determine the appropriate fetch implementation based on the environment.
* Uses global.fetch in Node.js environments and window.fetch in browser environments.
*/
const globalFetch = (): typeof global.fetch => {
// Browser environment
if (typeof window !== 'undefined' && window.fetch) {
return window.fetch.bind(window);
}
// Web Worker environment
if (typeof self !== 'undefined' && self.fetch) {
return self.fetch.bind(self);
}
// Node.js environment
if (typeof global !== 'undefined') {
// Modern Node.js (v18+) with built-in fetch
if (global.fetch) {
return global.fetch.bind(global);
}
// For older Node.js versions, suggest installing node-fetch
throw new Error(
'No fetch implementation found in Node.js environment. ' + 'For Node.js versions < 18, please install node-fetch: npm install node-fetch',
);
}
throw new Error('No fetch implementation found. ' + 'Please ensure fetch is available in your environment.');
};
/**
* Cache of undici `Agent` dispatchers keyed by connect-timeout ms, so we build
* one Agent per distinct timeout instead of per request.
*/
const connectTimeoutDispatchers = new Map<number, unknown>();
/**
* Resolve an undici `Agent` dispatcher that bounds the connect phase to
* `connectTimeoutMs`.
*
* Node only: browsers and Web Workers expose no connect-timeout knob at all, so
* this returns `undefined` there and no `dispatcher` is passed — behavior stays
* byte-identical to today, as documented on `connectTimeoutMs`.
*
* `undici` is an OPTIONAL peer dependency, imported lazily so it is never loaded
* unless a connect timeout is actually requested. When it is requested and undici
* is absent, this throws rather than quietly running without the bound the caller
* asked for — a timeout that silently isn't applied is the failure mode this
* whole feature exists to prevent.
*/
async function getConnectTimeoutDispatcher(connectTimeoutMs: number): Promise<unknown | undefined> {
// Only Node's fetch (undici) honors a `dispatcher`. Bail everywhere else.
if (typeof window !== 'undefined' || typeof process === 'undefined' || !process.versions?.node) {
return undefined;
}
const cached = connectTimeoutDispatchers.get(connectTimeoutMs);
if (cached) return cached;
let Agent: new (options: { connect: { timeout: number } }) => unknown;
try {
({ Agent } = await import('undici'));
} catch (error) {
throw new Error(
'connectTimeoutMs requires the optional peer dependency `undici` (Node only). Install it alongside @smooai/fetch, or drop connectTimeoutMs to use the whole-request timeout alone.',
{ cause: error },
);
}
const dispatcher = new Agent({ connect: { timeout: connectTimeoutMs } });
connectTimeoutDispatchers.set(connectTimeoutMs, dispatcher);
return dispatcher;
}
/**
* Interface for browser-compatible logging functionality.
* Provides methods for different log levels with context support.
*/
export interface LoggerInterface {
/**
* Log a debug message with optional context.
* @param message - The message to log
* @param args - Additional arguments to include in the log
*/
debug(message: string, ...args: any[]): void;
/**
* Log an info message with optional context.
* @param message - The message to log
* @param args - Additional arguments to include in the log
*/
info(message: string, ...args: any[]): void;
/**
* Log a warning message with optional context.
* @param message - The message to log
* @param args - Additional arguments to include in the log
*/
warn(message: string, ...args: any[]): void;
/**
* Log an error message with the error object and optional context.
* @param error - The error object to log
* @param message - The error message
* @param args - Additional arguments to include in the log
*/
error(error: Error | unknown, message: string, ...args: any[]): void;
}
const contextLoggerToUse = contextLogger();
/**
* Extended Response type that includes parsed body data and metadata.
* @template T - The type of the response body data
*/
export type ResponseWithBody<T = any> = Response & {
/** The parsed response body data */
data?: T;
/** Whether the response body is JSON */
isJson: boolean;
/** The raw response body as a string */
dataString: string;
};
type Headers = globalThis.Headers;
export type HeadersInit = string[][] | Record<string, string | ReadonlyArray<string>> | Headers;
type RequestInit = globalThis.RequestInit;
export type RequestInfo = string | URL | Request;
type Request = globalThis.Request;
type Response = globalThis.Response;
export type { Headers, RequestInit, Request, Response };
type ResponseType<Schema extends StandardSchemaV1 = never> = Schema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<Schema> : any;
/**
* Defaults set below:
*
* - DEFAULTS
* - DEFAULT_RETRY_OPTIONS
* - DEFAULT_RATE_LIMIT_RETRY_OPTIONS
*/
/**
* Error thrown when an HTTP request fails with a non-2xx status code.
* Includes the response data and attempts to extract error information.
* @template T - The type of the response body data
*/
export class HTTPResponseError<T = any> extends Error {
/** The response object containing the error details */
public response: ResponseWithBody<T>;
constructor(response: ResponseWithBody<T>, msg?: string) {
let errorStr = '';
let errIsSet = false;
if (response.isJson && response.data) {
const data = response.data as any;
if (data.error) {
if (!Array.isArray(data.error)) {
if (data.error.type) {
errorStr += `(${data.error.type}): `;
errIsSet = true;
}
if (data.error.code) {
errorStr += `(${data.error.code}): `;
errIsSet = true;
}
if (data.error.message) {
errorStr += `${data.error.message}`;
errIsSet = true;
}
if (typeof data.error === 'string') {
errorStr += `${data.error}`;
errIsSet = true;
}
}
}
if (data.errorMessages) {
if (Array.isArray(data.errorMessages)) {
errorStr += `${data.errorMessages.join('; ')}`;
errIsSet = true;
}
}
}
if (!errIsSet) {
errorStr = response.dataString || 'Unknown error';
}
super(`${msg ? `${msg}; ` : ''}${errorStr}; HTTP Error Response: ${response.status} ${response.statusText}`);
this.response = response;
}
}
export function isRetryable(status: number) {
return status === 429 || status >= 500;
}
export class RetryError<T = any> extends HTTPResponseError<T> {
constructor(response: ResponseWithBody<T>) {
super(response, 'Retry Error: Ran out of retry attempts.');
this.response = response;
}
}
export type ErrorCallback = (err: any) => boolean;
export type RetryCallback = (err: any, attempt: number) => boolean | number;
/**
* Configuration options for retry behavior.
*/
export interface RetryOptions {
/** Number of retry attempts */
attempts: number;
/** Initial delay between retries in milliseconds */
initialIntervalMs: number;
/** Retry mode (e.g., exponential backoff, jitter) */
mode?: RetryMode;
/** Factor to multiply the interval by for each retry */
factor?: number;
/** Whether to attempt the first retry immediately */
fastFirst?: boolean;
/** Maximum delay between retries in milliseconds */
maxInterval?: number;
/** Amount of random jitter to add to retry delays */
jitterAdjustment?: number;
/** Callback to determine if and when to retry */
onRejection?: RetryCallback;
/**
* Retry non-idempotent methods (POST, PATCH, ...) too. Off by default.
*
* Only idempotent methods (RFC 9110 §9.2.2: GET, HEAD, OPTIONS, TRACE, PUT,
* DELETE) are retried unless this is set or the request carries an
* `Idempotency-Key` header. A POST that timed out or got a 429/5xx may
* already have done its work server-side — re-sending it bills a second
* image, sends a second message, charges a card twice. Set this only when
* the endpoint tolerates a duplicate, and prefer an `Idempotency-Key`.
*
* This overrides `onRejection`: an ineligible request makes exactly one
* attempt and `onRejection` is never consulted.
*/
allowNonIdempotent?: boolean;
}
/** Header that, when set to a non-empty value, makes a non-idempotent request retry-eligible. */
export const IDEMPOTENCY_KEY_HEADER = 'Idempotency-Key';
const IDEMPOTENT_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE', 'PUT', 'DELETE']);
/**
* Whether an HTTP method is idempotent per RFC 9110 §9.2.2 — i.e. sending it
* twice has the same effect on the server as sending it once. Case-insensitive;
* anything unrecognised is treated as non-idempotent.
*/
export function isIdempotentMethod(method: string | undefined): boolean {
return IDEMPOTENT_METHODS.has((method ?? 'GET').toUpperCase());
}
function hasIdempotencyKey(headers: RequestInit['headers']): boolean {
if (!headers) return false;
let value: string | null = null;
if (headers instanceof Headers) {
value = headers.get(IDEMPOTENCY_KEY_HEADER);
} else {
const entries = Array.isArray(headers) ? headers : Object.entries(headers);
const found = entries.find(([key]) => key.toLowerCase() === IDEMPOTENCY_KEY_HEADER.toLowerCase());
value = found ? String(found[1]) : null;
}
return !!value && value.trim().length > 0;
}
/**
* Whether a failed attempt of this request may be re-sent: its method is
* idempotent, the caller set `retry.allowNonIdempotent`, or it carries a
* non-empty `Idempotency-Key` header (the server then dedupes for us).
*/
export function isRetryEligible(init: Pick<RequestInit, 'method' | 'headers'>, retry?: Partial<RetryOptions>): boolean {
return isIdempotentMethod(init.method) || !!retry?.allowNonIdempotent || hasIdempotencyKey(init.headers);
}
export const DEFAULT_RETRY_OPTIONS: RetryOptions = {
attempts: 2,
initialIntervalMs: 500,
mode: RetryMode.JITTER,
factor: 2,
jitterAdjustment: 0.5,
onRejection: (error) => {
if (error instanceof HTTPResponseError) {
if (isRetryable(error.response.status) && error.response.headers?.has('Retry-After')) {
return parseInt(error.response.headers.get('Retry-After')!) * 1000;
}
return isRetryable(error.response.status);
} else if (error instanceof RatelimitError) {
return error.remainingTimeInRatelimit;
} else if (error instanceof TimeoutError) {
return true;
} else if (error instanceof HumanReadableSchemaError) {
return false;
}
return true;
},
};
export const DEFAULT_RATE_LIMIT_RETRY_OPTIONS: RetryOptions = {
attempts: 1,
initialIntervalMs: 500,
onRejection: (error) => {
if (error instanceof RatelimitError) {
return error.remainingTimeInRatelimit + 50;
}
return false;
},
};
/**
* Hook that runs before the request is made, allowing modification of the request.
*
* May return synchronously or async — the fetch pipeline awaits the result, so
* callers can perform asynchronous work (e.g., minting a fresh auth token).
*/
export type PreRequestHook = (url: string, init: RequestInit) => [string, RequestInit] | void | Promise<[string, RequestInit] | void>;
/**
* Provider that returns an auth token to inject as the `Authorization` header.
* May be sync or async. Invoked before every request.
*/
export type AuthTokenProvider = () => string | Promise<string>;
/**
* Hook that runs after a successful response, allowing modification of the response
*/
export type PostResponseSuccessHook<T = any> = (url: string, init: Readonly<RequestInit>, response: ResponseWithBody<T>) => ResponseWithBody<T> | void;
/**
* Hook that runs after a failed response, allowing modification of the error
*/
export type PostResponseErrorHook<T = any> = (url: string, init: Readonly<RequestInit>, error: Error, response?: ResponseWithBody<T>) => Error | void;
/**
* Collection of lifecycle hooks for request/response handling
*/
export interface LifecycleHooks<T = any> {
/** Hook that runs before the request is made */
preRequest?: PreRequestHook;
/** Hook that runs after a successful response */
postResponseSuccess?: PostResponseSuccessHook<T>;
/** Hook that runs after a failed response */
postResponseError?: PostResponseErrorHook<T>;
}
/**
* Configuration options for HTTP requests.
* @template Schema - The schema type for response validation. Must be a StandardSchemaV1 compatible schema (e.g., Zod schema)
*/
export interface RequestOptions<Schema extends StandardSchemaV1 = never> {
/** Custom logger for request logging */
logger?: LoggerInterface;
/**
* Per-attempt timeout. When it fires the attempt is ABORTED (its
* connection is closed, so the server sees the cancel) before any retry.
*/
timeout?: {
/** Timeout duration in milliseconds */
timeoutMs: number;
};
/**
* Connect timeout in milliseconds. Bounds only the connection-establishment
* phase (Node only, via an undici `Agent` dispatcher). When set, a connect
* that never completes (e.g. a black-holed SYN to a dead pod IP still
* lingering in a ClusterIP's iptables) fails in ~this window and the
* configured retry can land on a live endpoint — instead of stalling until
* the whole-request {@link timeout}. Slow-but-alive handlers are unaffected.
* Leaving it unset preserves the previous no-connect-timeout behavior.
* Ignored in browser/worker environments (no connect-timeout knob there).
*/
connectTimeoutMs?: number;
/**
* Retry configuration, deep-merged over {@link DEFAULT_RETRY_OPTIONS}, so
* `retry: { allowNonIdempotent: true }` keeps every other default.
* POST/PATCH are not retried unless `allowNonIdempotent` is set or the
* request carries an `Idempotency-Key` — see {@link RetryOptions.allowNonIdempotent}.
*/
retry?: Partial<RetryOptions>;
/** Schema for response validation. Must be a StandardSchemaV1 compatible schema (e.g., Zod schema) */
schema?: Schema;
/** Lifecycle hooks for request/response handling */
hooks?: LifecycleHooks<ResponseType<Schema>>;
}
const DEFAULTS: RequestOptions<never> = {
logger: contextLoggerToUse,
retry: DEFAULT_RETRY_OPTIONS,
timeout: {
timeoutMs: 10000,
},
};
// RateLimit, CircuitBreaker below is using https://genesys.github.io/mollitia/overview/introduction
/**
* Configuration options for fetch container features like rate limiting and circuit breaking.
*/
export interface FetchContainerOptions {
/** Rate limiting configuration */
rateLimit?: {
/** Maximum number of requests allowed in the period */
limitForPeriod: number;
/** Duration of the rate limit period in milliseconds */
limitPeriodMs: number;
/** Retry configuration for rate limit handling */
retry?: RetryOptions;
};
/** Circuit breaker configuration */
circuitBreaker?: {
/** Current state of the circuit breaker */
state?: BreakerState;
/** Failure rate threshold as a percentage */
failureRateThreshold?: number;
/** Slow call rate threshold as a percentage */
slowCallRateThreshold?: number;
/** Duration threshold for slow calls in milliseconds */
slowCallDurationThresholdMs?: number;
/** Number of calls allowed in half-open state */
permittedNumberOfCallsInHalfOpenState?: number;
/** Maximum delay in half-open state in milliseconds */
halfOpenStateMaxDelayMs?: number;
/** Size of the sliding window for failure rate calculation */
slidingWindowSize?: number;
/** Minimum number of calls for failure rate calculation */
minimumNumberOfCalls?: number;
/** Time to stay in open state in milliseconds */
openStateDelayMs?: number;
/** Callback to determine if an error should trigger circuit breaker */
onError?: ErrorCallback;
};
}
function mergeHeadersWithContext(headersInit?: HeadersInit): HeadersInit {
let newHeadersInit: HeadersInit = {};
if (
CONTEXT[ContextKey.Http] &&
CONTEXT[ContextKey.Http][ContextKeyHttp.Request] &&
CONTEXT[ContextKey.Http][ContextKeyHttp.Request][ContextKeyHttpRequest.UserAgent]
) {
newHeadersInit[ContextHeader.UserAgent] = CONTEXT[ContextKey.Http][ContextKeyHttp.Request][ContextKeyHttpRequest.UserAgent];
}
if (CONTEXT[ContextKey.CorrelationId]) {
newHeadersInit[ContextHeader.CorrelationId] = CONTEXT[ContextKey.CorrelationId];
}
let initialHeaders = headersInit;
if ((initialHeaders && initialHeaders instanceof Headers) || initialHeaders instanceof Map) {
initialHeaders = Array.from(initialHeaders.entries()).reduce((result, entry) => {
result[entry[0]] = entry[1];
return result;
}, {} as any);
}
newHeadersInit = merge({}, initialHeaders, newHeadersInit);
return newHeadersInit;
}
// Both helpers below feed logger payloads only — never the outgoing request —
// so they redact credentials in place. `@smooai/logger` does no redaction of its
// own, so if it isn't scrubbed here it reaches CloudWatch in plaintext.
function getHeadersObject(headers: Headers | Record<string, string> | undefined): Record<string, string> {
if (!headers) return {};
if (headers instanceof Headers) {
const result: Record<string, string> = {};
headers.forEach((value, key) => {
result[key] = value;
});
return redactHeaders(result);
}
return redactHeaders(headers);
}
function getRequestBody(body: any): string | undefined {
return redactBody(body);
}
function prepareDefaultInit(init?: RequestInit): RequestInit {
const requestInit: RequestInit = {
headers: {
...mergeHeadersWithContext(init?.headers),
},
method: init && init.method ? init.method : 'GET',
};
if (init && init.headers) {
delete init.headers;
}
return merge({}, init, requestInit);
}
function prepareDefaultOptions<Schema extends StandardSchemaV1 = never>(options?: RequestOptions<Schema>): RequestOptions<Schema> {
return merge({}, DEFAULTS, options);
}
// Mollitia modules need a name unique within the process; these are labels that
// show up in logs, nothing more. This used to be `${prefix}-${faker.color.human()}-
// ${faker.animal.type()}`, which made @faker-js/faker — a test-data generator —
// a RUNTIME dependency of a published HTTP client, for two cosmetic words.
let moduleSequence = 0;
function generateRandomName(prefix: string): string {
return `${prefix}-${++moduleSequence}`;
}
function prepareCircuitModules<Schema extends StandardSchemaV1 = never>(options: RequestOptions<Schema>, init: RequestInit): Module[] {
const modules: Module[] = [];
const logger = options.logger || contextLoggerToUse;
const retryEligible = isRetryEligible(init, options.retry);
const onRejection = options.retry?.onRejection;
// No Retry module at all for an ineligible request: one attempt, and the
// underlying error surfaces as-is rather than as a RetryError.
//
// There is deliberately no mollitia `Timeout` module here either. It only
// RACED the attempt — the losing fetch kept running, so a timed-out POST
// stayed in flight server-side while the retry sent it again. The timeout
// now lives in `doGlobalFetch`, where it can abort the request itself.
if (options.retry && retryEligible) {
modules.push(
new Retry({
name: generateRandomName('smooai-fetch-retry'),
logger: logger,
attempts: options.retry.attempts,
interval: options.retry.initialIntervalMs,
mode: options.retry.mode,
factor: options.retry.factor,
jitterAdjustment: options.retry.jitterAdjustment,
// A request the CALLER aborted is finished, not failed — never re-send it.
onRejection: (error, attempt) => (init.signal?.aborted ? false : onRejection ? onRejection(error, attempt) : true),
}),
);
}
return modules;
}
function prepareFetchContainerModules(options: RequestOptions, containerOptions?: FetchContainerOptions): Module[] {
const modules: Module[] = [];
const logger = options.logger || contextLoggerToUse;
if (containerOptions) {
if (containerOptions.rateLimit) {
const retryOptions = containerOptions.rateLimit.retry || DEFAULT_RATE_LIMIT_RETRY_OPTIONS;
modules.push(
new Retry({
name: generateRandomName('smooai-fetch-rate-limit-retry'),
logger: logger,
attempts: retryOptions.attempts,
interval: retryOptions.initialIntervalMs,
mode: retryOptions.mode,
factor: retryOptions.factor,
jitterAdjustment: retryOptions.jitterAdjustment,
onRejection: retryOptions.onRejection,
}),
);
modules.push(
new Ratelimit({
name: generateRandomName('smooai-fetch-rate-limit'),
logger: logger,
limitPeriod: containerOptions.rateLimit.limitPeriodMs,
limitForPeriod: containerOptions.rateLimit.limitForPeriod,
}),
);
}
if (containerOptions.circuitBreaker) {
modules.push(
new SlidingCountBreaker({
name: generateRandomName('smooai-fetch-circuit-breaker'),
logger: logger,
state: containerOptions.circuitBreaker.state,
failureRateThreshold: containerOptions.circuitBreaker.failureRateThreshold,
slowCallRateThreshold: containerOptions.circuitBreaker.slowCallRateThreshold,
slowCallDurationThreshold: containerOptions.circuitBreaker.slowCallDurationThresholdMs,
permittedNumberOfCallsInHalfOpenState: containerOptions.circuitBreaker.permittedNumberOfCallsInHalfOpenState,
halfOpenStateMaxDelay: containerOptions.circuitBreaker.halfOpenStateMaxDelayMs,
slidingWindowSize: containerOptions.circuitBreaker.slidingWindowSize,
minimumNumberOfCalls: containerOptions.circuitBreaker.minimumNumberOfCalls,
openStateDelay: containerOptions.circuitBreaker.openStateDelayMs,
onError: containerOptions.circuitBreaker.onError,
}),
);
}
}
return modules;
}
/**
* Cached, best-effort handle on `@opentelemetry/api`.
*
* The package is an OPTIONAL peer dependency: an OSS HTTP client must not force
* OpenTelemetry on anyone. When it is absent the import rejects, this resolves
* `null`, and injection becomes a no-op — no crash, no behaviour change.
*/
let otelApi: Promise<typeof import('@opentelemetry/api') | null> | undefined;
/**
* Inject W3C trace context (`traceparent`/`tracestate`) into an outbound request.
*
* # Why this exists
*
* api-prime already EXTRACTS `traceparent` on ingress, but nothing on the
* platform ever injected it on egress — so every service-to-service call began a
* brand new root trace. Measured on 2026-08-14 over a three-hour window: 34,961
* traces touched exactly one service, and 4 touched two.
*
* This is the client, which is the correct place for propagation: services are
* already required to use `@smooai/fetch` over raw HTTP, so wiring it once here
* covers the fleet. Mirrors `rust/fetch/src/client.rs::inject_trace_context`.
*
* # Three guards, each for a reason
*
* 1. **Optional dependency.** No `@opentelemetry/api` installed → no-op.
* 2. **Valid span contexts only.** No registered SDK / no active span yields
* INVALID_SPAN_CONTEXT (all-zero ids). Injecting that writes a malformed
* `traceparent` a downstream service will either reject or, worse, adopt —
* poisoning its trace. The sibling logger shipped exactly this bug, where
* all-zero ids overwrote a real correlation id.
* 3. **Caller wins.** An explicitly-set `traceparent` is left alone. A client
* that silently rewrites an intentional header is worse than one that does
* nothing.
*/
async function injectTraceContext(init: RequestInit): Promise<void> {
otelApi ??= import('@opentelemetry/api').catch(() => null);
const otel = await otelApi;
if (!otel) return;
const activeContext = otel.context.active();
const spanContext = otel.trace.getSpanContext(activeContext);
if (!spanContext || !otel.isSpanContextValid(spanContext)) return;
// Copy rather than mutate: the caller's `init` is reused across retries, and a
// header we wrote ourselves must never be mistaken for the caller's on the next
// attempt — that would pin every retry to the traceparent of the first one.
const headers = new Headers(init.headers as HeadersInit | undefined);
if (headers.has('traceparent')) return;
const carrier: Record<string, string> = {};
otel.propagation.inject(activeContext, carrier);
if (Object.keys(carrier).length === 0) return;
for (const [key, value] of Object.entries(carrier)) {
headers.set(key, value);
}
init.headers = headers;
}
async function doGlobalFetch<Schema extends StandardSchemaV1 = never>(
url: RequestInfo,
init?: RequestInit,
options?: RequestOptions<Schema>,
): Promise<ResponseWithBody<ResponseType<Schema>>> {
// Defaults FIRST, caller's init LAST — `merge` lets later sources win, so
// the old order (`merge({}, init, { redirect: 'follow' })`) silently
// overwrote an explicit `redirect: 'manual' | 'error'` with 'follow'.
//
// Following redirects is the right default, but it must be a default and
// not a mandate: a caller that resolved a hostname and checked it against
// an SSRF allowlist has that guard defeated by a 302 to an internal
// address, and RFC 8461 forbids following them at all when fetching an
// MTA-STS policy.
const useInit: RequestInit = merge({}, { redirect: 'follow' } as RequestInit, init);
// Stringify JSON body if needed
if ((useInit?.headers as Record<string, string>)?.['Content-Type'] === 'application/json' && typeof useInit.body === 'object') {
useInit.body = JSON.stringify(useInit.body);
}
// Continue the caller's trace across the hop. This is the single-request site —
// the innermost place that performs exactly one HTTP call — so every retry and
// every re-issued request carries a CURRENT traceparent instead of a stale one.
await injectTraceContext(useInit);
// Bound the connect phase via an undici dispatcher (Node only). Only attach
// when explicitly requested so the default path stays byte-identical.
if (options?.connectTimeoutMs) {
const dispatcher = await getConnectTimeoutDispatcher(options.connectTimeoutMs);
if (dispatcher) {
(useInit as Record<string, unknown>).dispatcher = dispatcher;
}
}
// Per-attempt timeout that ABORTS the request. The caller's own signal still
// works: either one aborting cancels the fetch.
const timeoutMs = options?.timeout?.timeoutMs;
const timeoutController = new AbortController();
let timer: ReturnType<typeof setTimeout> | undefined;
if (timeoutMs !== undefined) {
timer = setTimeout(() => timeoutController.abort(new TimeoutError()), timeoutMs);
useInit.signal = init?.signal ? anySignal([init.signal, timeoutController.signal]) : timeoutController.signal;
}
try {
const attempt = sendAndRead<Schema>(url, useInit, options);
if (timeoutMs === undefined) return await attempt;
// Race as well as abort: a fetch implementation that ignores `signal` (a
// polyfill, a test double) must still time out on schedule. With a
// compliant fetch the abort has already torn the request down.
return await Promise.race([
attempt,
new Promise<never>((_, reject) => {
timeoutController.signal.addEventListener('abort', () => reject(timeoutController.signal.reason), { once: true });
}),
]);
} catch (error) {
// undici rejects with the abort reason, a browser with an AbortError —
// normalise both to the TimeoutError the retry policy and callers expect.
if (timeoutController.signal.aborted && !init?.signal?.aborted) {
throw timeoutController.signal.reason instanceof TimeoutError ? timeoutController.signal.reason : new TimeoutError();
}
throw error;
} finally {
clearTimeout(timer);
}
}
/** `AbortSignal.any` where available (Node 20+, modern browsers), else a manual fan-in. */
function anySignal(signals: AbortSignal[]): AbortSignal {
const any = (AbortSignal as unknown as { any?: (signals: AbortSignal[]) => AbortSignal }).any;
if (any) return any(signals);
const controller = new AbortController();
for (const signal of signals) {
if (signal.aborted) {
controller.abort(signal.reason);
break;
}
signal.addEventListener('abort', () => controller.abort(signal.reason), { once: true });
}
return controller.signal;
}
async function sendAndRead<Schema extends StandardSchemaV1 = never>(
url: RequestInfo,
useInit: RequestInit,
options?: RequestOptions<Schema>,
): Promise<ResponseWithBody<ResponseType<Schema>>> {
const response = await globalFetch()(url, useInit);
let isJson = false;
let data: ResponseType<Schema> | undefined;
let dataString: string = '';
let read = false;
const responseClone = response.clone();
if (responseClone.headers?.has('Content-Type') && responseClone.headers?.get('Content-Type')?.includes('application/json')) {
dataString = await responseClone.text();
read = true;
try {
const parsedData = JSON.parse(dataString);
if (responseClone.ok && options?.schema) {
data = (await handleSchemaValidation(options.schema, parsedData)) as Schema extends StandardSchemaV1
? StandardSchemaV1.InferOutput<Schema>
: any;
} else {
data = parsedData as ResponseType<Schema>;
}
isJson = true;
} catch (error) {
if (error instanceof HumanReadableSchemaError) {
throw error;
}
isJson = false;
}
} else {
isJson = false;
}
const responseWithBody = response as any;
responseWithBody.isJson = isJson;
responseWithBody.dataString = dataString;
responseWithBody.data = data;
// A 3xx under `redirect: 'manual'` is the ANSWER, not a failure — the
// caller asked to see the redirect rather than follow it. It is neither
// `ok` nor `redirected` (nothing was followed), so without this it would
// throw and the option would be useless even once it is honoured.
const isManualRedirect = useInit.redirect === 'manual' && responseClone.status >= 300 && responseClone.status < 400;
if (responseClone.ok || responseClone.redirected || isManualRedirect) {
return responseWithBody;
} else {
if (!read) {
responseWithBody.dataString = await responseClone.text();
}
throw new HTTPResponseError<ResponseType<Schema>>(responseWithBody);
}
}
async function doFetch<Schema extends StandardSchemaV1 = never>(
url: RequestInfo,
init: RequestInit,
options: RequestOptions<Schema>,
): Promise<ResponseWithBody<ResponseType<Schema>>> {
const logger = options.logger || contextLoggerToUse;
// Apply pre-request hook if present (supports async hooks)
let modifiedInit = init;
if (options.hooks?.preRequest) {
const hookResult = await options.hooks.preRequest(url.toString(), init);
if (hookResult) {
modifiedInit = hookResult[1];
url = hookResult[0];
}
}
// Built AFTER the pre-request hook: retry eligibility depends on the final
// method and headers, and a hook may be what adds the Idempotency-Key.
const retryEligible = isRetryEligible(modifiedInit, options.retry);
const circuit = new Circuit({
name: 'node-fetch-circuit',
func: doGlobalFetch,
options: {
modules: prepareCircuitModules(options, modifiedInit),
},
});
const urlObj = new URL(url.toString());
const safeUrl = redactUrl(url.toString());
logger.debug(`Sending HTTP request "${modifiedInit.method} ${safeUrl}"`, {
[ContextKey.Http]: {
[ContextKeyHttp.Request]: {
[ContextKeyHttpRequest.Method]: modifiedInit.method,
[ContextKeyHttpRequest.Host]: urlObj.host,
[ContextKeyHttpRequest.Path]: urlObj.pathname,
[ContextKeyHttpRequest.QueryString]: redactQueryString(urlObj.search),
[ContextKeyHttpRequest.Headers]: getHeadersObject(modifiedInit.headers as Headers),
[ContextKeyHttpRequest.Body]: getRequestBody(modifiedInit.body),
},
},
});
let response: ResponseWithBody<ResponseType<Schema>>;
try {
response = await circuit.execute(url, modifiedInit, options);
// Apply post-response success hook if present
if (options.hooks?.postResponseSuccess) {
const hookResult = options.hooks.postResponseSuccess(url.toString(), init, response);
if (hookResult) {
response = hookResult;
}
}
return response;
} catch (error) {
// Apply post-response error hook if present
if (options.hooks?.postResponseError) {
const hookResult = options.hooks.postResponseError(
url.toString(),
init,
error as Error,
error instanceof HTTPResponseError ? error.response : undefined,
);
if (hookResult) {
throw hookResult;
}
}
if (error instanceof TimeoutError) {
logger.error(error, `HTTP request "${modifiedInit.method} ${safeUrl}" timed out (${error.name}) after ${options.timeout!.timeoutMs} ms`, {
[ContextKey.Http]: {
[ContextKeyHttp.Request]: {
[ContextKeyHttpRequest.Method]: modifiedInit.method,
[ContextKeyHttpRequest.Host]: urlObj.host,
[ContextKeyHttpRequest.Path]: urlObj.pathname,
[ContextKeyHttpRequest.QueryString]: redactQueryString(urlObj.search),
[ContextKeyHttpRequest.Headers]: getHeadersObject(modifiedInit.headers as Headers),
[ContextKeyHttpRequest.Body]: getRequestBody(modifiedInit.body),
},
},
});
} else if (options.retry && retryEligible && error instanceof HTTPResponseError) {
if (options.retry.onRejection && options.retry.onRejection(error, 1)) {
logger.error(error, `HTTP request "${modifiedInit.method} ${safeUrl}" retries failed after ${options.retry.attempts} retries`, {
[ContextKey.Http]: {
[ContextKeyHttp.Request]: {
[ContextKeyHttpRequest.Method]: modifiedInit.method,
[ContextKeyHttpRequest.Host]: urlObj.host,
[ContextKeyHttpRequest.Path]: urlObj.pathname,
[ContextKeyHttpRequest.QueryString]: redactQueryString(urlObj.search),
[ContextKeyHttpRequest.Headers]: getHeadersObject(modifiedInit.headers as Headers),
[ContextKeyHttpRequest.Body]: getRequestBody(modifiedInit.body),
},
[ContextKeyHttp.Response]: {
[ContextKeyHttpResponse.StatusCode]: error.response.status,
[ContextKeyHttpResponse.Headers]: getHeadersObject(error.response.headers),
[ContextKeyHttpResponse.Body]: redactBody(error.response.dataString),
},
},
});
throw new RetryError<ResponseType<Schema>>(error.response);
}
}
throw error;
}
}
export type RequestInitWithOptions<Schema extends StandardSchemaV1 = never> = RequestInit & {
options?: RequestOptions<Schema>;
};
// Overload signatures
export default async function fetch(url: RequestInfo, init?: RequestInitWithOptions<never>): Promise<ResponseWithBody<any>>;
export default async function fetch<Schema extends StandardSchemaV1>(
url: RequestInfo,
init?: RequestInitWithOptions<Schema>,
): Promise<ResponseWithBody<ResponseType<Schema>>>;
// Implementation
export default async function fetch<Schema extends StandardSchemaV1 = never>(
url: RequestInfo,
init?: RequestInitWithOptions<Schema>,
): Promise<ResponseWithBody<ResponseType<Schema>>> {
const { options, ...requestInit } = init || {};
return doFetch<Schema>(url, prepareDefaultInit(requestInit), prepareDefaultOptions(options));
}
/**
* Example usage:
*
* const fetch = generateFetchWithOptions({
containerOptions: {
rateLimit: {
name: 'finch-node-fetch-rate-limit',
limitForPeriod: 2,
limitPeriodMs: 62 * 1000,
retry: DEFAULT_RATE_LIMIT_RETRY_OPTIONS,
},
},
requestOptions: {
logger,
timeout: {
name: 'finch-node-fetch-timeout',
timeoutMs: 60 * 1000,
},
retry: DEFAULT_RETRY_OPTIONS,
},
});
* @param options
* @returns
*/
function generateFetchWithOptions(options: { init?: RequestInit; requestOptions?: RequestOptions<never>; containerOptions?: FetchContainerOptions }): {
(url: RequestInfo, init?: RequestInitWithOptions<never>): Promise<ResponseWithBody<any>>;
<Schema extends StandardSchemaV1>(url: RequestInfo, init?: RequestInitWithOptions<Schema>): Promise<ResponseWithBody<ResponseType<Schema>>>;
} {
const _init = prepareDefaultInit(options.init);
const _requestOptions = prepareDefaultOptions(options.requestOptions);
const circuit = new Circuit({
name: 'node-fetch-container-circuit',
options: {
modules: prepareFetchContainerModules(_requestOptions, options.containerOptions),
},
});
return <Schema extends StandardSchemaV1 = never>(
url: RequestInfo,
init?: RequestInitWithOptions<Schema>,
): Promise<ResponseWithBody<ResponseType<Schema>>> => {
circuit.fn(doFetch);
const { options: requestOptions, ...requestInit } = init || {};
const __init = prepareDefaultInit(merge({}, _init, requestInit));
const __requestOptions = prepareDefaultOptions(merge({}, _requestOptions, requestOptions));
const logger = __requestOptions.logger || contextLoggerToUse;
const urlObj = new URL(url.toString());
const safeUrl = redactUrl(url.toString());
const headers = getHeadersObject(__init.headers as Headers);
const requestBody = getRequestBody(__init.body);
try {
return circuit.execute(url, prepareDefaultInit(__init), prepareDefaultOptions(__requestOptions));
} catch (error) {
if (error instanceof RatelimitError) {
logger.error(
error,
`HTTP request "${__init.method} ${safeUrl}" rate limited (${error.name}) - more than ${
options.containerOptions!.rateLimit?.limitForPeriod