breaker-box 5.0.0 → 6.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/README.md +159 -55
- package/dist/index.cjs +84 -69
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +111 -23
- package/dist/index.d.mts +111 -23
- package/dist/index.mjs +84 -69
- package/dist/index.mjs.map +1 -1
- package/package.json +11 -6
package/README.md
CHANGED
|
@@ -12,9 +12,7 @@ A zero-dependency [circuit breaker][0] implementation for Node.js.
|
|
|
12
12
|
npm install breaker-box
|
|
13
13
|
```
|
|
14
14
|
|
|
15
|
-
## Usage
|
|
16
|
-
|
|
17
|
-
### Basic Usage
|
|
15
|
+
## Basic Usage
|
|
18
16
|
|
|
19
17
|
```typescript
|
|
20
18
|
import { createCircuitBreaker } from "breaker-box"
|
|
@@ -29,7 +27,9 @@ async function unreliableApiCall(data: string) {
|
|
|
29
27
|
const protectedApiCall = createCircuitBreaker(unreliableApiCall, {
|
|
30
28
|
errorThreshold: 0.5, // Open circuit when 50% of calls fail
|
|
31
29
|
errorWindow: 10_000, // Track errors over 10 second window
|
|
32
|
-
|
|
30
|
+
// Fallback receives the same parameters as the original function
|
|
31
|
+
fallback: (data) => ({ data: "fallback data", error: "API call failed" }),
|
|
32
|
+
minimumCandidates: 1, // Need at least 1 call before calculating error rate
|
|
33
33
|
resetAfter: 30_000, // Try again after 30 seconds
|
|
34
34
|
})
|
|
35
35
|
|
|
@@ -41,59 +41,125 @@ try {
|
|
|
41
41
|
}
|
|
42
42
|
```
|
|
43
43
|
|
|
44
|
-
|
|
44
|
+
The above example creates a function named `protectedApiCall` which, when called will execute the `unreliableApiCall` function with circuit breaker protection. If the underlying function fails, then `fallback` is called instead. If **50%** of the calls fail within a **10-second sliding window**, then the circuit breaker will open and subsequent calls to `protectedApiCall` will **always** use the `fallback` for the next **30 seconds**.
|
|
45
|
+
|
|
46
|
+
## Composition Helpers
|
|
47
|
+
|
|
48
|
+
The circuit breaker function doesn't handle timeouts, retries, or cooldowns on
|
|
49
|
+
its own. For these features, you need to compose with other helper functions.
|
|
50
|
+
`breaker-box` provides a set of composable functions that can wrap your API call
|
|
51
|
+
with these features.
|
|
52
|
+
|
|
53
|
+
### Timeouts
|
|
54
|
+
|
|
55
|
+
Wrap the `unreliableApiCall` with a timeout using `withTimeout()`. If the timer
|
|
56
|
+
expires before the call completes, then the promise will reject with
|
|
57
|
+
`ERR_CIRCUIT_BREAKER_TIMEOUT`.
|
|
58
|
+
|
|
59
|
+
This wrapping may not be needed if your API call supports a timeout option
|
|
60
|
+
already (e.g. `axios` already has a `timeout` option).
|
|
61
|
+
|
|
62
|
+
```typescript
|
|
63
|
+
import { createCircuitBreaker, withTimeout } from "breaker-box"
|
|
64
|
+
|
|
65
|
+
const protectedApiCall = createCircuitBreaker(
|
|
66
|
+
withTimeout(unreliableApiCall, 5000),
|
|
67
|
+
)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### Retries
|
|
71
|
+
|
|
72
|
+
Wrap the `unreliableApiCall` with retry logic using `withRetry()` function. If
|
|
73
|
+
the promise gets rejected, it will be retried up to a certain number of times.
|
|
74
|
+
Once the max number of retries is reached, then the promise will ultimately
|
|
75
|
+
reject with `ERR_CIRCUIT_BREAKER_MAX_ATTEMPTS (${number})`.
|
|
76
|
+
|
|
77
|
+
This wrapping may not be needed if your API call supports a retry option already
|
|
78
|
+
(e.g. `aws-sdk` already has retry logic).
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
import { createCircuitBreaker, withRetry } from "breaker-box"
|
|
82
|
+
|
|
83
|
+
const protectedApiCall = createCircuitBreaker(
|
|
84
|
+
withRetry(unreliableApiCall, {
|
|
85
|
+
maxAttempts: 3,
|
|
86
|
+
shouldRetry: (error) => true, // Check whether error is retryable
|
|
87
|
+
}),
|
|
88
|
+
)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### Cooldowns
|
|
92
|
+
|
|
93
|
+
When using retry logic, it may be necessary to introduce a cooldown period
|
|
94
|
+
between retries to prevent overwhelming the remote system. By default,
|
|
95
|
+
`withRetry` will retry immediately. However, you can provide a custom
|
|
96
|
+
`retryDelay` function to introduce a delay before each retry attempt. The
|
|
97
|
+
function should return a promise that resolves after the desired delay.
|
|
45
98
|
|
|
46
|
-
|
|
99
|
+
`breaker-box` offers helper functions to generate retry delays:
|
|
100
|
+
|
|
101
|
+
- `delayMs(ms: number)`: Returns a promise that resolves after the specified
|
|
102
|
+
number of milliseconds.
|
|
103
|
+
- `useExponentialBackoff(maxSeconds: number)`: Returns a function that
|
|
104
|
+
calculates the delay using exponential backoff.
|
|
105
|
+
|
|
106
|
+
- `useFibonacciBackoff(maxSeconds: number)`: Returns a function that calculates
|
|
107
|
+
the delay using Fibonacci sequence.
|
|
47
108
|
|
|
48
109
|
```typescript
|
|
49
110
|
import {
|
|
50
111
|
createCircuitBreaker,
|
|
51
|
-
|
|
112
|
+
delayMs,
|
|
52
113
|
useExponentialBackoff,
|
|
53
114
|
useFibonacciBackoff,
|
|
115
|
+
withRetry,
|
|
54
116
|
} from "breaker-box"
|
|
55
117
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
118
|
+
const protectedApiCall1 = createCircuitBreaker(
|
|
119
|
+
withRetry(unreliableApiCall, {
|
|
120
|
+
maxAttempts: 3,
|
|
121
|
+
retryDelay: (attempt, signal) => delayMs(1_000, signal),
|
|
122
|
+
}),
|
|
59
123
|
)
|
|
60
124
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
125
|
+
const protectedApiCall2 = createCircuitBreaker(
|
|
126
|
+
withRetry(unreliableApiCall, {
|
|
127
|
+
maxAttempts: 3,
|
|
128
|
+
retryDelay: useExponentialBackoff(60),
|
|
129
|
+
}),
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
const protectedApiCall3 = createCircuitBreaker(
|
|
133
|
+
withRetry(unreliableApiCall, {
|
|
134
|
+
maxAttempts: 3,
|
|
135
|
+
retryDelay: useFibonacciBackoff(60),
|
|
136
|
+
}),
|
|
64
137
|
)
|
|
65
138
|
```
|
|
66
139
|
|
|
67
|
-
###
|
|
140
|
+
### Complete Example
|
|
68
141
|
|
|
69
|
-
|
|
142
|
+
The optimal composition should look like this: Circuit Breaker -> Retry -> Timeout -> Implementation. However, you may compose it in any order you prefer as long as you understand the behavior.
|
|
70
143
|
|
|
71
144
|
```typescript
|
|
72
145
|
import {
|
|
73
146
|
createCircuitBreaker,
|
|
147
|
+
useExponentialBackoff,
|
|
74
148
|
withRetry,
|
|
75
149
|
withTimeout,
|
|
76
|
-
useExponentialBackoff,
|
|
77
150
|
} from "breaker-box"
|
|
78
151
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
retryDelay: useExponentialBackoff(10),
|
|
86
|
-
shouldRetry: (error) => !error.message.includes("404"), // Don't retry 404s
|
|
87
|
-
})
|
|
88
|
-
|
|
89
|
-
// 3. Add circuit breaker (outermost - prevents cascading failures)
|
|
90
|
-
const protectedApiCall = createCircuitBreaker(retryCall, {
|
|
91
|
-
errorThreshold: 0.5,
|
|
92
|
-
minimumCandidates: 5,
|
|
93
|
-
})
|
|
152
|
+
const protectedApiCall = createCircuitBreaker(
|
|
153
|
+
withRetry(withTimeout(unreliableApiCall, 4_000), {
|
|
154
|
+
maxAttempts: 3,
|
|
155
|
+
retryDelay: useExponentialBackoff(60),
|
|
156
|
+
}),
|
|
157
|
+
)
|
|
94
158
|
```
|
|
95
159
|
|
|
96
|
-
|
|
160
|
+
## Observability
|
|
161
|
+
|
|
162
|
+
The following callbacks are available:
|
|
97
163
|
|
|
98
164
|
```typescript
|
|
99
165
|
const protectedFunction = createCircuitBreaker(unreliableApiCall, {
|
|
@@ -107,20 +173,29 @@ const protectedFunction = createCircuitBreaker(unreliableApiCall, {
|
|
|
107
173
|
console.log("🔴 Circuit opened due to:", cause.message)
|
|
108
174
|
},
|
|
109
175
|
})
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
The following methods can retrieve information about the circuit breaker:
|
|
110
179
|
|
|
111
|
-
|
|
180
|
+
```typescript
|
|
181
|
+
// Check current state: "closed", "open", "halfOpen"
|
|
112
182
|
console.log("Current state:", protectedFunction.getState())
|
|
113
|
-
|
|
183
|
+
|
|
184
|
+
// Check failure rate: Number between 0 and 1
|
|
185
|
+
console.log("Failure rate:", protectedFunction.getFailureRate())
|
|
186
|
+
|
|
187
|
+
// Get the last error that caused the circuit to open: undefined or Error object
|
|
188
|
+
console.log("Last error:", protectedFunction.getLatestError())
|
|
114
189
|
```
|
|
115
190
|
|
|
116
|
-
|
|
191
|
+
## Cleanup
|
|
117
192
|
|
|
118
193
|
```typescript
|
|
119
194
|
// Clean up resources when shutting down
|
|
120
195
|
protectedFunction.dispose()
|
|
121
196
|
```
|
|
122
197
|
|
|
123
|
-
## API
|
|
198
|
+
## API Reference
|
|
124
199
|
|
|
125
200
|
### `createCircuitBreaker(fn, options?)`
|
|
126
201
|
|
|
@@ -130,11 +205,11 @@ Creates a circuit breaker around the provided async function.
|
|
|
130
205
|
|
|
131
206
|
- `fn`: The async function to protect
|
|
132
207
|
- `options`: Configuration object (optional)
|
|
133
|
-
- `errorIsFailure`: Function to determine if an error
|
|
208
|
+
- `errorIsFailure`: Function to determine if an error is a non-retryable failure; when true, the error is thrown immediately without counting toward metrics (default: `() => false`)
|
|
134
209
|
- `errorThreshold`: Percentage (0-1) of errors that triggers circuit opening (default: `0`)
|
|
135
210
|
- `errorWindow`: Time window in ms for tracking errors (default: `10_000`)
|
|
136
|
-
- `fallback`: Function to call when circuit is open (default: undefined)
|
|
137
|
-
- `minimumCandidates`: Minimum calls before calculating error rate (default: `
|
|
211
|
+
- `fallback`: Function to call when an error occurs or circuit is open (default: undefined)
|
|
212
|
+
- `minimumCandidates`: Minimum calls before calculating error rate (default: `1`)
|
|
138
213
|
- `onClose`: Function called when circuit closes (default: undefined)
|
|
139
214
|
- `onHalfOpen`: Function called when circuit enters half-open state (default: undefined)
|
|
140
215
|
- `onOpen`: Function called when circuit opens (default: undefined)
|
|
@@ -145,6 +220,7 @@ Creates a circuit breaker around the provided async function.
|
|
|
145
220
|
A function with the same signature as `fn` and additional methods:
|
|
146
221
|
|
|
147
222
|
- `.dispose(message?)`: Clean up resources and reject future calls
|
|
223
|
+
- `.getFailureRate()`: Returns the current failure rate (0-1) or 0 if fewer than `minimumCandidates` calls have been made
|
|
148
224
|
- `.getLatestError()`: Returns the error which triggered the circuit breaker
|
|
149
225
|
- `.getState()`: Returns current circuit state (`'closed'`, `'open'`, `'halfOpen'`)
|
|
150
226
|
|
|
@@ -154,11 +230,13 @@ A function with the same signature as `fn` and additional methods:
|
|
|
154
230
|
|
|
155
231
|
Wraps a function with retry logic. Failures will be retried according to the provided options.
|
|
156
232
|
|
|
157
|
-
**
|
|
233
|
+
**Parameters:**
|
|
158
234
|
|
|
159
|
-
- `
|
|
160
|
-
- `
|
|
161
|
-
- `
|
|
235
|
+
- `fn`: The async function to wrap with retry logic
|
|
236
|
+
- `options`: Configuration object (optional)
|
|
237
|
+
- `maxAttempts`: Maximum number of attempts (default: `3`)
|
|
238
|
+
- `retryDelay`: Function `(attempt: number, signal: AbortSignal) => Promise<void>` for delay before retry (default: immediate)
|
|
239
|
+
- `shouldRetry`: Function `(error: unknown, attempt: number) => boolean` to determine if error should be retried (default: `() => true`)
|
|
162
240
|
|
|
163
241
|
**Example:**
|
|
164
242
|
|
|
@@ -170,33 +248,59 @@ const retryCall = withRetry(apiCall, {
|
|
|
170
248
|
})
|
|
171
249
|
```
|
|
172
250
|
|
|
251
|
+
#### `withTimeout(fn, timeoutMs, message?)`
|
|
252
|
+
|
|
253
|
+
Wraps a function with a timeout. Rejects with `Error(message)` if execution exceeds `timeoutMs`.
|
|
254
|
+
|
|
255
|
+
**Parameters:**
|
|
256
|
+
|
|
257
|
+
- `fn`: The async function to wrap with timeout
|
|
258
|
+
- `timeoutMs`: Timeout in milliseconds
|
|
259
|
+
- `message`: Error message to use when timeout occurs (default: `"ERR_CIRCUIT_BREAKER_TIMEOUT"`)
|
|
260
|
+
|
|
173
261
|
#### `useExponentialBackoff(maxSeconds)`
|
|
174
262
|
|
|
175
263
|
Returns a retry delay function that implements exponential backoff (2^n seconds, capped at maxSeconds).
|
|
176
264
|
|
|
265
|
+
**Parameters:**
|
|
266
|
+
|
|
267
|
+
- `maxSeconds`: Maximum delay in seconds before capping
|
|
268
|
+
|
|
269
|
+
**Returns:** Function `(attempt: number, signal: AbortSignal) => Promise<void>`
|
|
270
|
+
|
|
177
271
|
#### `useFibonacciBackoff(maxSeconds)`
|
|
178
272
|
|
|
179
273
|
Returns a retry delay function that implements Fibonacci backoff (Fibonacci sequence in seconds, capped at maxSeconds).
|
|
180
274
|
|
|
181
|
-
|
|
275
|
+
**Parameters:**
|
|
182
276
|
|
|
183
|
-
|
|
277
|
+
- `maxSeconds`: Maximum delay in seconds before capping
|
|
184
278
|
|
|
185
|
-
|
|
279
|
+
**Returns:** Function `(attempt: number, signal: AbortSignal) => Promise<void>`
|
|
186
280
|
|
|
187
|
-
|
|
281
|
+
#### `delayMs(ms, signal?)`
|
|
188
282
|
|
|
189
|
-
|
|
190
|
-
npm run build
|
|
191
|
-
```
|
|
283
|
+
Returns a promise that resolves after the specified number of milliseconds. Supports optional abort signal for cancellation.
|
|
192
284
|
|
|
193
|
-
|
|
285
|
+
**Parameters:**
|
|
194
286
|
|
|
195
|
-
|
|
196
|
-
|
|
287
|
+
- `ms`: Delay in milliseconds
|
|
288
|
+
- `signal`: Optional AbortSignal for cancellation
|
|
197
289
|
|
|
198
|
-
|
|
199
|
-
|
|
290
|
+
**Returns:** `Promise<void>`
|
|
291
|
+
|
|
292
|
+
## Development Commands
|
|
293
|
+
|
|
294
|
+
| Command | Purpose |
|
|
295
|
+
| --------------------------- | -------------------------------------- |
|
|
296
|
+
| `npm run build` | Build with pkgroll (CJS + ESM + types) |
|
|
297
|
+
| `npm run dev` | Run tests in watch mode (vitest) |
|
|
298
|
+
| `npm run format` | Format with Prettier |
|
|
299
|
+
| `npm run test:coverage` | Run tests with coverage |
|
|
300
|
+
| `npm test` | Run tests once |
|
|
301
|
+
| `npx tsc --noEmit` | Type-check without emit |
|
|
302
|
+
| `npx vitest index.test.ts` | Run single test file |
|
|
303
|
+
| `npx vitest -t "test name"` | Run specific test by name |
|
|
200
304
|
|
|
201
305
|
## Contributing
|
|
202
306
|
|
package/dist/index.cjs
CHANGED
|
@@ -3,29 +3,43 @@
|
|
|
3
3
|
function assert(value, message) {
|
|
4
4
|
if (!value) throw new TypeError(message);
|
|
5
5
|
}
|
|
6
|
+
/* v8 ignore next -- @preserve */
|
|
6
7
|
const assertNever = (val, msg = "Unexpected value") => {
|
|
7
8
|
throw new TypeError(`${msg}: ${val}`);
|
|
8
9
|
};
|
|
9
|
-
const delayMs = (ms
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
signal.
|
|
19
|
-
|
|
20
|
-
|
|
10
|
+
const delayMs = (ms, signal) => {
|
|
11
|
+
if (!Number.isFinite(ms) || ms < 0) {
|
|
12
|
+
throw new RangeError(
|
|
13
|
+
`"ms" must be a finite, non-negative number (received ${ms})`
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
return signal ? new Promise((resolve, reject) => {
|
|
17
|
+
signal.throwIfAborted();
|
|
18
|
+
const timer = setTimeout(() => {
|
|
19
|
+
signal.removeEventListener("abort", onAbort);
|
|
20
|
+
resolve();
|
|
21
|
+
}, ms);
|
|
22
|
+
const onAbort = () => {
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
reject(signal.reason);
|
|
25
|
+
};
|
|
26
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
27
|
+
}) : new Promise((next) => setTimeout(next, ms));
|
|
21
28
|
};
|
|
29
|
+
const abortable = (signal, pending) => new Promise((resolve, reject) => {
|
|
30
|
+
signal.throwIfAborted();
|
|
31
|
+
const onAbort = () => reject(signal.reason);
|
|
32
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
33
|
+
Promise.resolve(pending).then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
34
|
+
});
|
|
22
35
|
|
|
23
36
|
function parseOptions(options) {
|
|
24
37
|
const {
|
|
25
38
|
errorIsFailure = () => false,
|
|
26
39
|
errorThreshold = 0,
|
|
27
40
|
errorWindow = 1e4,
|
|
28
|
-
|
|
41
|
+
fallback,
|
|
42
|
+
minimumCandidates = 1,
|
|
29
43
|
onClose,
|
|
30
44
|
onHalfOpen,
|
|
31
45
|
onOpen,
|
|
@@ -43,6 +57,10 @@ function parseOptions(options) {
|
|
|
43
57
|
errorWindow >= 1e3,
|
|
44
58
|
`"errorWindow" must be milliseconds of at least 1 second (received ${errorWindow})`
|
|
45
59
|
);
|
|
60
|
+
assert(
|
|
61
|
+
!fallback || typeof fallback === "function",
|
|
62
|
+
`"fallback" must be a function (received ${typeof fallback})`
|
|
63
|
+
);
|
|
46
64
|
assert(
|
|
47
65
|
minimumCandidates >= 1,
|
|
48
66
|
`"minimumCandidates" must be greater than 0 (received ${minimumCandidates})`
|
|
@@ -82,18 +100,18 @@ function parseOptions(options) {
|
|
|
82
100
|
const disposeKey = Symbol("disposeKey");
|
|
83
101
|
|
|
84
102
|
function useExponentialBackoff(maxSeconds) {
|
|
85
|
-
return function exponentialBackoff(attempt) {
|
|
103
|
+
return function exponentialBackoff(attempt, signal) {
|
|
86
104
|
const num = Math.max(attempt - 2, 0);
|
|
87
105
|
const delay = Math.min(2 ** num, maxSeconds);
|
|
88
|
-
return delayMs(delay * 1e3);
|
|
106
|
+
return delayMs(delay * 1e3, signal);
|
|
89
107
|
};
|
|
90
108
|
}
|
|
91
109
|
const sqrt5 = /* @__PURE__ */ Math.sqrt(5);
|
|
92
110
|
const binet = (n) => Math.round(((1 + sqrt5) ** n - (1 - sqrt5) ** n) / (2 ** n * sqrt5));
|
|
93
111
|
function useFibonacciBackoff(maxSeconds) {
|
|
94
|
-
return function fibonacciBackoff(attempt) {
|
|
112
|
+
return function fibonacciBackoff(attempt, signal) {
|
|
95
113
|
const delay = Math.min(binet(attempt), maxSeconds);
|
|
96
|
-
return delayMs(delay * 1e3);
|
|
114
|
+
return delayMs(delay * 1e3, signal);
|
|
97
115
|
};
|
|
98
116
|
}
|
|
99
117
|
function withRetry(main, options = {}) {
|
|
@@ -105,53 +123,40 @@ function withRetry(main, options = {}) {
|
|
|
105
123
|
assert(maxAttempts >= 1, "maxAttempts must be a number greater than 0");
|
|
106
124
|
const controller = new AbortController();
|
|
107
125
|
const { signal } = controller;
|
|
108
|
-
async function
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
126
|
+
async function withRetryFunction(...args) {
|
|
127
|
+
let attempt = 1;
|
|
128
|
+
while (true) {
|
|
129
|
+
try {
|
|
130
|
+
return await main(...args);
|
|
131
|
+
} catch (cause) {
|
|
132
|
+
if (attempt >= maxAttempts) {
|
|
133
|
+
throw new Error(`ERR_CIRCUIT_BREAKER_MAX_ATTEMPTS (${maxAttempts})`, {
|
|
134
|
+
cause
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
if (!shouldRetry(cause, attempt)) throw cause;
|
|
138
|
+
}
|
|
139
|
+
attempt++;
|
|
140
|
+
await abortable(signal, retryDelay(attempt, signal));
|
|
119
141
|
}
|
|
120
142
|
}
|
|
121
|
-
return Object.assign(
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
[disposeKey]: (disposeMessage = "ERR_CIRCUIT_BREAKER_DISPOSED") => {
|
|
127
|
-
const reason = new ReferenceError(disposeMessage);
|
|
128
|
-
main[disposeKey]?.(disposeMessage);
|
|
129
|
-
controller.abort(reason);
|
|
130
|
-
}
|
|
143
|
+
return Object.assign(withRetryFunction, {
|
|
144
|
+
[disposeKey]: (disposeMessage = "ERR_CIRCUIT_BREAKER_DISPOSED") => {
|
|
145
|
+
const reason = new ReferenceError(disposeMessage);
|
|
146
|
+
main[disposeKey]?.(disposeMessage);
|
|
147
|
+
controller.abort(reason);
|
|
131
148
|
}
|
|
132
|
-
);
|
|
149
|
+
});
|
|
133
150
|
}
|
|
134
151
|
function withTimeout(main, timeoutMs, timeoutMessage = "ERR_CIRCUIT_BREAKER_TIMEOUT") {
|
|
135
152
|
const error = new Error(timeoutMessage);
|
|
136
153
|
const controller = new AbortController();
|
|
137
154
|
const { signal } = controller;
|
|
138
155
|
function withTimeoutFunction(...args) {
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
clearTimeout(timer);
|
|
144
|
-
signal.removeEventListener("abort", teardown);
|
|
145
|
-
}),
|
|
146
|
-
new Promise((_, reject) => {
|
|
147
|
-
teardown = () => {
|
|
148
|
-
clearTimeout(timer);
|
|
149
|
-
reject(signal.reason);
|
|
150
|
-
};
|
|
151
|
-
timer = setTimeout(reject, timeoutMs, error);
|
|
152
|
-
signal.addEventListener("abort", teardown, { once: true });
|
|
153
|
-
})
|
|
154
|
-
]);
|
|
156
|
+
return new Promise((resolve, reject) => {
|
|
157
|
+
const timer = setTimeout(reject, timeoutMs, error);
|
|
158
|
+
abortable(signal, main(...args)).then(resolve, reject).finally(() => clearTimeout(timer));
|
|
159
|
+
});
|
|
155
160
|
}
|
|
156
161
|
return Object.assign(withTimeoutFunction, {
|
|
157
162
|
[disposeKey]: (disposeMessage = "ERR_CIRCUIT_BREAKER_DISPOSED") => {
|
|
@@ -177,20 +182,22 @@ function createCircuitBreaker(main, options = {}) {
|
|
|
177
182
|
const history = /* @__PURE__ */ new Map();
|
|
178
183
|
const signal = controller.signal;
|
|
179
184
|
let failureCause;
|
|
185
|
+
let failureRate = 0;
|
|
180
186
|
let fallback = options.fallback || (() => Promise.reject(failureCause));
|
|
181
187
|
let halfOpenPending;
|
|
182
188
|
let resetTimer;
|
|
183
189
|
let state = "closed";
|
|
184
190
|
function clearFailure() {
|
|
185
191
|
failureCause = void 0;
|
|
192
|
+
clearTimeout(resetTimer);
|
|
193
|
+
resetTimer = void 0;
|
|
186
194
|
}
|
|
187
195
|
function closeCircuit() {
|
|
188
196
|
state = "closed";
|
|
189
197
|
clearFailure();
|
|
190
|
-
|
|
191
|
-
onClose?.();
|
|
198
|
+
if (onClose) setImmediate(onClose);
|
|
192
199
|
}
|
|
193
|
-
function
|
|
200
|
+
function calculateFailureRate() {
|
|
194
201
|
let failures = 0;
|
|
195
202
|
let total = 0;
|
|
196
203
|
for (const { status } of history.values()) {
|
|
@@ -201,14 +208,16 @@ function createCircuitBreaker(main, options = {}) {
|
|
|
201
208
|
return failures / total;
|
|
202
209
|
}
|
|
203
210
|
function openCircuit(cause) {
|
|
204
|
-
failureCause = cause;
|
|
205
211
|
state = "open";
|
|
212
|
+
failureCause = cause;
|
|
206
213
|
clearTimeout(resetTimer);
|
|
207
|
-
resetTimer = setTimeout(() =>
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
214
|
+
resetTimer = setTimeout(() => halfOpenCircuit(), resetAfter);
|
|
215
|
+
if (onOpen) setImmediate(onOpen, cause);
|
|
216
|
+
}
|
|
217
|
+
function halfOpenCircuit() {
|
|
218
|
+
state = "halfOpen";
|
|
219
|
+
halfOpenPending = void 0;
|
|
220
|
+
if (onHalfOpen) setImmediate(onHalfOpen);
|
|
212
221
|
}
|
|
213
222
|
function createHistoryItem(pending) {
|
|
214
223
|
const entry = { status: "pending", timer: void 0 };
|
|
@@ -219,14 +228,15 @@ function createCircuitBreaker(main, options = {}) {
|
|
|
219
228
|
};
|
|
220
229
|
signal.addEventListener("abort", teardown, { once: true });
|
|
221
230
|
const settle = (value) => {
|
|
222
|
-
if (signal.aborted) return;
|
|
231
|
+
if (signal.aborted) return 0;
|
|
223
232
|
entry.status = value;
|
|
224
233
|
entry.timer = setTimeout(teardown, errorWindow);
|
|
234
|
+
return failureRate = calculateFailureRate();
|
|
225
235
|
};
|
|
226
236
|
history.set(pending, entry);
|
|
227
237
|
return { pending, settle, teardown };
|
|
228
238
|
}
|
|
229
|
-
function execute(args) {
|
|
239
|
+
function execute(...args) {
|
|
230
240
|
if (state === "closed") {
|
|
231
241
|
const { pending, settle, teardown } = createHistoryItem(main(...args));
|
|
232
242
|
return pending.then(
|
|
@@ -240,7 +250,7 @@ function createCircuitBreaker(main, options = {}) {
|
|
|
240
250
|
throw cause;
|
|
241
251
|
}
|
|
242
252
|
settle("rejected");
|
|
243
|
-
if (failureRate
|
|
253
|
+
if (failureRate > errorThreshold) openCircuit(cause);
|
|
244
254
|
return fallback(...args);
|
|
245
255
|
}
|
|
246
256
|
);
|
|
@@ -260,20 +270,25 @@ function createCircuitBreaker(main, options = {}) {
|
|
|
260
270
|
}
|
|
261
271
|
);
|
|
262
272
|
}
|
|
273
|
+
/* v8 ignore next -- @preserve */
|
|
263
274
|
return assertNever(state);
|
|
264
275
|
}
|
|
265
|
-
return Object.assign(
|
|
276
|
+
return Object.assign(execute, {
|
|
266
277
|
dispose: (disposeMessage = "ERR_CIRCUIT_BREAKER_DISPOSED") => {
|
|
278
|
+
/* v8 ignore if -- @preserve */
|
|
279
|
+
if (signal.aborted) return;
|
|
267
280
|
const reason = new ReferenceError(disposeMessage);
|
|
268
281
|
main[disposeKey]?.(disposeMessage);
|
|
269
282
|
clearFailure();
|
|
270
|
-
|
|
283
|
+
halfOpenPending = void 0;
|
|
271
284
|
history.forEach((entry) => clearTimeout(entry.timer));
|
|
272
285
|
history.clear();
|
|
286
|
+
failureRate = 0;
|
|
273
287
|
fallback = () => Promise.reject(reason);
|
|
274
288
|
state = "open";
|
|
275
289
|
controller.abort(reason);
|
|
276
290
|
},
|
|
291
|
+
getFailureRate: () => failureRate,
|
|
277
292
|
getLatestError: () => failureCause,
|
|
278
293
|
getState: () => state
|
|
279
294
|
});
|