breaker-box 4.2.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 +189 -46
- package/dist/index.cjs +120 -59
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +158 -50
- package/dist/index.d.mts +158 -50
- package/dist/index.mjs +120 -60
- package/dist/index.mjs.map +1 -1
- package/package.json +18 -12
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"
|
|
@@ -27,10 +25,11 @@ async function unreliableApiCall(data: string) {
|
|
|
27
25
|
}
|
|
28
26
|
|
|
29
27
|
const protectedApiCall = createCircuitBreaker(unreliableApiCall, {
|
|
30
|
-
errorIsFailure: (error) => error.message.includes("404"), // Don't retry 404s
|
|
31
28
|
errorThreshold: 0.5, // Open circuit when 50% of calls fail
|
|
32
29
|
errorWindow: 10_000, // Track errors over 10 second window
|
|
33
|
-
|
|
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
|
|
34
33
|
resetAfter: 30_000, // Try again after 30 seconds
|
|
35
34
|
})
|
|
36
35
|
|
|
@@ -42,66 +41,161 @@ try {
|
|
|
42
41
|
}
|
|
43
42
|
```
|
|
44
43
|
|
|
45
|
-
|
|
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.
|
|
98
|
+
|
|
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.
|
|
46
108
|
|
|
47
109
|
```typescript
|
|
48
110
|
import {
|
|
49
111
|
createCircuitBreaker,
|
|
112
|
+
delayMs,
|
|
50
113
|
useExponentialBackoff,
|
|
51
114
|
useFibonacciBackoff,
|
|
115
|
+
withRetry,
|
|
52
116
|
} from "breaker-box"
|
|
53
117
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
118
|
+
const protectedApiCall1 = createCircuitBreaker(
|
|
119
|
+
withRetry(unreliableApiCall, {
|
|
120
|
+
maxAttempts: 3,
|
|
121
|
+
retryDelay: (attempt, signal) => delayMs(1_000, signal),
|
|
122
|
+
}),
|
|
123
|
+
)
|
|
58
124
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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
|
+
}),
|
|
137
|
+
)
|
|
63
138
|
```
|
|
64
139
|
|
|
65
|
-
###
|
|
140
|
+
### Complete Example
|
|
141
|
+
|
|
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.
|
|
66
143
|
|
|
67
144
|
```typescript
|
|
68
|
-
import {
|
|
145
|
+
import {
|
|
146
|
+
createCircuitBreaker,
|
|
147
|
+
useExponentialBackoff,
|
|
148
|
+
withRetry,
|
|
149
|
+
withTimeout,
|
|
150
|
+
} from "breaker-box"
|
|
69
151
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
152
|
+
const protectedApiCall = createCircuitBreaker(
|
|
153
|
+
withRetry(withTimeout(unreliableApiCall, 4_000), {
|
|
154
|
+
maxAttempts: 3,
|
|
155
|
+
retryDelay: useExponentialBackoff(60),
|
|
156
|
+
}),
|
|
75
157
|
)
|
|
76
|
-
|
|
77
|
-
const protectedApiCall = createCircuitBreaker(timeoutProtectedCall, {})
|
|
78
158
|
```
|
|
79
159
|
|
|
80
|
-
|
|
160
|
+
## Observability
|
|
161
|
+
|
|
162
|
+
The following callbacks are available:
|
|
81
163
|
|
|
82
164
|
```typescript
|
|
83
165
|
const protectedFunction = createCircuitBreaker(unreliableApiCall, {
|
|
84
166
|
onClose: () => {
|
|
85
|
-
console.log("Circuit closed - normal operation resumed")
|
|
167
|
+
console.log("🟢 Circuit closed - normal operation resumed")
|
|
168
|
+
},
|
|
169
|
+
onHalfOpen: () => {
|
|
170
|
+
console.log("🟡 Circuit half-opened - waiting for success")
|
|
86
171
|
},
|
|
87
172
|
onOpen: (cause) => {
|
|
88
|
-
console.log("Circuit opened due to:", cause.message)
|
|
173
|
+
console.log("🔴 Circuit opened due to:", cause.message)
|
|
89
174
|
},
|
|
90
175
|
})
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
The following methods can retrieve information about the circuit breaker:
|
|
91
179
|
|
|
92
|
-
|
|
180
|
+
```typescript
|
|
181
|
+
// Check current state: "closed", "open", "halfOpen"
|
|
93
182
|
console.log("Current state:", protectedFunction.getState())
|
|
94
|
-
|
|
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())
|
|
95
189
|
```
|
|
96
190
|
|
|
97
|
-
|
|
191
|
+
## Cleanup
|
|
98
192
|
|
|
99
193
|
```typescript
|
|
100
194
|
// Clean up resources when shutting down
|
|
101
195
|
protectedFunction.dispose()
|
|
102
196
|
```
|
|
103
197
|
|
|
104
|
-
## API
|
|
198
|
+
## API Reference
|
|
105
199
|
|
|
106
200
|
### `createCircuitBreaker(fn, options?)`
|
|
107
201
|
|
|
@@ -111,53 +205,102 @@ Creates a circuit breaker around the provided async function.
|
|
|
111
205
|
|
|
112
206
|
- `fn`: The async function to protect
|
|
113
207
|
- `options`: Configuration object (optional)
|
|
114
|
-
- `errorIsFailure`: Function to determine if an error is non-retryable (default: `() => false`)
|
|
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`)
|
|
115
209
|
- `errorThreshold`: Percentage (0-1) of errors that triggers circuit opening (default: `0`)
|
|
116
210
|
- `errorWindow`: Time window in ms for tracking errors (default: `10_000`)
|
|
117
|
-
- `fallback`: Function to call when circuit is open (default: undefined)
|
|
118
|
-
- `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`)
|
|
119
213
|
- `onClose`: Function called when circuit closes (default: undefined)
|
|
214
|
+
- `onHalfOpen`: Function called when circuit enters half-open state (default: undefined)
|
|
120
215
|
- `onOpen`: Function called when circuit opens (default: undefined)
|
|
121
216
|
- `resetAfter`: Milliseconds to wait before trying half-open (default: `30_000`)
|
|
122
|
-
- `retryDelay`: Function returning promise for retry delays (default: immediate retry)
|
|
123
217
|
|
|
124
218
|
#### Returns
|
|
125
219
|
|
|
126
220
|
A function with the same signature as `fn` and additional methods:
|
|
127
221
|
|
|
128
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
|
|
129
224
|
- `.getLatestError()`: Returns the error which triggered the circuit breaker
|
|
130
225
|
- `.getState()`: Returns current circuit state (`'closed'`, `'open'`, `'halfOpen'`)
|
|
131
226
|
|
|
132
227
|
### Helper Functions
|
|
133
228
|
|
|
229
|
+
#### `withRetry(fn, options?)`
|
|
230
|
+
|
|
231
|
+
Wraps a function with retry logic. Failures will be retried according to the provided options.
|
|
232
|
+
|
|
233
|
+
**Parameters:**
|
|
234
|
+
|
|
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`)
|
|
240
|
+
|
|
241
|
+
**Example:**
|
|
242
|
+
|
|
243
|
+
```typescript
|
|
244
|
+
const retryCall = withRetry(apiCall, {
|
|
245
|
+
maxAttempts: 5,
|
|
246
|
+
retryDelay: useExponentialBackoff(30),
|
|
247
|
+
shouldRetry: (error) => error.statusCode !== 404,
|
|
248
|
+
})
|
|
249
|
+
```
|
|
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
|
+
|
|
134
261
|
#### `useExponentialBackoff(maxSeconds)`
|
|
135
262
|
|
|
136
263
|
Returns a retry delay function that implements exponential backoff (2^n seconds, capped at maxSeconds).
|
|
137
264
|
|
|
265
|
+
**Parameters:**
|
|
266
|
+
|
|
267
|
+
- `maxSeconds`: Maximum delay in seconds before capping
|
|
268
|
+
|
|
269
|
+
**Returns:** Function `(attempt: number, signal: AbortSignal) => Promise<void>`
|
|
270
|
+
|
|
138
271
|
#### `useFibonacciBackoff(maxSeconds)`
|
|
139
272
|
|
|
140
273
|
Returns a retry delay function that implements Fibonacci backoff (Fibonacci sequence in seconds, capped at maxSeconds).
|
|
141
274
|
|
|
142
|
-
|
|
275
|
+
**Parameters:**
|
|
143
276
|
|
|
144
|
-
|
|
277
|
+
- `maxSeconds`: Maximum delay in seconds before capping
|
|
145
278
|
|
|
146
|
-
|
|
279
|
+
**Returns:** Function `(attempt: number, signal: AbortSignal) => Promise<void>`
|
|
147
280
|
|
|
148
|
-
|
|
281
|
+
#### `delayMs(ms, signal?)`
|
|
149
282
|
|
|
150
|
-
|
|
151
|
-
npm run build
|
|
152
|
-
```
|
|
283
|
+
Returns a promise that resolves after the specified number of milliseconds. Supports optional abort signal for cancellation.
|
|
153
284
|
|
|
154
|
-
|
|
285
|
+
**Parameters:**
|
|
155
286
|
|
|
156
|
-
|
|
157
|
-
|
|
287
|
+
- `ms`: Delay in milliseconds
|
|
288
|
+
- `signal`: Optional AbortSignal for cancellation
|
|
158
289
|
|
|
159
|
-
|
|
160
|
-
|
|
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 |
|
|
161
304
|
|
|
162
305
|
## Contributing
|
|
163
306
|
|
package/dist/index.cjs
CHANGED
|
@@ -3,34 +3,47 @@
|
|
|
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,
|
|
32
|
-
resetAfter = 3e4
|
|
33
|
-
retryDelay = () => void 0
|
|
46
|
+
resetAfter = 3e4
|
|
34
47
|
} = options;
|
|
35
48
|
assert(
|
|
36
49
|
typeof errorIsFailure === "function",
|
|
@@ -44,6 +57,10 @@ function parseOptions(options) {
|
|
|
44
57
|
errorWindow >= 1e3,
|
|
45
58
|
`"errorWindow" must be milliseconds of at least 1 second (received ${errorWindow})`
|
|
46
59
|
);
|
|
60
|
+
assert(
|
|
61
|
+
!fallback || typeof fallback === "function",
|
|
62
|
+
`"fallback" must be a function (received ${typeof fallback})`
|
|
63
|
+
);
|
|
47
64
|
assert(
|
|
48
65
|
minimumCandidates >= 1,
|
|
49
66
|
`"minimumCandidates" must be greater than 0 (received ${minimumCandidates})`
|
|
@@ -68,10 +85,6 @@ function parseOptions(options) {
|
|
|
68
85
|
resetAfter >= errorWindow,
|
|
69
86
|
`"resetAfter" must be greater than or equal to "errorWindow" (received ${resetAfter}, expected >= ${errorWindow})`
|
|
70
87
|
);
|
|
71
|
-
assert(
|
|
72
|
-
typeof retryDelay === "function",
|
|
73
|
-
`"retryDelay" must be a function (received ${typeof retryDelay})`
|
|
74
|
-
);
|
|
75
88
|
return {
|
|
76
89
|
errorIsFailure,
|
|
77
90
|
errorThreshold,
|
|
@@ -80,37 +93,78 @@ function parseOptions(options) {
|
|
|
80
93
|
onClose,
|
|
81
94
|
onHalfOpen,
|
|
82
95
|
onOpen,
|
|
83
|
-
resetAfter
|
|
84
|
-
retryDelay
|
|
96
|
+
resetAfter
|
|
85
97
|
};
|
|
86
98
|
}
|
|
87
99
|
|
|
100
|
+
const disposeKey = Symbol("disposeKey");
|
|
101
|
+
|
|
88
102
|
function useExponentialBackoff(maxSeconds) {
|
|
89
|
-
return function exponentialBackoff(attempt) {
|
|
103
|
+
return function exponentialBackoff(attempt, signal) {
|
|
90
104
|
const num = Math.max(attempt - 2, 0);
|
|
91
105
|
const delay = Math.min(2 ** num, maxSeconds);
|
|
92
|
-
return delayMs(delay * 1e3);
|
|
106
|
+
return delayMs(delay * 1e3, signal);
|
|
93
107
|
};
|
|
94
108
|
}
|
|
95
109
|
const sqrt5 = /* @__PURE__ */ Math.sqrt(5);
|
|
96
110
|
const binet = (n) => Math.round(((1 + sqrt5) ** n - (1 - sqrt5) ** n) / (2 ** n * sqrt5));
|
|
97
111
|
function useFibonacciBackoff(maxSeconds) {
|
|
98
|
-
return function fibonacciBackoff(attempt) {
|
|
112
|
+
return function fibonacciBackoff(attempt, signal) {
|
|
99
113
|
const delay = Math.min(binet(attempt), maxSeconds);
|
|
100
|
-
return delayMs(delay * 1e3);
|
|
114
|
+
return delayMs(delay * 1e3, signal);
|
|
101
115
|
};
|
|
102
116
|
}
|
|
117
|
+
function withRetry(main, options = {}) {
|
|
118
|
+
const {
|
|
119
|
+
shouldRetry = () => true,
|
|
120
|
+
maxAttempts = 3,
|
|
121
|
+
retryDelay = () => Promise.resolve()
|
|
122
|
+
} = options;
|
|
123
|
+
assert(maxAttempts >= 1, "maxAttempts must be a number greater than 0");
|
|
124
|
+
const controller = new AbortController();
|
|
125
|
+
const { signal } = controller;
|
|
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));
|
|
141
|
+
}
|
|
142
|
+
}
|
|
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);
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
}
|
|
103
151
|
function withTimeout(main, timeoutMs, timeoutMessage = "ERR_CIRCUIT_BREAKER_TIMEOUT") {
|
|
104
152
|
const error = new Error(timeoutMessage);
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
153
|
+
const controller = new AbortController();
|
|
154
|
+
const { signal } = controller;
|
|
155
|
+
function withTimeoutFunction(...args) {
|
|
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
|
+
});
|
|
160
|
+
}
|
|
161
|
+
return Object.assign(withTimeoutFunction, {
|
|
162
|
+
[disposeKey]: (disposeMessage = "ERR_CIRCUIT_BREAKER_DISPOSED") => {
|
|
163
|
+
const reason = new ReferenceError(disposeMessage);
|
|
164
|
+
main[disposeKey]?.(disposeMessage);
|
|
165
|
+
controller.abort(reason);
|
|
166
|
+
}
|
|
167
|
+
});
|
|
114
168
|
}
|
|
115
169
|
|
|
116
170
|
function createCircuitBreaker(main, options = {}) {
|
|
@@ -122,27 +176,28 @@ function createCircuitBreaker(main, options = {}) {
|
|
|
122
176
|
onClose,
|
|
123
177
|
onHalfOpen,
|
|
124
178
|
onOpen,
|
|
125
|
-
resetAfter
|
|
126
|
-
retryDelay
|
|
179
|
+
resetAfter
|
|
127
180
|
} = parseOptions(options);
|
|
128
181
|
const controller = new AbortController();
|
|
129
182
|
const history = /* @__PURE__ */ new Map();
|
|
130
183
|
const signal = controller.signal;
|
|
131
184
|
let failureCause;
|
|
185
|
+
let failureRate = 0;
|
|
132
186
|
let fallback = options.fallback || (() => Promise.reject(failureCause));
|
|
133
187
|
let halfOpenPending;
|
|
134
188
|
let resetTimer;
|
|
135
189
|
let state = "closed";
|
|
136
190
|
function clearFailure() {
|
|
137
191
|
failureCause = void 0;
|
|
192
|
+
clearTimeout(resetTimer);
|
|
193
|
+
resetTimer = void 0;
|
|
138
194
|
}
|
|
139
195
|
function closeCircuit() {
|
|
140
196
|
state = "closed";
|
|
141
197
|
clearFailure();
|
|
142
|
-
|
|
143
|
-
onClose?.();
|
|
198
|
+
if (onClose) setImmediate(onClose);
|
|
144
199
|
}
|
|
145
|
-
function
|
|
200
|
+
function calculateFailureRate() {
|
|
146
201
|
let failures = 0;
|
|
147
202
|
let total = 0;
|
|
148
203
|
for (const { status } of history.values()) {
|
|
@@ -153,14 +208,16 @@ function createCircuitBreaker(main, options = {}) {
|
|
|
153
208
|
return failures / total;
|
|
154
209
|
}
|
|
155
210
|
function openCircuit(cause) {
|
|
156
|
-
failureCause = cause;
|
|
157
211
|
state = "open";
|
|
212
|
+
failureCause = cause;
|
|
158
213
|
clearTimeout(resetTimer);
|
|
159
|
-
resetTimer = setTimeout(() =>
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
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);
|
|
164
221
|
}
|
|
165
222
|
function createHistoryItem(pending) {
|
|
166
223
|
const entry = { status: "pending", timer: void 0 };
|
|
@@ -169,16 +226,17 @@ function createCircuitBreaker(main, options = {}) {
|
|
|
169
226
|
history.delete(pending);
|
|
170
227
|
signal.removeEventListener("abort", teardown);
|
|
171
228
|
};
|
|
172
|
-
signal.addEventListener("abort", teardown);
|
|
229
|
+
signal.addEventListener("abort", teardown, { once: true });
|
|
173
230
|
const settle = (value) => {
|
|
174
|
-
if (signal.aborted) return;
|
|
231
|
+
if (signal.aborted) return 0;
|
|
175
232
|
entry.status = value;
|
|
176
233
|
entry.timer = setTimeout(teardown, errorWindow);
|
|
234
|
+
return failureRate = calculateFailureRate();
|
|
177
235
|
};
|
|
178
236
|
history.set(pending, entry);
|
|
179
237
|
return { pending, settle, teardown };
|
|
180
238
|
}
|
|
181
|
-
function execute(
|
|
239
|
+
function execute(...args) {
|
|
182
240
|
if (state === "closed") {
|
|
183
241
|
const { pending, settle, teardown } = createHistoryItem(main(...args));
|
|
184
242
|
return pending.then(
|
|
@@ -186,16 +244,14 @@ function createCircuitBreaker(main, options = {}) {
|
|
|
186
244
|
settle("resolved");
|
|
187
245
|
return result;
|
|
188
246
|
},
|
|
189
|
-
|
|
247
|
+
(cause) => {
|
|
190
248
|
if (signal.aborted || errorIsFailure(cause)) {
|
|
191
249
|
teardown();
|
|
192
250
|
throw cause;
|
|
193
251
|
}
|
|
194
252
|
settle("rejected");
|
|
195
|
-
if (failureRate
|
|
196
|
-
|
|
197
|
-
await rejectOnAbort(signal, retryDelay(next, signal));
|
|
198
|
-
return execute(next, args);
|
|
253
|
+
if (failureRate > errorThreshold) openCircuit(cause);
|
|
254
|
+
return fallback(...args);
|
|
199
255
|
}
|
|
200
256
|
);
|
|
201
257
|
} else if (state === "open" || halfOpenPending) {
|
|
@@ -207,28 +263,32 @@ function createCircuitBreaker(main, options = {}) {
|
|
|
207
263
|
closeCircuit();
|
|
208
264
|
return result;
|
|
209
265
|
},
|
|
210
|
-
|
|
266
|
+
(cause) => {
|
|
211
267
|
if (signal.aborted || errorIsFailure(cause)) throw cause;
|
|
212
268
|
openCircuit(cause);
|
|
213
|
-
|
|
214
|
-
await rejectOnAbort(signal, retryDelay(next, signal));
|
|
215
|
-
return execute(next, args);
|
|
269
|
+
return fallback(...args);
|
|
216
270
|
}
|
|
217
271
|
);
|
|
218
272
|
}
|
|
273
|
+
/* v8 ignore next -- @preserve */
|
|
219
274
|
return assertNever(state);
|
|
220
275
|
}
|
|
221
|
-
return Object.assign(
|
|
276
|
+
return Object.assign(execute, {
|
|
222
277
|
dispose: (disposeMessage = "ERR_CIRCUIT_BREAKER_DISPOSED") => {
|
|
278
|
+
/* v8 ignore if -- @preserve */
|
|
279
|
+
if (signal.aborted) return;
|
|
223
280
|
const reason = new ReferenceError(disposeMessage);
|
|
281
|
+
main[disposeKey]?.(disposeMessage);
|
|
224
282
|
clearFailure();
|
|
225
|
-
|
|
283
|
+
halfOpenPending = void 0;
|
|
226
284
|
history.forEach((entry) => clearTimeout(entry.timer));
|
|
227
285
|
history.clear();
|
|
286
|
+
failureRate = 0;
|
|
228
287
|
fallback = () => Promise.reject(reason);
|
|
229
288
|
state = "open";
|
|
230
289
|
controller.abort(reason);
|
|
231
290
|
},
|
|
291
|
+
getFailureRate: () => failureRate,
|
|
232
292
|
getLatestError: () => failureCause,
|
|
233
293
|
getState: () => state
|
|
234
294
|
});
|
|
@@ -238,5 +298,6 @@ exports.createCircuitBreaker = createCircuitBreaker;
|
|
|
238
298
|
exports.delayMs = delayMs;
|
|
239
299
|
exports.useExponentialBackoff = useExponentialBackoff;
|
|
240
300
|
exports.useFibonacciBackoff = useFibonacciBackoff;
|
|
301
|
+
exports.withRetry = withRetry;
|
|
241
302
|
exports.withTimeout = withTimeout;
|
|
242
303
|
//# sourceMappingURL=index.cjs.map
|