@eserstack/httpclient 0.0.0-stage → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +13 -0
- package/README.md +303 -2
- package/dist/client.d.ts +85 -0
- package/dist/client.js +468 -0
- package/dist/errors.d.ts +70 -0
- package/dist/errors.js +132 -0
- package/dist/ffi-client.d.ts +9 -0
- package/dist/ffi-client.js +10 -0
- package/dist/go-client.d.ts +141 -0
- package/dist/go-client.js +177 -0
- package/dist/go-transport.d.ts +15 -0
- package/dist/go-transport.js +74 -0
- package/dist/h3-fetch.d.ts +32 -0
- package/dist/h3-fetch.js +38 -0
- package/dist/interceptors.d.ts +28 -0
- package/dist/interceptors.js +57 -0
- package/dist/mod.d.ts +11 -0
- package/dist/mod.js +10 -0
- package/dist/retry-policy.d.ts +32 -0
- package/dist/retry-policy.js +93 -0
- package/dist/types.d.ts +137 -0
- package/dist/types.js +2 -0
- package/package.json +52 -3
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* This package's view of the Go bridge.
|
|
4
|
+
*
|
|
5
|
+
* The loader itself lives in `@eserstack/ajan/ffi/client` and is shared with
|
|
6
|
+
* every other package, so the whole process opens the library once. This module
|
|
7
|
+
* stays as the import path the package's own code already uses.
|
|
8
|
+
*/
|
|
9
|
+
export { describeLoadFailure, ensureLib, getLib, getLoadError, requireLibSync, } from "@eserstack/ajan/ffi/client";
|
|
10
|
+
export { registerRequestSignal } from "@eserstack/ajan/ffi/request-signals";
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Go-backed HTTP client.
|
|
3
|
+
*
|
|
4
|
+
* Wraps the bridge's httpCreate, httpRequest and httpClose calls and its
|
|
5
|
+
* httpRequestStream stream for lightweight HTTP requests through the Go
|
|
6
|
+
* library (the native library, or the WASM fallback's host fetch).
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import type * as ffiTypes from "@eserstack/ajan/ffi";
|
|
11
|
+
/** The HTTP methods the Go bridge sends. */
|
|
12
|
+
export type GoHttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
|
|
13
|
+
/**
|
|
14
|
+
* Options for {@link createGoHttpClient}. The names are the JSON fields of the
|
|
15
|
+
* Go bridge's create request (`httpCreateRequest` in
|
|
16
|
+
* the ajan bridge), so every field reaches the Go client as is.
|
|
17
|
+
*/
|
|
18
|
+
export type GoHttpClientOptions = {
|
|
19
|
+
/** Prefix for request URLs that are not absolute. */
|
|
20
|
+
readonly baseUrl?: string;
|
|
21
|
+
/** Headers sent with every request; a request's own headers win. */
|
|
22
|
+
readonly headers?: Record<string, string>;
|
|
23
|
+
/**
|
|
24
|
+
* Time limit for one whole request, the response body included, in
|
|
25
|
+
* milliseconds. Defaults to 30 000.
|
|
26
|
+
*/
|
|
27
|
+
readonly timeoutMs?: number;
|
|
28
|
+
/** Retry failed requests inside the Go client. Off unless `true`. */
|
|
29
|
+
readonly retryEnabled?: boolean;
|
|
30
|
+
/** Attempts in total when `retryEnabled` is set. The Go default is 3. */
|
|
31
|
+
readonly maxAttempts?: number;
|
|
32
|
+
/** First retry delay in milliseconds. The Go default is 100. */
|
|
33
|
+
readonly initialIntervalMs?: number;
|
|
34
|
+
/** Upper bound for one retry delay in milliseconds. The Go default is 10 000. */
|
|
35
|
+
readonly maxIntervalMs?: number;
|
|
36
|
+
/** Stop calling a failing server for a while. Off unless `true`. */
|
|
37
|
+
readonly circuitBreakerEnabled?: boolean;
|
|
38
|
+
/** Failures in a row that open the circuit. The Go default is 5. */
|
|
39
|
+
readonly failureThreshold?: number;
|
|
40
|
+
/** Milliseconds an open circuit waits before it tries again. The Go default is 10 000. */
|
|
41
|
+
readonly resetTimeoutMs?: number;
|
|
42
|
+
};
|
|
43
|
+
/** One request for {@link GoHttpClient}; the fields match the Go bridge's request JSON. */
|
|
44
|
+
export type GoHttpRequest = {
|
|
45
|
+
readonly method: GoHttpMethod;
|
|
46
|
+
readonly url: string;
|
|
47
|
+
readonly headers?: Record<string, string>;
|
|
48
|
+
/** Text body; the Go bridge carries no binary bodies. */
|
|
49
|
+
readonly body?: string;
|
|
50
|
+
/**
|
|
51
|
+
* Largest response body read into memory, in bytes; the Go default is
|
|
52
|
+
* 32 MiB. A larger body fails the request. Use `requestStream` for more.
|
|
53
|
+
*/
|
|
54
|
+
readonly maxResponseBytes?: number;
|
|
55
|
+
/**
|
|
56
|
+
* Stops the request when it fires: the promise rejects with the signal's
|
|
57
|
+
* reason, and for `requestStream` the body errors. The native library runs
|
|
58
|
+
* each request in a worker thread; an aborted `request` frees the caller at
|
|
59
|
+
* once while its worker finishes the Go request (bounded by `timeoutMs`),
|
|
60
|
+
* and an aborted body read closes the stream, which ends the Go read. The
|
|
61
|
+
* WASM fallback aborts its fetch.
|
|
62
|
+
*/
|
|
63
|
+
readonly signal?: AbortSignal;
|
|
64
|
+
};
|
|
65
|
+
/** A complete response from {@link GoHttpClient.request}. */
|
|
66
|
+
export type GoHttpResponse = {
|
|
67
|
+
readonly status: number;
|
|
68
|
+
readonly statusText: string;
|
|
69
|
+
readonly headers: Record<string, string>;
|
|
70
|
+
readonly body: string;
|
|
71
|
+
readonly retries: number;
|
|
72
|
+
};
|
|
73
|
+
/** A response from {@link GoHttpClient.requestStream}, its body unread. */
|
|
74
|
+
export type GoHttpStreamResponse = {
|
|
75
|
+
readonly body: ReadableStream<Uint8Array>;
|
|
76
|
+
readonly status: number;
|
|
77
|
+
readonly statusText: string;
|
|
78
|
+
readonly headers: Record<string, string>;
|
|
79
|
+
};
|
|
80
|
+
export type GoHttpErrorPayload = {
|
|
81
|
+
error: string;
|
|
82
|
+
status?: number;
|
|
83
|
+
statusText?: string;
|
|
84
|
+
headers?: Record<string, string>;
|
|
85
|
+
body?: string;
|
|
86
|
+
retries?: number;
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Thrown by GoHttpClient when Go returns a structured HTTP error.
|
|
90
|
+
* Carries status, body, headers, and retry count for typed reconstruction.
|
|
91
|
+
*/
|
|
92
|
+
export declare class GoHttpError extends Error {
|
|
93
|
+
readonly status: number;
|
|
94
|
+
readonly statusText: string;
|
|
95
|
+
readonly headers: Record<string, string>;
|
|
96
|
+
readonly body: string;
|
|
97
|
+
readonly retries: number;
|
|
98
|
+
constructor(payload: GoHttpErrorPayload);
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* A handle on one Go HTTP client. An error status rejects with a
|
|
102
|
+
* {@link GoHttpError} that carries the status and body.
|
|
103
|
+
*/
|
|
104
|
+
export type GoHttpClient = {
|
|
105
|
+
/** Sends a request and reads its whole body. */
|
|
106
|
+
request(req: GoHttpRequest): Promise<GoHttpResponse>;
|
|
107
|
+
/** Sends a request and returns its body as a stream. */
|
|
108
|
+
requestStream(req: GoHttpRequest): Promise<GoHttpStreamResponse>;
|
|
109
|
+
/** Releases the handle; later calls fail. */
|
|
110
|
+
close(): void;
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* Creates a Go-backed HTTP client handle on a loaded library. Tests pass a
|
|
114
|
+
* library from `@eserstack/ajan/ffi/fake`; everything else goes through
|
|
115
|
+
* {@link createGoHttpClient}.
|
|
116
|
+
*
|
|
117
|
+
* @throws Error if the bridge refuses the client options.
|
|
118
|
+
* @throws RangeError if `timeoutMs` is not a positive number.
|
|
119
|
+
*/
|
|
120
|
+
export declare const createGoHttpClientFor: (lib: ffiTypes.FFILibrary, options?: GoHttpClientOptions) => GoHttpClient;
|
|
121
|
+
/**
|
|
122
|
+
* Creates a Go-backed HTTP client handle.
|
|
123
|
+
*
|
|
124
|
+
* With the native library, each request runs in a worker thread, so the
|
|
125
|
+
* JavaScript thread keeps running while it waits; `timeoutMs` bounds it. On
|
|
126
|
+
* the WASM fallback the requests wait on the runtime's fetch instead.
|
|
127
|
+
*
|
|
128
|
+
* @throws Error if the native library is unavailable.
|
|
129
|
+
* @throws RangeError if `timeoutMs` is not a positive number.
|
|
130
|
+
*
|
|
131
|
+
* @example
|
|
132
|
+
* ```typescript
|
|
133
|
+
* import * as goClient from "@eserstack/httpclient/go-client";
|
|
134
|
+
*
|
|
135
|
+
* const client = await goClient.createGoHttpClient({ timeoutMs: 10_000 });
|
|
136
|
+
* const resp = await client.request({ method: "GET", url: "https://example.com" });
|
|
137
|
+
* console.log(resp.status, resp.body);
|
|
138
|
+
* client.close();
|
|
139
|
+
* ```
|
|
140
|
+
*/
|
|
141
|
+
export declare const createGoHttpClient: (options?: GoHttpClientOptions) => Promise<GoHttpClient>;
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
import * as ffiClient from "./ffi-client.js";
|
|
3
|
+
/**
|
|
4
|
+
* Thrown by GoHttpClient when Go returns a structured HTTP error.
|
|
5
|
+
* Carries status, body, headers, and retry count for typed reconstruction.
|
|
6
|
+
*/
|
|
7
|
+
export class GoHttpError extends Error {
|
|
8
|
+
status;
|
|
9
|
+
statusText;
|
|
10
|
+
headers;
|
|
11
|
+
body;
|
|
12
|
+
retries;
|
|
13
|
+
constructor(payload) {
|
|
14
|
+
super(payload.error);
|
|
15
|
+
this.name = "GoHttpError";
|
|
16
|
+
this.status = payload.status ?? 0;
|
|
17
|
+
this.statusText = payload.statusText ?? "";
|
|
18
|
+
this.headers = payload.headers ?? {};
|
|
19
|
+
this.body = payload.body ?? "";
|
|
20
|
+
this.retries = payload.retries ?? 0;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
24
|
+
/**
|
|
25
|
+
* Runs a request for a client handle. With a signal, the request carries a
|
|
26
|
+
* requestId for the WASM fallback's fetch, and the call gets the signal, so
|
|
27
|
+
* the promise rejects with its reason when it fires; the signal is released
|
|
28
|
+
* once the call is answered.
|
|
29
|
+
*/
|
|
30
|
+
const withSignal = async (handle, req, send) => {
|
|
31
|
+
const { signal, ...wire } = req;
|
|
32
|
+
if (signal === undefined) {
|
|
33
|
+
return await send({ handle, ...wire }, {});
|
|
34
|
+
}
|
|
35
|
+
signal.throwIfAborted();
|
|
36
|
+
const registration = ffiClient.registerRequestSignal(signal);
|
|
37
|
+
try {
|
|
38
|
+
return await send({ handle, ...wire, requestId: registration.requestId }, { signal });
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
registration.release();
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
/** Decodes a base64 chunk of the bridge's stream reads. */
|
|
45
|
+
const decodeChunk = (chunk) => {
|
|
46
|
+
const binary = atob(chunk);
|
|
47
|
+
const bytes = new Uint8Array(binary.length);
|
|
48
|
+
for (let i = 0; i < binary.length; i++) {
|
|
49
|
+
bytes[i] = binary.charCodeAt(i);
|
|
50
|
+
}
|
|
51
|
+
return bytes;
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Throws the RangeError for a `timeoutMs` that would leave calls unbounded.
|
|
55
|
+
*/
|
|
56
|
+
const checkedTimeout = (options) => {
|
|
57
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
58
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
59
|
+
// The Go client treats 0 as no limit at all, and each call holds a
|
|
60
|
+
// worker thread until it returns, so an unbounded client is never created.
|
|
61
|
+
throw new RangeError(`createGoHttpClient: timeoutMs ${timeoutMs} is not a positive number of milliseconds`);
|
|
62
|
+
}
|
|
63
|
+
return timeoutMs;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Creates a Go-backed HTTP client handle on a loaded library. Tests pass a
|
|
67
|
+
* library from `@eserstack/ajan/ffi/fake`; everything else goes through
|
|
68
|
+
* {@link createGoHttpClient}.
|
|
69
|
+
*
|
|
70
|
+
* @throws Error if the bridge refuses the client options.
|
|
71
|
+
* @throws RangeError if `timeoutMs` is not a positive number.
|
|
72
|
+
*/
|
|
73
|
+
export const createGoHttpClientFor = (lib, options = {}) => {
|
|
74
|
+
const timeoutMs = checkedTimeout(options);
|
|
75
|
+
const result = lib.call("httpCreate", { ...options, timeoutMs });
|
|
76
|
+
if (result.error !== undefined && result.error !== "") {
|
|
77
|
+
throw new Error(`createGoHttpClient: ${result.error}`);
|
|
78
|
+
}
|
|
79
|
+
const handle = result.handle ?? "";
|
|
80
|
+
return {
|
|
81
|
+
async request(req) {
|
|
82
|
+
const res = await withSignal(handle, req, (wire, options) => lib.call("httpRequest", wire, options));
|
|
83
|
+
if (res.error !== undefined && res.error !== "") {
|
|
84
|
+
throw new GoHttpError({ ...res, error: res.error });
|
|
85
|
+
}
|
|
86
|
+
return res;
|
|
87
|
+
},
|
|
88
|
+
async requestStream(req) {
|
|
89
|
+
const stream = await withSignal(handle, req, (wire, options) => lib.stream("httpRequestStream", wire, options));
|
|
90
|
+
const init = stream.opened;
|
|
91
|
+
if ((init.error !== undefined && init.error !== "") ||
|
|
92
|
+
stream.handle === "") {
|
|
93
|
+
throw new GoHttpError({
|
|
94
|
+
error: init.error ??
|
|
95
|
+
"open HTTP stream: the Go bridge returned no stream handle",
|
|
96
|
+
status: init.status,
|
|
97
|
+
statusText: init.statusText,
|
|
98
|
+
headers: init.headers,
|
|
99
|
+
body: init.body,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
const status = init.status ?? 200;
|
|
103
|
+
const statusText = init.statusText ?? "";
|
|
104
|
+
const headers = { ...init.headers };
|
|
105
|
+
// The Go handle is released once: at the end of the body, on a read
|
|
106
|
+
// error, or when the reader cancels.
|
|
107
|
+
let released = false;
|
|
108
|
+
const release = () => {
|
|
109
|
+
if (!released) {
|
|
110
|
+
released = true;
|
|
111
|
+
stream.close();
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
const body = new ReadableStream({
|
|
115
|
+
async pull(controller) {
|
|
116
|
+
// The request's signal also ends a read in flight: its cancel
|
|
117
|
+
// entry closes the stream, as an aborted fetch errors its body.
|
|
118
|
+
const chunk = await stream.read({ signal: req.signal });
|
|
119
|
+
if (chunk === null) {
|
|
120
|
+
release();
|
|
121
|
+
controller.close();
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
if (chunk.error !== undefined && chunk.error !== "") {
|
|
125
|
+
release();
|
|
126
|
+
controller.error(new Error(chunk.error));
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
// The last read can carry both bytes and done.
|
|
130
|
+
if (chunk.chunk !== undefined && chunk.chunk !== "") {
|
|
131
|
+
controller.enqueue(decodeChunk(chunk.chunk));
|
|
132
|
+
}
|
|
133
|
+
if (chunk.done === true) {
|
|
134
|
+
release();
|
|
135
|
+
controller.close();
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
cancel() {
|
|
139
|
+
release();
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
return { body, status, statusText, headers };
|
|
143
|
+
},
|
|
144
|
+
close() {
|
|
145
|
+
lib.call("httpClose", handle);
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
};
|
|
149
|
+
/**
|
|
150
|
+
* Creates a Go-backed HTTP client handle.
|
|
151
|
+
*
|
|
152
|
+
* With the native library, each request runs in a worker thread, so the
|
|
153
|
+
* JavaScript thread keeps running while it waits; `timeoutMs` bounds it. On
|
|
154
|
+
* the WASM fallback the requests wait on the runtime's fetch instead.
|
|
155
|
+
*
|
|
156
|
+
* @throws Error if the native library is unavailable.
|
|
157
|
+
* @throws RangeError if `timeoutMs` is not a positive number.
|
|
158
|
+
*
|
|
159
|
+
* @example
|
|
160
|
+
* ```typescript
|
|
161
|
+
* import * as goClient from "@eserstack/httpclient/go-client";
|
|
162
|
+
*
|
|
163
|
+
* const client = await goClient.createGoHttpClient({ timeoutMs: 10_000 });
|
|
164
|
+
* const resp = await client.request({ method: "GET", url: "https://example.com" });
|
|
165
|
+
* console.log(resp.status, resp.body);
|
|
166
|
+
* client.close();
|
|
167
|
+
* ```
|
|
168
|
+
*/
|
|
169
|
+
export const createGoHttpClient = async (options = {}) => {
|
|
170
|
+
checkedTimeout(options);
|
|
171
|
+
await ffiClient.ensureLib();
|
|
172
|
+
const lib = ffiClient.getLib();
|
|
173
|
+
if (lib === null) {
|
|
174
|
+
throw new Error(`createGoHttpClient: the @eserstack/ajan native library is not available${ffiClient.describeLoadFailure()}`, { cause: ffiClient.getLoadError() ?? undefined });
|
|
175
|
+
}
|
|
176
|
+
return createGoHttpClientFor(lib, options);
|
|
177
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import * as goClientModule from "./go-client.ts";
|
|
2
|
+
/** What HttpClient calls in place of `fetch`. */
|
|
3
|
+
export type FetchLike = (request: Request) => Promise<Response>;
|
|
4
|
+
/**
|
|
5
|
+
* Makes a fetch-shaped function that sends each Request through `goClient`.
|
|
6
|
+
* `stream` picks the Go streaming call, which hands the body over unread.
|
|
7
|
+
*
|
|
8
|
+
* The request's signal reaches the Go client, and an abort fails the call as
|
|
9
|
+
* fetch fails on one. With the native library the request runs in a worker
|
|
10
|
+
* thread: an abort frees the caller at once, while the worker finishes the Go
|
|
11
|
+
* request, which the Go client's own `timeoutMs` bounds, and an abort during
|
|
12
|
+
* a streamed body closes the stream. On the WASM fallback the signal stops
|
|
13
|
+
* the fetch in flight.
|
|
14
|
+
*/
|
|
15
|
+
export declare const createGoFetch: (goClient: goClientModule.GoHttpClient, stream: boolean) => FetchLike;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* The Go HTTP client behind a fetch-shaped function.
|
|
4
|
+
*
|
|
5
|
+
* HttpClient sends every request through one pipeline: URL and header
|
|
6
|
+
* building, request interceptors, the retry policy, status handling and
|
|
7
|
+
* response interceptors. With `transport: "native"` only the last step, the
|
|
8
|
+
* exchange itself, goes to the Go client, through the function made here.
|
|
9
|
+
* Internal: not exported from the package.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
import * as errors from "./errors.js";
|
|
14
|
+
import * as goClientModule from "./go-client.js";
|
|
15
|
+
/** Statuses whose responses have no body; `new Response` refuses one. */
|
|
16
|
+
const NULL_BODY_STATUSES = new Set([204, 205, 304]);
|
|
17
|
+
const toResponse = (status, statusText, headers, body) => new Response(NULL_BODY_STATUSES.has(status) ? null : body, {
|
|
18
|
+
status,
|
|
19
|
+
statusText,
|
|
20
|
+
headers,
|
|
21
|
+
});
|
|
22
|
+
/**
|
|
23
|
+
* Turns a failure of the Go client into what fetch would have produced: a
|
|
24
|
+
* Response for an error status, so the shared status handling and retry
|
|
25
|
+
* policy see it, and an error otherwise.
|
|
26
|
+
*/
|
|
27
|
+
const toResponseOrError = (error, request) => {
|
|
28
|
+
if (error instanceof goClientModule.GoHttpError) {
|
|
29
|
+
if (error.status >= 400) {
|
|
30
|
+
return toResponse(error.status, error.statusText, error.headers, error.body);
|
|
31
|
+
}
|
|
32
|
+
if (error.status === 0) {
|
|
33
|
+
throw new errors.HttpNetworkError(`${request.method} request through the native client: ${error.message}`, { cause: error });
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const cause = error instanceof Error ? error : new Error(String(error));
|
|
37
|
+
throw new errors.HttpClientError(`${request.method} request through the native client: ${cause.message}`, { cause });
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Makes a fetch-shaped function that sends each Request through `goClient`.
|
|
41
|
+
* `stream` picks the Go streaming call, which hands the body over unread.
|
|
42
|
+
*
|
|
43
|
+
* The request's signal reaches the Go client, and an abort fails the call as
|
|
44
|
+
* fetch fails on one. With the native library the request runs in a worker
|
|
45
|
+
* thread: an abort frees the caller at once, while the worker finishes the Go
|
|
46
|
+
* request, which the Go client's own `timeoutMs` bounds, and an abort during
|
|
47
|
+
* a streamed body closes the stream. On the WASM fallback the signal stops
|
|
48
|
+
* the fetch in flight.
|
|
49
|
+
*/
|
|
50
|
+
export const createGoFetch = (goClient, stream) => async (request) => {
|
|
51
|
+
request.signal.throwIfAborted();
|
|
52
|
+
const body = request.body === null ? "" : await request.text();
|
|
53
|
+
const goRequest = {
|
|
54
|
+
method: request.method,
|
|
55
|
+
url: request.url,
|
|
56
|
+
headers: Object.fromEntries(request.headers),
|
|
57
|
+
...(body !== "" && { body }),
|
|
58
|
+
signal: request.signal,
|
|
59
|
+
};
|
|
60
|
+
try {
|
|
61
|
+
if (stream) {
|
|
62
|
+
const resp = await goClient.requestStream(goRequest);
|
|
63
|
+
return toResponse(resp.status, resp.statusText, resp.headers, resp.body);
|
|
64
|
+
}
|
|
65
|
+
const resp = await goClient.request(goRequest);
|
|
66
|
+
return toResponse(resp.status, resp.statusText, resp.headers, resp.body);
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (request.signal.aborted) {
|
|
70
|
+
throw request.signal.reason;
|
|
71
|
+
}
|
|
72
|
+
return toResponseOrError(error, request);
|
|
73
|
+
}
|
|
74
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A fetch function for HTTP/3 servers such as noskills-server.
|
|
3
|
+
*
|
|
4
|
+
* `createH3FetchFn` returns the runtime's own `fetch`. Browsers negotiate
|
|
5
|
+
* HTTP/3 by themselves when the server advertises it, so the native `fetch`
|
|
6
|
+
* already speaks it there. This package has no HTTP/3 transport of its own:
|
|
7
|
+
* outside a browser, `fetch` speaks whatever the runtime supports.
|
|
8
|
+
*
|
|
9
|
+
* It pins no certificate. Trust a self-signed certificate through the runtime
|
|
10
|
+
* (on Node, the `NODE_EXTRA_CA_CERTS` environment variable) or, for
|
|
11
|
+
* WebTransport, through `serverCertificateHashes` in `@eserstack/webtransport`.
|
|
12
|
+
*
|
|
13
|
+
* @module
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* Returns the global `fetch`, bound to `globalThis`, for use as the `fetchFn`
|
|
17
|
+
* of `createHttpClient`.
|
|
18
|
+
*
|
|
19
|
+
* @throws Error when the runtime has no global `fetch`.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```ts
|
|
23
|
+
* import * as httpclient from "@eserstack/httpclient";
|
|
24
|
+
* import * as h3Fetch from "@eserstack/httpclient/h3-fetch";
|
|
25
|
+
*
|
|
26
|
+
* const client = httpclient.createHttpClient({
|
|
27
|
+
* baseUrl: "https://localhost:4433",
|
|
28
|
+
* fetchFn: h3Fetch.createH3FetchFn(),
|
|
29
|
+
* });
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export declare function createH3FetchFn(): typeof fetch;
|
package/dist/h3-fetch.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* A fetch function for HTTP/3 servers such as noskills-server.
|
|
4
|
+
*
|
|
5
|
+
* `createH3FetchFn` returns the runtime's own `fetch`. Browsers negotiate
|
|
6
|
+
* HTTP/3 by themselves when the server advertises it, so the native `fetch`
|
|
7
|
+
* already speaks it there. This package has no HTTP/3 transport of its own:
|
|
8
|
+
* outside a browser, `fetch` speaks whatever the runtime supports.
|
|
9
|
+
*
|
|
10
|
+
* It pins no certificate. Trust a self-signed certificate through the runtime
|
|
11
|
+
* (on Node, the `NODE_EXTRA_CA_CERTS` environment variable) or, for
|
|
12
|
+
* WebTransport, through `serverCertificateHashes` in `@eserstack/webtransport`.
|
|
13
|
+
*
|
|
14
|
+
* @module
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Returns the global `fetch`, bound to `globalThis`, for use as the `fetchFn`
|
|
18
|
+
* of `createHttpClient`.
|
|
19
|
+
*
|
|
20
|
+
* @throws Error when the runtime has no global `fetch`.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```ts
|
|
24
|
+
* import * as httpclient from "@eserstack/httpclient";
|
|
25
|
+
* import * as h3Fetch from "@eserstack/httpclient/h3-fetch";
|
|
26
|
+
*
|
|
27
|
+
* const client = httpclient.createHttpClient({
|
|
28
|
+
* baseUrl: "https://localhost:4433",
|
|
29
|
+
* fetchFn: h3Fetch.createH3FetchFn(),
|
|
30
|
+
* });
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export function createH3FetchFn() {
|
|
34
|
+
if (typeof globalThis.fetch !== "function") {
|
|
35
|
+
throw new Error("createH3FetchFn: this runtime has no global fetch; use Node 18 or later or a browser, or pass your own fetchFn to createHttpClient");
|
|
36
|
+
}
|
|
37
|
+
return globalThis.fetch.bind(globalThis);
|
|
38
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Named interceptor chain for @eserstack/httpclient.
|
|
3
|
+
*
|
|
4
|
+
* Interceptors allow middleware-style transformation of requests and responses.
|
|
5
|
+
* Named interceptors can be removed by name at runtime (useful for auth header
|
|
6
|
+
* injection, logging, metrics, and testing).
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import type * as types from "./types.ts";
|
|
11
|
+
/** Mutable, ordered list of named interceptors. */
|
|
12
|
+
export declare class InterceptorChain<T extends {
|
|
13
|
+
name?: string;
|
|
14
|
+
}> {
|
|
15
|
+
private readonly _interceptors;
|
|
16
|
+
/** Append an interceptor to the end of the chain. */
|
|
17
|
+
add(interceptor: T): this;
|
|
18
|
+
/** Remove the first interceptor with the given name. Returns true if found. */
|
|
19
|
+
remove(name: string): boolean;
|
|
20
|
+
/** Remove all interceptors. */
|
|
21
|
+
clear(): this;
|
|
22
|
+
get length(): number;
|
|
23
|
+
[Symbol.iterator](): IterableIterator<T>;
|
|
24
|
+
}
|
|
25
|
+
/** Apply request interceptors in order, each receiving the previous result. */
|
|
26
|
+
export declare const applyRequestInterceptors: (request: Request, chain: ReadonlyArray<types.RequestInterceptor>) => Promise<Request>;
|
|
27
|
+
/** Apply response interceptors in order, each receiving the previous result. */
|
|
28
|
+
export declare const applyResponseInterceptors: <T>(response: types.HttpResponse<T>, chain: ReadonlyArray<types.ResponseInterceptor>) => Promise<types.HttpResponse<T>>;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
// =============================================================================
|
|
3
|
+
// InterceptorChain
|
|
4
|
+
// =============================================================================
|
|
5
|
+
/** Mutable, ordered list of named interceptors. */
|
|
6
|
+
export class InterceptorChain {
|
|
7
|
+
_interceptors = [];
|
|
8
|
+
/** Append an interceptor to the end of the chain. */
|
|
9
|
+
add(interceptor) {
|
|
10
|
+
this._interceptors.push(interceptor);
|
|
11
|
+
return this;
|
|
12
|
+
}
|
|
13
|
+
/** Remove the first interceptor with the given name. Returns true if found. */
|
|
14
|
+
remove(name) {
|
|
15
|
+
const index = this._interceptors.findIndex((i) => i.name === name);
|
|
16
|
+
if (index === -1)
|
|
17
|
+
return false;
|
|
18
|
+
this._interceptors.splice(index, 1);
|
|
19
|
+
return true;
|
|
20
|
+
}
|
|
21
|
+
/** Remove all interceptors. */
|
|
22
|
+
clear() {
|
|
23
|
+
this._interceptors.length = 0;
|
|
24
|
+
return this;
|
|
25
|
+
}
|
|
26
|
+
get length() {
|
|
27
|
+
return this._interceptors.length;
|
|
28
|
+
}
|
|
29
|
+
[Symbol.iterator]() {
|
|
30
|
+
return this._interceptors[Symbol.iterator]();
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
// =============================================================================
|
|
34
|
+
// Applicators
|
|
35
|
+
// =============================================================================
|
|
36
|
+
/** Apply request interceptors in order, each receiving the previous result. */
|
|
37
|
+
export const applyRequestInterceptors = async (request, chain) => {
|
|
38
|
+
let current = request;
|
|
39
|
+
for (const interceptor of chain) {
|
|
40
|
+
// Each interceptor receives the previous one's output, so they run in
|
|
41
|
+
// order.
|
|
42
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
43
|
+
current = await interceptor.intercept(current);
|
|
44
|
+
}
|
|
45
|
+
return current;
|
|
46
|
+
};
|
|
47
|
+
/** Apply response interceptors in order, each receiving the previous result. */
|
|
48
|
+
export const applyResponseInterceptors = async (response, chain) => {
|
|
49
|
+
let current = response;
|
|
50
|
+
for (const interceptor of chain) {
|
|
51
|
+
// Each interceptor receives the previous one's output, so they run in
|
|
52
|
+
// order.
|
|
53
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
54
|
+
current = (await interceptor.intercept(current));
|
|
55
|
+
}
|
|
56
|
+
return current;
|
|
57
|
+
};
|
package/dist/mod.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @eserstack/httpclient — resilient HTTP client with retry, timeout, rate-limit
|
|
3
|
+
* handling, typed errors, and @eserstack/functions Result compatibility.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
export { createHttpClient, extractRateLimitInfo, HttpClient, parseRetryAfter, } from "./client.ts";
|
|
8
|
+
export { classifyAndWrap, classifyError, classifyHttpStatus, HttpAbortError, HttpClientError, type HttpClientErrorOptions, HttpNetworkError, HttpRateLimitError, HttpResponseError, HttpTimeoutError, } from "./errors.ts";
|
|
9
|
+
export type { GoHttpClient, GoHttpClientOptions, GoHttpMethod, GoHttpRequest, GoHttpResponse, GoHttpStreamResponse, } from "./go-client.ts";
|
|
10
|
+
export { applyRequestInterceptors, applyResponseInterceptors, InterceptorChain, } from "./interceptors.ts";
|
|
11
|
+
export type { Fail, HttpClientConfig, HttpMethod, HttpResponse, HttpStreamResponse, HttpTransport, Interceptors, Ok, RateLimitInfo, RequestInterceptor, RequestOptions, ResponseInterceptor, Result, RetryConfig, } from "./types.ts";
|
package/dist/mod.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
|
|
2
|
+
/**
|
|
3
|
+
* @eserstack/httpclient — resilient HTTP client with retry, timeout, rate-limit
|
|
4
|
+
* handling, typed errors, and @eserstack/functions Result compatibility.
|
|
5
|
+
*
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
export { createHttpClient, extractRateLimitInfo, HttpClient, parseRetryAfter, } from "./client.js";
|
|
9
|
+
export { classifyAndWrap, classifyError, classifyHttpStatus, HttpAbortError, HttpClientError, HttpNetworkError, HttpRateLimitError, HttpResponseError, HttpTimeoutError, } from "./errors.js";
|
|
10
|
+
export { applyRequestInterceptors, applyResponseInterceptors, InterceptorChain, } from "./interceptors.js";
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type * as bindings from "@eserstack/ajan/ffi/bindings";
|
|
2
|
+
import type * as types from "./types.ts";
|
|
3
|
+
/** The retry plan of one request, as Go resolved it. */
|
|
4
|
+
export type RetryPlan = {
|
|
5
|
+
/** Attempts run while the attempt number is below this. */
|
|
6
|
+
readonly maxAttempts: number;
|
|
7
|
+
/** The plan as Go answered it, sent back with every decision. */
|
|
8
|
+
readonly wire: bindings.HttpRetryPlan;
|
|
9
|
+
};
|
|
10
|
+
/** What to do after a failed attempt. */
|
|
11
|
+
export type RetryDecision = {
|
|
12
|
+
readonly retry: boolean;
|
|
13
|
+
readonly delayMs: number;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Resolves the plan of one request from the client's and the request's retry
|
|
17
|
+
* settings. A stream body, which the first attempt consumes, gets one
|
|
18
|
+
* attempt.
|
|
19
|
+
*
|
|
20
|
+
* @throws {errors.HttpClientError} When the bridge is unavailable (its load
|
|
21
|
+
* error as `cause`) or Go refuses a setting outside RetryConfig.
|
|
22
|
+
*/
|
|
23
|
+
export declare const resolveRetryPlan: (clientRetry: types.RetryConfig | false | undefined, requestRetry: types.RetryConfig | false | undefined, streamBody: boolean) => RetryPlan;
|
|
24
|
+
/**
|
|
25
|
+
* Decides after the failed attempt number `attempt` (0 for the first).
|
|
26
|
+
* `status` is the response status, 0 for a network failure; `retryAfterMs` is
|
|
27
|
+
* the response's Retry-After, null when it has none.
|
|
28
|
+
*
|
|
29
|
+
* @throws {errors.HttpClientError} When the bridge is unavailable or refuses
|
|
30
|
+
* the request.
|
|
31
|
+
*/
|
|
32
|
+
export declare const nextRetry: (plan: RetryPlan, attempt: number, status: number, retryAfterMs: number | null) => RetryDecision;
|