breaker-box 5.0.0 → 7.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 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
- minimumCandidates: 6, // Need at least 6 calls before calculating error rate
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
- ### Retry Strategies
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
- The circuit breaker doesn't retry - it only tracks failures and prevents calls when too many fail. Use `withRetry` to add retry logic:
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
- withRetry,
112
+ delayMs,
52
113
  useExponentialBackoff,
53
114
  useFibonacciBackoff,
115
+ withRetry,
54
116
  } from "breaker-box"
55
117
 
56
- // Exponential backoff: 1s, 2s, 4s, 8s, up to 30s max
57
- const protectedWithExponential = createCircuitBreaker(
58
- withRetry(unreliableApiCall, { retryDelay: useExponentialBackoff(30) }),
118
+ const protectedApiCall1 = createCircuitBreaker(
119
+ withRetry(unreliableApiCall, {
120
+ maxAttempts: 3,
121
+ retryDelay: (attempt, signal) => delayMs(1_000, signal),
122
+ }),
59
123
  )
60
124
 
61
- // Fibonacci backoff: 1s, 2s, 3s, 5s, 8s, up to 60s max
62
- const protectedWithFibonacci = createCircuitBreaker(
63
- withRetry(unreliableApiCall, { retryDelay: useFibonacciBackoff(60) }),
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
- ### Timeout Protection
140
+ ### Complete Example
68
141
 
69
- Compose `withTimeout`, `withRetry`, and circuit breaker for complete fault tolerance:
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
- // 1. Add timeout (innermost - fails fast)
80
- const timedCall = withTimeout(unreliableApiCall, 5_000, "Request timed out")
81
-
82
- // 2. Add retry logic (middle - retries on transient errors)
83
- const retryCall = withRetry(timedCall, {
84
- maxAttempts: 3,
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
- ### Event Monitoring
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
- // Check current state
180
+ ```typescript
181
+ // Check current state: "closed", "open", "halfOpen"
112
182
  console.log("Current state:", protectedFunction.getState())
113
- // Possible states: 'closed', 'open', 'halfOpen'
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
- ### Cleanup
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 should not count toward circuit breaker metrics (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`)
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: `6`)
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
- **Options:**
233
+ **Parameters:**
158
234
 
159
- - `maxAttempts`: Maximum number of attempts (default: `3`)
160
- - `retryDelay`: Function returning promise for when to retry (default: immediate)
161
- - `shouldRetry`: Function to determine if error should be retried (default: `() => true`)
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
- #### `withTimeout(fn, timeoutMs, message?)`
275
+ **Parameters:**
182
276
 
183
- Wraps a function with a timeout. Rejects with `Error(message)` if execution exceeds `timeoutMs`.
277
+ - `maxSeconds`: Maximum delay in seconds before capping
184
278
 
185
- ### Development
279
+ **Returns:** Function `(attempt: number, signal: AbortSignal) => Promise<void>`
186
280
 
187
- ### Building the Project
281
+ #### `delayMs(ms, signal?)`
188
282
 
189
- ```sh
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
- ### Running Tests
285
+ **Parameters:**
194
286
 
195
- ```sh
196
- npm test # once
287
+ - `ms`: Delay in milliseconds
288
+ - `signal`: Optional AbortSignal for cancellation
197
289
 
198
- npm run dev # run and watch for file changes
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