@jondotsoy/resilience 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +637 -2
- package/backoff.d.ts +27 -0
- package/backoff.js +22 -0
- package/bulkhead.d.ts +23 -0
- package/bulkhead.js +59 -0
- package/cache.d.ts +22 -0
- package/cache.js +38 -0
- package/circuit-breaker.d.ts +26 -0
- package/circuit-breaker.js +81 -0
- package/dedupe.d.ts +11 -0
- package/dedupe.js +19 -0
- package/errors.d.ts +19 -0
- package/errors.js +25 -0
- package/index.d.ts +189 -0
- package/index.js +190 -0
- package/package.json +30 -4
- package/throttle.d.ts +14 -0
- package/throttle.js +30 -0
package/index.js
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { exponentialBackoff, fibonacciBackoff, fixedBackoff, linearBackoff, } from "./backoff.js";
|
|
2
|
+
import { circuitBreaker } from "./circuit-breaker.js";
|
|
3
|
+
import { bulkhead } from "./bulkhead.js";
|
|
4
|
+
import { throttle } from "./throttle.js";
|
|
5
|
+
import { cache } from "./cache.js";
|
|
6
|
+
import { dedupe } from "./dedupe.js";
|
|
7
|
+
import { BulkheadRejectedError, CircuitOpenError, ThrottleError, } from "./errors.js";
|
|
8
|
+
const abortReason = (signal) => signal.reason ?? new DOMException("This operation was aborted", "AbortError");
|
|
9
|
+
const timeoutError = (ms) => new DOMException(`The attempt timed out after ${ms} ms`, "TimeoutError");
|
|
10
|
+
const assertDelay = (ms) => {
|
|
11
|
+
if (!Number.isFinite(ms) || ms < 0) {
|
|
12
|
+
throw new RangeError(`delay must be a finite number >= 0, received ${ms}`);
|
|
13
|
+
}
|
|
14
|
+
return ms;
|
|
15
|
+
};
|
|
16
|
+
/** Espera `ms` milisegundos; rechaza de inmediato si se aborta el signal. */
|
|
17
|
+
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
18
|
+
if (signal?.aborted)
|
|
19
|
+
return reject(abortReason(signal));
|
|
20
|
+
if (ms <= 0)
|
|
21
|
+
return resolve();
|
|
22
|
+
const onAbort = () => {
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
reject(abortReason(signal));
|
|
25
|
+
};
|
|
26
|
+
const timer = setTimeout(() => {
|
|
27
|
+
signal?.removeEventListener("abort", onAbort);
|
|
28
|
+
resolve();
|
|
29
|
+
}, ms);
|
|
30
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
31
|
+
});
|
|
32
|
+
/**
|
|
33
|
+
* Crea un ejecutor con reintentos.
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* const res = await resilience({ attempts: 3 }).attempt(({ signal }) =>
|
|
37
|
+
* fetch("https://example.com", { signal }),
|
|
38
|
+
* );
|
|
39
|
+
*/
|
|
40
|
+
const createResilience = (options = {}) => {
|
|
41
|
+
const attempts = options.attempts ?? 1;
|
|
42
|
+
if (!Number.isInteger(attempts) || attempts < 1) {
|
|
43
|
+
throw new RangeError(`options.attempts must be an integer >= 1, received ${attempts}`);
|
|
44
|
+
}
|
|
45
|
+
const { signal: parentSignal, onRetry, retryable, timeout, fallback, delay = 0, waitForTask = false, onStart, onAttempt, onTimeout, onError, onSuccess, onFailure, onAbort: onAbortHook, onSettled, } = options;
|
|
46
|
+
if (typeof delay === "number")
|
|
47
|
+
assertDelay(delay);
|
|
48
|
+
if (timeout !== undefined && (!Number.isFinite(timeout) || timeout <= 0)) {
|
|
49
|
+
throw new RangeError(`options.timeout must be a finite number > 0, received ${timeout}`);
|
|
50
|
+
}
|
|
51
|
+
const run = async (fn, progress) => {
|
|
52
|
+
let lastError;
|
|
53
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
54
|
+
progress.attempt = attempt;
|
|
55
|
+
if (parentSignal?.aborted)
|
|
56
|
+
throw abortReason(parentSignal);
|
|
57
|
+
if (attempt > 1) {
|
|
58
|
+
const context = { attempt, attempts, error: lastError };
|
|
59
|
+
const ms = assertDelay(typeof delay === "function" ? delay(context) : delay);
|
|
60
|
+
if (onRetry)
|
|
61
|
+
await onRetry({ ...context, delay: ms });
|
|
62
|
+
await sleep(ms, parentSignal);
|
|
63
|
+
if (parentSignal?.aborted)
|
|
64
|
+
throw abortReason(parentSignal);
|
|
65
|
+
}
|
|
66
|
+
// Cada intento tiene su propio controller, enlazado al signal externo.
|
|
67
|
+
const controller = new AbortController();
|
|
68
|
+
const onAbort = () => controller.abort(abortReason(parentSignal));
|
|
69
|
+
parentSignal?.addEventListener("abort", onAbort, { once: true });
|
|
70
|
+
let timer;
|
|
71
|
+
let timedOut = false;
|
|
72
|
+
try {
|
|
73
|
+
await onAttempt?.({ attempt, attempts, lastError });
|
|
74
|
+
const run = Promise.resolve().then(() => fn({ signal: controller.signal, attempt, attempts, lastError }));
|
|
75
|
+
if (timeout !== undefined) {
|
|
76
|
+
timer = setTimeout(() => {
|
|
77
|
+
timedOut = true;
|
|
78
|
+
controller.abort(timeoutError(timeout));
|
|
79
|
+
}, timeout);
|
|
80
|
+
}
|
|
81
|
+
// La tarea decide cuándo termina: se devuelve lo que ella devuelva.
|
|
82
|
+
if (waitForTask)
|
|
83
|
+
return await run;
|
|
84
|
+
// Si se aborta (signal o timeout) se rechaza en ese momento; la
|
|
85
|
+
// promesa de la tarea puede rechazar después.
|
|
86
|
+
run.catch(() => { });
|
|
87
|
+
return await Promise.race([
|
|
88
|
+
run,
|
|
89
|
+
new Promise((_, reject) => {
|
|
90
|
+
const reject_ = () => reject(controller.signal.reason);
|
|
91
|
+
if (controller.signal.aborted)
|
|
92
|
+
return reject_();
|
|
93
|
+
controller.signal.addEventListener("abort", reject_, { once: true });
|
|
94
|
+
}),
|
|
95
|
+
]);
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
// Si se canceló desde afuera, no se reintenta.
|
|
99
|
+
if (parentSignal?.aborted) {
|
|
100
|
+
throw waitForTask ? error : abortReason(parentSignal);
|
|
101
|
+
}
|
|
102
|
+
if (timedOut)
|
|
103
|
+
await onTimeout?.({ attempt, attempts, timeout: timeout });
|
|
104
|
+
const willRetry = attempt < attempts &&
|
|
105
|
+
(!retryable || (await retryable(error, { attempt, attempts })));
|
|
106
|
+
await onError?.(error, { attempt, attempts, willRetry });
|
|
107
|
+
if (!willRetry)
|
|
108
|
+
throw error;
|
|
109
|
+
lastError = error;
|
|
110
|
+
}
|
|
111
|
+
finally {
|
|
112
|
+
clearTimeout(timer);
|
|
113
|
+
// No se aborta el controller al terminar: un `fetch` resuelto aún
|
|
114
|
+
// puede estar leyendo el body con ese signal.
|
|
115
|
+
parentSignal?.removeEventListener("abort", onAbort);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
throw lastError;
|
|
119
|
+
};
|
|
120
|
+
return {
|
|
121
|
+
async attempt(fn) {
|
|
122
|
+
const progress = { attempt: 0 };
|
|
123
|
+
const context = () => ({
|
|
124
|
+
attempt: progress.attempt,
|
|
125
|
+
attempts,
|
|
126
|
+
});
|
|
127
|
+
await onStart?.(context());
|
|
128
|
+
let value;
|
|
129
|
+
try {
|
|
130
|
+
value = await run(fn, progress);
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
// Cancelar no es un fallo: no se usa el fallback.
|
|
134
|
+
if (parentSignal?.aborted) {
|
|
135
|
+
await onAbortHook?.(error, context());
|
|
136
|
+
await onSettled?.({ status: "aborted", error, ...context() });
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
await onFailure?.(error, context());
|
|
140
|
+
if (!fallback) {
|
|
141
|
+
await onSettled?.({ status: "failure", error, ...context() });
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
const recovered = await fallback(error, context());
|
|
145
|
+
await onSettled?.({
|
|
146
|
+
status: "fallback",
|
|
147
|
+
error,
|
|
148
|
+
value: recovered,
|
|
149
|
+
...context(),
|
|
150
|
+
});
|
|
151
|
+
return recovered;
|
|
152
|
+
}
|
|
153
|
+
await onSuccess?.(value, context());
|
|
154
|
+
await onSettled?.({ status: "success", value, ...context() });
|
|
155
|
+
return value;
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
};
|
|
159
|
+
/**
|
|
160
|
+
* Crea un ejecutor con reintentos. Las utilidades también están disponibles
|
|
161
|
+
* como propiedades, por ejemplo `resilience.exponentialBackoff(200)`.
|
|
162
|
+
*
|
|
163
|
+
* @example
|
|
164
|
+
* const res = await resilience({
|
|
165
|
+
* attempts: 3,
|
|
166
|
+
* delay: resilience.exponentialBackoff(200),
|
|
167
|
+
* }).attempt(({ signal }) => fetch("https://example.com", { signal }));
|
|
168
|
+
*/
|
|
169
|
+
export const resilience = Object.assign(createResilience, {
|
|
170
|
+
fixedBackoff,
|
|
171
|
+
linearBackoff,
|
|
172
|
+
exponentialBackoff,
|
|
173
|
+
fibonacciBackoff,
|
|
174
|
+
circuitBreaker,
|
|
175
|
+
bulkhead,
|
|
176
|
+
throttle,
|
|
177
|
+
cache,
|
|
178
|
+
dedupe,
|
|
179
|
+
CircuitOpenError,
|
|
180
|
+
BulkheadRejectedError,
|
|
181
|
+
ThrottleError,
|
|
182
|
+
});
|
|
183
|
+
export * from "./backoff.js";
|
|
184
|
+
export * from "./errors.js";
|
|
185
|
+
export * from "./circuit-breaker.js";
|
|
186
|
+
export * from "./bulkhead.js";
|
|
187
|
+
export * from "./throttle.js";
|
|
188
|
+
export * from "./cache.js";
|
|
189
|
+
export * from "./dedupe.js";
|
|
190
|
+
export default resilience;
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jondotsoy/resilience",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Ejecuta una función con reintentos y cancelación vía AbortSignal.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./index.js",
|
|
7
|
+
"types": "./index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./index.d.ts",
|
|
11
|
+
"import": "./index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"sideEffects": false,
|
|
15
|
+
"keywords": [
|
|
16
|
+
"retry",
|
|
17
|
+
"resilience",
|
|
18
|
+
"abort",
|
|
19
|
+
"signal",
|
|
20
|
+
"fetch"
|
|
21
|
+
],
|
|
22
|
+
"author": "JonDotsoy",
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/JonDotsoy/resilience.git"
|
|
27
|
+
},
|
|
28
|
+
"homepage": "https://github.com/JonDotsoy/resilience#readme",
|
|
29
|
+
"bugs": {
|
|
30
|
+
"url": "https://github.com/JonDotsoy/resilience/issues"
|
|
31
|
+
}
|
|
32
|
+
}
|
package/throttle.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface ThrottleOptions {
|
|
2
|
+
/** Máximo de llamadas permitidas dentro de `interval`. */
|
|
3
|
+
limit: number;
|
|
4
|
+
/** Ventana de tiempo en ms. */
|
|
5
|
+
interval: number;
|
|
6
|
+
}
|
|
7
|
+
export interface Throttle {
|
|
8
|
+
/** Cupos disponibles en este momento. */
|
|
9
|
+
readonly remaining: number;
|
|
10
|
+
/** Ejecuta `fn` si hay cupo; si no, lanza `ThrottleError` con `retryAfter`. */
|
|
11
|
+
execute<T>(fn: () => T | Promise<T>): Promise<T>;
|
|
12
|
+
}
|
|
13
|
+
/** Limita cuántas llamadas se hacen en una ventana de tiempo (ventana deslizante). */
|
|
14
|
+
export declare const throttle: ({ limit, interval }: ThrottleOptions) => Throttle;
|
package/throttle.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { ThrottleError } from "./errors.js";
|
|
2
|
+
/** Limita cuántas llamadas se hacen en una ventana de tiempo (ventana deslizante). */
|
|
3
|
+
export const throttle = ({ limit, interval }) => {
|
|
4
|
+
if (!Number.isInteger(limit) || limit < 1) {
|
|
5
|
+
throw new RangeError(`limit must be an integer >= 1, received ${limit}`);
|
|
6
|
+
}
|
|
7
|
+
if (!Number.isFinite(interval) || interval <= 0) {
|
|
8
|
+
throw new RangeError(`interval must be a finite number > 0, received ${interval}`);
|
|
9
|
+
}
|
|
10
|
+
const calls = [];
|
|
11
|
+
const prune = (now) => {
|
|
12
|
+
while (calls.length && now - calls[0] >= interval)
|
|
13
|
+
calls.shift();
|
|
14
|
+
};
|
|
15
|
+
return {
|
|
16
|
+
get remaining() {
|
|
17
|
+
prune(Date.now());
|
|
18
|
+
return limit - calls.length;
|
|
19
|
+
},
|
|
20
|
+
async execute(fn) {
|
|
21
|
+
const now = Date.now();
|
|
22
|
+
prune(now);
|
|
23
|
+
if (calls.length >= limit) {
|
|
24
|
+
throw new ThrottleError(interval - (now - calls[0]));
|
|
25
|
+
}
|
|
26
|
+
calls.push(now);
|
|
27
|
+
return fn();
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
};
|