Repository navigation
Expand file tree
/
Copy pathclient.ts
More file actions
696 lines (618 loc) · 22.3 KB
/
Copy pathclient.ts
File metadata and controls
696 lines (618 loc) · 22.3 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
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
/**
* HttpClient — resilient HTTP client with timeout, retry, rate-limit handling,
* and request/response interceptors.
*
* Provides two APIs:
* - Throw-style: `client.get<T>(url)` — throws HttpClientError on failure
* - Result-style: `client.getResult<T>(url)` — returns Result<HttpResponse<T>, HttpClientError>
* for @eserstack/functions do-notation compatibility
*
* @module
*/
import * as results from "@eserstack/primitives/results";
import type * as types from "./types.ts";
import * as errors from "./errors.ts";
import * as interceptors from "./interceptors.ts";
import * as goClientModule from "./go-client.ts";
import * as goTransport from "./go-transport.ts";
import * as retryPolicy from "./retry-policy.ts";
// =============================================================================
// Defaults
// =============================================================================
const DEFAULT_TIMEOUT = 30_000;
const defaultDelayFn = (ms: number): Promise<void> =>
new Promise((resolve) => setTimeout(resolve, ms));
// =============================================================================
// Internal Helpers
// =============================================================================
const resolveUrl = (baseUrl: string | undefined, path: string): string => {
if (path.startsWith("http://") || path.startsWith("https://")) {
return path;
}
if (baseUrl !== undefined && baseUrl !== "") {
const base = baseUrl.replace(/\/$/, "");
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
return `${base}${normalizedPath}`;
}
return path;
};
export const parseRetryAfter = (header: string | null): number | null => {
const ms = parseRetryAfterMs(header);
return ms !== null ? ms / 1_000 : null;
};
const parseRetryAfterMs = (header: string | null): number | null => {
if (header === null) return null;
const seconds = Number(header);
if (!Number.isNaN(seconds) && seconds >= 0) {
return Math.round(seconds * 1_000);
}
const date = new Date(header);
if (!Number.isNaN(date.getTime())) {
return Math.max(0, date.getTime() - Date.now());
}
return null;
};
export const extractRateLimitInfo = (
hdrs: Headers,
): types.RateLimitInfo | undefined => {
const remaining =
hdrs.get("X-RateLimit-Remaining") ?? hdrs.get("x-rate-limit-remaining");
const limit = hdrs.get("X-RateLimit-Limit") ?? hdrs.get("x-rate-limit-limit");
const reset = hdrs.get("X-RateLimit-Reset") ?? hdrs.get("x-rate-limit-reset");
const retryAfterHeader = hdrs.get("Retry-After");
if (
remaining === null &&
limit === null &&
reset === null &&
retryAfterHeader === null
) {
return undefined;
}
const retryAfterMs = parseRetryAfterMs(retryAfterHeader);
return {
...(remaining !== null && { remaining: Number(remaining) }),
...(limit !== null && { limit: Number(limit) }),
...(reset !== null && { resetAt: Number(reset) }),
...(retryAfterMs !== null && { retryAfterSeconds: retryAfterMs / 1_000 }),
};
};
const extractErrorBody = async (raw: Response): Promise<unknown> => {
try {
return await raw.clone().json();
} catch {
return await raw
.clone()
.text()
.catch(() => undefined);
}
};
const errorMessageFromBody = (body: unknown): string | null => {
if (typeof body === "object" && body !== null) {
const b = body as Record<string, unknown>;
const msg = b["error"] ?? b["message"] ?? b["detail"] ?? b["title"];
if (msg !== undefined) return String(msg);
}
return null;
};
// =============================================================================
// HttpClient
// =============================================================================
export class HttpClient {
private readonly config: types.HttpClientConfig;
#goClientInit: Promise<goClientModule.GoHttpClient> | null = null;
constructor(config?: types.HttpClientConfig) {
if (config?.transport === "native" && config.fetchFn !== undefined) {
throw new TypeError(
'HttpClient: fetchFn and transport "native" exclude each other; pass one of them',
);
}
this.config = config ?? {};
}
/** Return a new client with merged configuration (immutable). */
withDefaults(overrides: Partial<types.HttpClientConfig>): HttpClient {
return new HttpClient({
...this.config,
...overrides,
headers: {
...(this.config.headers ?? {}),
...(overrides.headers ?? {}),
},
});
}
// ---------------------------------------------------------------------------
// Throw-style API
// ---------------------------------------------------------------------------
request<T>(
method: types.HttpMethod,
url: string,
options?: types.RequestOptions,
): Promise<types.HttpResponse<T>> {
return this._execute<T>(method, url, options);
}
get<T>(
url: string,
options?: types.RequestOptions,
): Promise<types.HttpResponse<T>> {
return this._execute<T>("GET", url, options);
}
post<T>(
url: string,
options?: types.RequestOptions,
): Promise<types.HttpResponse<T>> {
return this._execute<T>("POST", url, options);
}
put<T>(
url: string,
options?: types.RequestOptions,
): Promise<types.HttpResponse<T>> {
return this._execute<T>("PUT", url, options);
}
patch<T>(
url: string,
options?: types.RequestOptions,
): Promise<types.HttpResponse<T>> {
return this._execute<T>("PATCH", url, options);
}
delete<T>(
url: string,
options?: types.RequestOptions,
): Promise<types.HttpResponse<T>> {
return this._execute<T>("DELETE", url, options);
}
// ---------------------------------------------------------------------------
// Streaming throw-style API
// ---------------------------------------------------------------------------
/**
* Make a request and return the response body as a ReadableStream.
* Throws HttpClientError on non-2xx status (after retries).
*
* Key differences from `request<T>()`:
* - Body is NOT consumed or parsed — caller owns the stream lifecycle.
* - Retry applies to connection establishment only, not stream reading.
* - Timeout applies to the initial connection, not stream duration; on
* transport "native" the Go client's timeout covers the whole stream.
* - Response interceptors do NOT run (they require a parsed `data` field).
*/
requestStream(
method: types.HttpMethod,
url: string,
options?: types.RequestOptions,
): Promise<types.HttpStreamResponse> {
return this._executeStream(method, url, options);
}
/**
* POST a request and return the response body as a ReadableStream.
* The only streaming convenience method provided — it is the only HTTP verb
* used for streaming in practice (SSE, NDJSON).
*/
postStream(
url: string,
options?: types.RequestOptions,
): Promise<types.HttpStreamResponse> {
return this.requestStream("POST", url, options);
}
// ---------------------------------------------------------------------------
// Result-style API (@eserstack/functions do-notation compatibility)
// ---------------------------------------------------------------------------
requestResult<T>(
method: types.HttpMethod,
url: string,
options?: types.RequestOptions,
): Promise<results.Result<types.HttpResponse<T>, errors.HttpClientError>> {
return results.fromPromise(
this._execute<T>(method, url, options),
toHttpClientError,
);
}
getResult<T>(
url: string,
options?: types.RequestOptions,
): Promise<results.Result<types.HttpResponse<T>, errors.HttpClientError>> {
return results.fromPromise(
this._execute<T>("GET", url, options),
toHttpClientError,
);
}
postResult<T>(
url: string,
options?: types.RequestOptions,
): Promise<results.Result<types.HttpResponse<T>, errors.HttpClientError>> {
return results.fromPromise(
this._execute<T>("POST", url, options),
toHttpClientError,
);
}
putResult<T>(
url: string,
options?: types.RequestOptions,
): Promise<results.Result<types.HttpResponse<T>, errors.HttpClientError>> {
return results.fromPromise(
this._execute<T>("PUT", url, options),
toHttpClientError,
);
}
patchResult<T>(
url: string,
options?: types.RequestOptions,
): Promise<results.Result<types.HttpResponse<T>, errors.HttpClientError>> {
return results.fromPromise(
this._execute<T>("PATCH", url, options),
toHttpClientError,
);
}
deleteResult<T>(
url: string,
options?: types.RequestOptions,
): Promise<results.Result<types.HttpResponse<T>, errors.HttpClientError>> {
return results.fromPromise(
this._execute<T>("DELETE", url, options),
toHttpClientError,
);
}
// ---------------------------------------------------------------------------
// Streaming Result-style API
// ---------------------------------------------------------------------------
requestStreamResult(
method: types.HttpMethod,
url: string,
options?: types.RequestOptions,
): Promise<results.Result<types.HttpStreamResponse, errors.HttpClientError>> {
return results.fromPromise(
this._executeStream(method, url, options),
toHttpClientError,
);
}
postStreamResult(
url: string,
options?: types.RequestOptions,
): Promise<results.Result<types.HttpStreamResponse, errors.HttpClientError>> {
return results.fromPromise(
this._executeStream("POST", url, options),
toHttpClientError,
);
}
// ---------------------------------------------------------------------------
// Core implementation
// ---------------------------------------------------------------------------
/**
* Shared retry/timeout/error-handling core.
* Handles URL building, header merging, body serialization, retry loop,
* timeout via AbortSignal, rate-limit parsing, and error classification.
*
* The `onSuccess` callback is invoked once a 2xx response is received.
* It receives the raw Response, the sent Request, the retry count, and any
* extracted rate-limit info. Each public method variant supplies its own
* onSuccess: _execute parses JSON and runs response interceptors;
* _executeStream returns the body stream directly.
*
* This is the single source of truth for retry/timeout behavior — both
* _execute and _executeStream delegate entirely to this method, on the
* fetch and the native transport alike. The loop stays here because it runs
* the request interceptors before every attempt; the decisions come from
* the retry policy in Go (retry-policy.ts). `stream` tells the native
* transport to hand the body over unread.
*/
private async _executeFetch<T>(
method: types.HttpMethod,
url: string,
options: types.RequestOptions | undefined,
stream: boolean,
onSuccess: (
raw: Response,
sentRequest: Request,
retries: number,
rateLimit: types.RateLimitInfo | undefined,
) => Promise<T>,
): Promise<T> {
const delayFn = this.config._delayFn ?? defaultDelayFn;
// Build URL
const resolvedUrl = resolveUrl(this.config.baseUrl, url);
const fullUrl = new URL(resolvedUrl);
if (options?.params !== undefined) {
for (const [key, value] of Object.entries(options.params)) {
fullUrl.searchParams.set(key, value);
}
}
// Merge headers
const headers: Record<string, string> = {
...(this.config.headers ?? {}),
...(options?.headers ?? {}),
};
// Handle body
let body: BodyInit | undefined;
const bodyValue = options?.body;
if (bodyValue !== undefined) {
if (
typeof bodyValue === "string" ||
bodyValue instanceof ArrayBuffer ||
ArrayBuffer.isView(bodyValue) ||
bodyValue instanceof Blob ||
bodyValue instanceof FormData ||
bodyValue instanceof URLSearchParams ||
bodyValue instanceof ReadableStream
) {
body = bodyValue as BodyInit;
} else if (typeof bodyValue === "object" && bodyValue !== null) {
body = JSON.stringify(bodyValue);
if (headers["Content-Type"] === undefined) {
headers["Content-Type"] = "application/json";
}
}
}
if (
this.config.transport === "native" &&
body !== undefined &&
typeof body !== "string" &&
!(body instanceof URLSearchParams)
) {
throw new errors.HttpClientError(
`${method} request: transport "native" sends text bodies only (a string, URLSearchParams, or an object sent as JSON); send binary, form and stream bodies with the default fetch transport`,
);
}
// The retry policy lives in Go: it answers how many attempts this request
// gets and, after each failed one, whether and how long to wait. A stream
// body is consumed by the first attempt and cannot be sent again, so a
// request with one gets one attempt.
const replayable = !(body instanceof ReadableStream);
const plan = retryPolicy.resolveRetryPlan(
this.config.retry,
options?.retry,
!replayable,
);
const timeout = options?.timeout ?? this.config.timeout ?? DEFAULT_TIMEOUT;
const requestInterceptors = this.config.interceptors?.request ?? [];
const fetchFn = await this.#resolveFetch(stream);
let retries = 0;
for (let attempt = 0; attempt < plan.maxAttempts; attempt++) {
if (attempt > 0) {
retries++;
}
let raw: Response;
let sentRequest: Request;
try {
// Build combined abort signal
const userSignal = options?.signal;
const timeoutSignal = AbortSignal.timeout(timeout);
const signal =
userSignal !== undefined
? AbortSignal.any([timeoutSignal, userSignal])
: timeoutSignal;
const init: RequestInit & { duplex?: "half" } = {
method,
headers,
body,
signal,
// Node's fetch requires duplex for a stream body; browsers
// accept it.
...(!replayable && { duplex: "half" }),
};
const initRequest = new Request(fullUrl.toString(), init);
// Attempts are sequential: a retry starts only after this one fails.
// oxlint-disable-next-line no-await-in-loop
sentRequest = await interceptors.applyRequestInterceptors(
initRequest,
requestInterceptors,
);
// Attempts are sequential: a retry starts only after this one fails.
// oxlint-disable-next-line no-await-in-loop
raw = await fetchFn(sentRequest);
} catch (err) {
const e = err instanceof Error ? err : new Error(String(err));
const classified = errors.classifyError(e);
// Never retry timeout or user abort
if (
classified instanceof errors.HttpTimeoutError ||
classified instanceof errors.HttpAbortError
) {
throw classified;
}
const decision = retryPolicy.nextRetry(plan, attempt, 0, null);
if (!decision.retry) {
throw classified;
}
// The backoff must elapse before the next attempt starts.
// oxlint-disable-next-line no-await-in-loop
await delayFn(decision.delayMs);
continue;
}
// Successful connection — check HTTP status
const rateLimit = extractRateLimitInfo(raw.headers);
if (!raw.ok) {
// The error body decides whether and how this attempt is retried.
// oxlint-disable-next-line no-await-in-loop
const errorBody = await extractErrorBody(raw);
const statusMsg =
errorMessageFromBody(errorBody) ?? `HTTP ${raw.status}`;
const retryAfterMs =
rateLimit !== undefined
? parseRetryAfterMs(raw.headers.get("Retry-After"))
: null;
const httpError =
raw.status === 429
? new errors.HttpRateLimitError(statusMsg, {
statusCode: raw.status,
response: raw,
body: errorBody,
...(retryAfterMs !== null && {
retryAfter: retryAfterMs / 1_000,
}),
})
: new errors.HttpResponseError(statusMsg, {
statusCode: raw.status,
response: raw,
body: errorBody,
});
const decision = retryPolicy.nextRetry(
plan,
attempt,
raw.status,
retryAfterMs,
);
if (decision.retry) {
// The backoff, or a 429's Retry-After, must elapse before the next
// attempt starts.
// oxlint-disable-next-line no-await-in-loop
await delayFn(decision.delayMs);
continue;
}
throw httpError;
}
// 2xx: delegate to the variant-specific success handler. The await
// ends the loop; it returns on the first successful attempt.
// oxlint-disable-next-line no-await-in-loop
return await onSuccess(raw, sentRequest, retries, rateLimit);
}
// Every failed attempt either retries or throws, so the loop only ends
// here when the plan allows no attempt at all.
throw new errors.HttpClientError(
`Request failed after ${plan.maxAttempts} attempt(s)`,
);
}
/** JSON-parsing variant — parses body, builds HttpResponse<T>, runs response interceptors. */
private _execute<T>(
method: types.HttpMethod,
url: string,
options?: types.RequestOptions,
): Promise<types.HttpResponse<T>> {
const responseInterceptors = this.config.interceptors?.response ?? [];
return this._executeFetch<types.HttpResponse<T>>(
method,
url,
options,
false,
async (raw, sentRequest, retries, rateLimit) => {
// Parse response body
let data: T;
if (
raw.status === 204 ||
raw.status === 304 ||
raw.headers.get("Content-Length") === "0"
) {
data = undefined as unknown as T;
} else {
const contentType = raw.headers.get("Content-Type") ?? "";
if (contentType.includes("application/json")) {
data = (await raw.json()) as T;
} else {
const text = await raw.text();
try {
data = JSON.parse(text) as T;
} catch {
data = text as unknown as T;
}
}
}
let response: types.HttpResponse<T> = {
data,
status: raw.status,
statusText: raw.statusText,
headers: raw.headers,
request: sentRequest,
raw,
retries,
...(rateLimit !== undefined && { rateLimit }),
};
response = await interceptors.applyResponseInterceptors(
response,
responseInterceptors,
);
return response;
},
);
}
/**
* Streaming variant — returns body as ReadableStream without consuming it.
* Response interceptors do NOT run (they require a parsed `data` field).
* Timeout applies to connection establishment only, not stream reading.
*/
private _executeStream(
method: types.HttpMethod,
url: string,
options?: types.RequestOptions,
): Promise<types.HttpStreamResponse> {
return this._executeFetch<types.HttpStreamResponse>(
method,
url,
options,
true,
(raw, sentRequest, retries, rateLimit) => {
if (raw.body === null) {
return Promise.reject(
new errors.HttpNetworkError(
"Response body is null — server sent no body for a streaming request",
),
);
}
return Promise.resolve({
body: raw.body,
status: raw.status,
statusText: raw.statusText,
headers: raw.headers,
request: sentRequest,
raw,
retries,
...(rateLimit !== undefined && { rateLimit }),
});
},
);
}
// ---------------------------------------------------------------------------
// Transport
// ---------------------------------------------------------------------------
/**
* The function that sends one Request: `fetchFn` or the global fetch, or the
* Go client for `transport: "native"`.
*/
async #resolveFetch(stream: boolean): Promise<goTransport.FetchLike> {
if (this.config.transport !== "native") {
return this.config.fetchFn ?? fetch;
}
return goTransport.createGoFetch(await this.#nativeClient(), stream);
}
/** Creates the Go client on first use and reuses it until `close()`. */
#nativeClient(): Promise<goClientModule.GoHttpClient> {
if (this.#goClientInit !== null) {
return this.#goClientInit;
}
const create =
this.config._createGoClient ?? goClientModule.createGoHttpClient;
// The Go client's own retries stay off: the retry policy of this client
// (retry-policy.ts) runs on both transports. The Go timeout bounds each
// blocking call.
const init = create({
timeoutMs: this.config.timeout ?? DEFAULT_TIMEOUT,
}).catch((cause: unknown) => {
throw new errors.HttpClientError(
'transport "native": the Go HTTP client could not be created; remove transport: "native" to send requests with fetch',
{ cause: cause instanceof Error ? cause : new Error(String(cause)) },
);
});
this.#goClientInit = init;
return init;
}
/** Release the Go HTTP client handle that `transport: "native"` opened. */
close(): void {
const init = this.#goClientInit;
this.#goClientInit = null;
init?.then(
(client) => client.close(),
() => {
// Creation failed, so there is no handle to release.
},
);
}
}
// =============================================================================
// Factory
// =============================================================================
export const createHttpClient = (config?: types.HttpClientConfig): HttpClient =>
new HttpClient(config);
// =============================================================================
// Internal Utilities
// =============================================================================
const toHttpClientError = (e: unknown): errors.HttpClientError => {
if (e instanceof errors.HttpClientError) return e;
const err = e instanceof Error ? e : new Error(String(e));
return new errors.HttpClientError(err.message, { cause: err });
};