reliable-requests 0.2.1 → 0.3.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/CHANGELOG.md +33 -19
- package/LICENSE +21 -21
- package/README.md +207 -207
- package/docs/MODEL_COMPATIBILITY.md +90 -56
- package/docs/STREAM_CONTRACT.md +72 -68
- package/docs/USAGE.md +313 -299
- package/index.d.ts +138 -127
- package/index.js +12 -11
- package/package.json +51 -49
- package/src/endpoint.js +17 -17
- package/src/index.js +128 -128
- package/src/local-chat.js +403 -343
- package/src/metrics.js +46 -46
- package/src/retry.js +48 -48
- package/src/sse.js +93 -93
- package/src/stream-events.js +69 -69
package/src/index.js
CHANGED
|
@@ -1,128 +1,128 @@
|
|
|
1
|
-
import {
|
|
2
|
-
isRetryableStatus,
|
|
3
|
-
defaultShouldRetryError,
|
|
4
|
-
retryDelayMs,
|
|
5
|
-
pause,
|
|
6
|
-
abortError,
|
|
7
|
-
discardResponse,
|
|
8
|
-
} from './retry.js';
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* A small fetch wrapper with one deadline across attempts and response consumption.
|
|
12
|
-
* Requires global fetch, AbortController, and DOMException (modern browsers and Node 18+).
|
|
13
|
-
*/
|
|
14
|
-
export class RequestTimeoutError extends Error {
|
|
15
|
-
constructor(timeoutMs, message = `Request exceeded the ${timeoutMs} ms total timeout`) {
|
|
16
|
-
super(message);
|
|
17
|
-
this.name = 'RequestTimeoutError';
|
|
18
|
-
this.code = 'REQUEST_TIMEOUT';
|
|
19
|
-
this.timeoutMs = timeoutMs;
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export class HttpError extends Error {
|
|
24
|
-
constructor(response, attempts) {
|
|
25
|
-
super(`HTTP ${response.status} ${response.statusText || ''}`.trim());
|
|
26
|
-
this.name = 'HttpError';
|
|
27
|
-
this.code = 'HTTP_ERROR';
|
|
28
|
-
this.status = response.status;
|
|
29
|
-
this.response = response;
|
|
30
|
-
this.attempts = attempts;
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
const SAFE_METHODS = new Set(['GET', 'HEAD']);
|
|
35
|
-
|
|
36
|
-
/**
|
|
37
|
-
* @param {string|URL} input URL to fetch. Request objects are deliberately unsupported.
|
|
38
|
-
* @param {object} options fetch options plus timeoutMs, retries, consume, fetchImpl, shouldRetryError.
|
|
39
|
-
* @returns {Promise<Response|unknown>} Response, or the result of consume(response, signal).
|
|
40
|
-
*/
|
|
41
|
-
export async function reliableRequest(input, options = {}) {
|
|
42
|
-
const {
|
|
43
|
-
timeoutMs = 30_000,
|
|
44
|
-
retries = 2,
|
|
45
|
-
consume,
|
|
46
|
-
fetchImpl = globalThis.fetch,
|
|
47
|
-
shouldRetryError = defaultShouldRetryError,
|
|
48
|
-
signal: callerSignal,
|
|
49
|
-
...init
|
|
50
|
-
} = options;
|
|
51
|
-
if (typeof input !== 'string' && !(input instanceof URL)) throw new TypeError('input must be a URL string or URL');
|
|
52
|
-
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) throw new RangeError('timeoutMs must be a positive integer');
|
|
53
|
-
if (!Number.isSafeInteger(retries) || retries < 0) throw new RangeError('retries must be a non-negative integer');
|
|
54
|
-
if (consume !== undefined && typeof consume !== 'function') throw new TypeError('consume must be a function');
|
|
55
|
-
if (typeof fetchImpl !== 'function') throw new TypeError('fetchImpl must be a function');
|
|
56
|
-
if (typeof shouldRetryError !== 'function') throw new TypeError('shouldRetryError must be a function');
|
|
57
|
-
const method = String(init.method || 'GET').toUpperCase();
|
|
58
|
-
const canRetry = SAFE_METHODS.has(method);
|
|
59
|
-
const controller = new AbortController();
|
|
60
|
-
let rejectStopped;
|
|
61
|
-
const stopped = new Promise((_, reject) => { rejectStopped = reject; });
|
|
62
|
-
let finished = false;
|
|
63
|
-
const stop = (error) => {
|
|
64
|
-
if (finished) return;
|
|
65
|
-
finished = true;
|
|
66
|
-
rejectStopped(error);
|
|
67
|
-
controller.abort(error);
|
|
68
|
-
};
|
|
69
|
-
const onCallerAbort = () => stop(abortError());
|
|
70
|
-
if (callerSignal?.aborted) throw abortError();
|
|
71
|
-
callerSignal?.addEventListener('abort', onCallerAbort, { once: true });
|
|
72
|
-
const started = performance.now();
|
|
73
|
-
const remaining = () => timeoutMs - (performance.now() - started);
|
|
74
|
-
const timer = setTimeout(() => stop(new RequestTimeoutError(timeoutMs)), timeoutMs);
|
|
75
|
-
const checkDeadline = () => {
|
|
76
|
-
if (controller.signal.aborted) throw controller.signal.reason;
|
|
77
|
-
if (remaining() <= 0) {
|
|
78
|
-
stop(new RequestTimeoutError(timeoutMs));
|
|
79
|
-
throw controller.signal.reason;
|
|
80
|
-
}
|
|
81
|
-
};
|
|
82
|
-
const waitToRetry = async (attempt, response) => {
|
|
83
|
-
checkDeadline();
|
|
84
|
-
const delay = retryDelayMs({ attempt, response, remainingMs: remaining() });
|
|
85
|
-
if (delay === null) {
|
|
86
|
-
stop(new RequestTimeoutError(timeoutMs, 'Retry delay cannot fit within the ' + timeoutMs + ' ms total timeout'));
|
|
87
|
-
throw controller.signal.reason;
|
|
88
|
-
}
|
|
89
|
-
await pause(delay, controller.signal);
|
|
90
|
-
};
|
|
91
|
-
const run = async () => {
|
|
92
|
-
for (let attempt = 1; ; attempt++) {
|
|
93
|
-
checkDeadline();
|
|
94
|
-
let response;
|
|
95
|
-
try {
|
|
96
|
-
response = await fetchImpl(input, { ...init, method, signal: controller.signal });
|
|
97
|
-
} catch (error) {
|
|
98
|
-
checkDeadline();
|
|
99
|
-
if (!canRetry || attempt > retries) throw error;
|
|
100
|
-
if (error?.name === 'AbortError' || error instanceof RequestTimeoutError) throw error;
|
|
101
|
-
if (shouldRetryError(error, { attempt, method, phase: 'fetch' }) !== true) throw error;
|
|
102
|
-
await waitToRetry(attempt);
|
|
103
|
-
continue;
|
|
104
|
-
}
|
|
105
|
-
if (controller.signal.aborted || remaining() <= 0) {
|
|
106
|
-
discardResponse(response);
|
|
107
|
-
checkDeadline();
|
|
108
|
-
}
|
|
109
|
-
if (!response.ok) {
|
|
110
|
-
const error = new HttpError(response, attempt);
|
|
111
|
-
if (!canRetry || attempt > retries || !isRetryableStatus(response.status)) throw error;
|
|
112
|
-
discardResponse(response);
|
|
113
|
-
await waitToRetry(attempt, response);
|
|
114
|
-
continue;
|
|
115
|
-
}
|
|
116
|
-
const value = consume ? await consume(response, controller.signal) : response;
|
|
117
|
-
checkDeadline();
|
|
118
|
-
return value;
|
|
119
|
-
}
|
|
120
|
-
};
|
|
121
|
-
try {
|
|
122
|
-
return await Promise.race([run(), stopped]);
|
|
123
|
-
} finally {
|
|
124
|
-
finished = true;
|
|
125
|
-
clearTimeout(timer);
|
|
126
|
-
callerSignal?.removeEventListener('abort', onCallerAbort);
|
|
127
|
-
}
|
|
128
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
isRetryableStatus,
|
|
3
|
+
defaultShouldRetryError,
|
|
4
|
+
retryDelayMs,
|
|
5
|
+
pause,
|
|
6
|
+
abortError,
|
|
7
|
+
discardResponse,
|
|
8
|
+
} from './retry.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A small fetch wrapper with one deadline across attempts and response consumption.
|
|
12
|
+
* Requires global fetch, AbortController, and DOMException (modern browsers and Node 18+).
|
|
13
|
+
*/
|
|
14
|
+
export class RequestTimeoutError extends Error {
|
|
15
|
+
constructor(timeoutMs, message = `Request exceeded the ${timeoutMs} ms total timeout`) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = 'RequestTimeoutError';
|
|
18
|
+
this.code = 'REQUEST_TIMEOUT';
|
|
19
|
+
this.timeoutMs = timeoutMs;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class HttpError extends Error {
|
|
24
|
+
constructor(response, attempts) {
|
|
25
|
+
super(`HTTP ${response.status} ${response.statusText || ''}`.trim());
|
|
26
|
+
this.name = 'HttpError';
|
|
27
|
+
this.code = 'HTTP_ERROR';
|
|
28
|
+
this.status = response.status;
|
|
29
|
+
this.response = response;
|
|
30
|
+
this.attempts = attempts;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const SAFE_METHODS = new Set(['GET', 'HEAD']);
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @param {string|URL} input URL to fetch. Request objects are deliberately unsupported.
|
|
38
|
+
* @param {object} options fetch options plus timeoutMs, retries, consume, fetchImpl, shouldRetryError.
|
|
39
|
+
* @returns {Promise<Response|unknown>} Response, or the result of consume(response, signal).
|
|
40
|
+
*/
|
|
41
|
+
export async function reliableRequest(input, options = {}) {
|
|
42
|
+
const {
|
|
43
|
+
timeoutMs = 30_000,
|
|
44
|
+
retries = 2,
|
|
45
|
+
consume,
|
|
46
|
+
fetchImpl = globalThis.fetch,
|
|
47
|
+
shouldRetryError = defaultShouldRetryError,
|
|
48
|
+
signal: callerSignal,
|
|
49
|
+
...init
|
|
50
|
+
} = options;
|
|
51
|
+
if (typeof input !== 'string' && !(input instanceof URL)) throw new TypeError('input must be a URL string or URL');
|
|
52
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) throw new RangeError('timeoutMs must be a positive integer');
|
|
53
|
+
if (!Number.isSafeInteger(retries) || retries < 0) throw new RangeError('retries must be a non-negative integer');
|
|
54
|
+
if (consume !== undefined && typeof consume !== 'function') throw new TypeError('consume must be a function');
|
|
55
|
+
if (typeof fetchImpl !== 'function') throw new TypeError('fetchImpl must be a function');
|
|
56
|
+
if (typeof shouldRetryError !== 'function') throw new TypeError('shouldRetryError must be a function');
|
|
57
|
+
const method = String(init.method || 'GET').toUpperCase();
|
|
58
|
+
const canRetry = SAFE_METHODS.has(method);
|
|
59
|
+
const controller = new AbortController();
|
|
60
|
+
let rejectStopped;
|
|
61
|
+
const stopped = new Promise((_, reject) => { rejectStopped = reject; });
|
|
62
|
+
let finished = false;
|
|
63
|
+
const stop = (error) => {
|
|
64
|
+
if (finished) return;
|
|
65
|
+
finished = true;
|
|
66
|
+
rejectStopped(error);
|
|
67
|
+
controller.abort(error);
|
|
68
|
+
};
|
|
69
|
+
const onCallerAbort = () => stop(abortError());
|
|
70
|
+
if (callerSignal?.aborted) throw abortError();
|
|
71
|
+
callerSignal?.addEventListener('abort', onCallerAbort, { once: true });
|
|
72
|
+
const started = performance.now();
|
|
73
|
+
const remaining = () => timeoutMs - (performance.now() - started);
|
|
74
|
+
const timer = setTimeout(() => stop(new RequestTimeoutError(timeoutMs)), timeoutMs);
|
|
75
|
+
const checkDeadline = () => {
|
|
76
|
+
if (controller.signal.aborted) throw controller.signal.reason;
|
|
77
|
+
if (remaining() <= 0) {
|
|
78
|
+
stop(new RequestTimeoutError(timeoutMs));
|
|
79
|
+
throw controller.signal.reason;
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
const waitToRetry = async (attempt, response) => {
|
|
83
|
+
checkDeadline();
|
|
84
|
+
const delay = retryDelayMs({ attempt, response, remainingMs: remaining() });
|
|
85
|
+
if (delay === null) {
|
|
86
|
+
stop(new RequestTimeoutError(timeoutMs, 'Retry delay cannot fit within the ' + timeoutMs + ' ms total timeout'));
|
|
87
|
+
throw controller.signal.reason;
|
|
88
|
+
}
|
|
89
|
+
await pause(delay, controller.signal);
|
|
90
|
+
};
|
|
91
|
+
const run = async () => {
|
|
92
|
+
for (let attempt = 1; ; attempt++) {
|
|
93
|
+
checkDeadline();
|
|
94
|
+
let response;
|
|
95
|
+
try {
|
|
96
|
+
response = await fetchImpl(input, { ...init, method, signal: controller.signal });
|
|
97
|
+
} catch (error) {
|
|
98
|
+
checkDeadline();
|
|
99
|
+
if (!canRetry || attempt > retries) throw error;
|
|
100
|
+
if (error?.name === 'AbortError' || error instanceof RequestTimeoutError) throw error;
|
|
101
|
+
if (shouldRetryError(error, { attempt, method, phase: 'fetch' }) !== true) throw error;
|
|
102
|
+
await waitToRetry(attempt);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (controller.signal.aborted || remaining() <= 0) {
|
|
106
|
+
discardResponse(response);
|
|
107
|
+
checkDeadline();
|
|
108
|
+
}
|
|
109
|
+
if (!response.ok) {
|
|
110
|
+
const error = new HttpError(response, attempt);
|
|
111
|
+
if (!canRetry || attempt > retries || !isRetryableStatus(response.status)) throw error;
|
|
112
|
+
discardResponse(response);
|
|
113
|
+
await waitToRetry(attempt, response);
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
const value = consume ? await consume(response, controller.signal) : response;
|
|
117
|
+
checkDeadline();
|
|
118
|
+
return value;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
try {
|
|
122
|
+
return await Promise.race([run(), stopped]);
|
|
123
|
+
} finally {
|
|
124
|
+
finished = true;
|
|
125
|
+
clearTimeout(timer);
|
|
126
|
+
callerSignal?.removeEventListener('abort', onCallerAbort);
|
|
127
|
+
}
|
|
128
|
+
}
|