@prash0029/circuit-breaker 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 +196 -0
- package/dist/index.cjs +584 -0
- package/dist/index.d.cts +392 -0
- package/dist/index.d.ts +392 -0
- package/dist/index.js +544 -0
- package/package.json +53 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sai Prashanth
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
# circuit-breaker
|
|
2
|
+
|
|
3
|
+
Two-level, config-driven, in-memory circuit breaker for guarding **outbound** server API calls. Built once at server start from a route checklist, then placed in front of every outgoing request (axios, fetch, or any promise-returning call).
|
|
4
|
+
|
|
5
|
+
Each request is matched against the rules to find its **service** rule and its **endpoint** rule. The request passes only if both matched breakers are non-open. The response status then classifies the call as success or failure on each level:
|
|
6
|
+
|
|
7
|
+
- failure -> `count + 1`
|
|
8
|
+
- success -> `count - 1` (floored at 0; leaky bucket, not a hard reset)
|
|
9
|
+
- `count >= failureThreshold` trips `CLOSED -> OPEN`
|
|
10
|
+
|
|
11
|
+
A request matching no rule passes through untouched.
|
|
12
|
+
|
|
13
|
+
## States
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
CLOSED ──count >= failureThreshold──▶ OPEN
|
|
17
|
+
OPEN ──cooldownMs elapsed──▶ HALF_OPEN
|
|
18
|
+
HALF_OPEN ──successThreshold trial successes──▶ CLOSED
|
|
19
|
+
HALF_OPEN ──any trial failure──▶ OPEN
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npm install circuit-breaker
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Configure once at startup
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { createBreaker } from "circuit-breaker";
|
|
32
|
+
|
|
33
|
+
export const breaker = createBreaker({
|
|
34
|
+
// evaluated in order; first match wins per level
|
|
35
|
+
rules: [
|
|
36
|
+
{
|
|
37
|
+
type: "service",
|
|
38
|
+
match: "insurer-x.com", // substring tested against the request path
|
|
39
|
+
skipList: ["/health", "/ping"], // endpoints NOT counted toward the service
|
|
40
|
+
failureThreshold: 10,
|
|
41
|
+
cooldownMs: 30_000,
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
type: "endpoint",
|
|
45
|
+
match: "/policies/create",
|
|
46
|
+
failureThreshold: 5,
|
|
47
|
+
cooldownMs: 30_000,
|
|
48
|
+
successThreshold: 2,
|
|
49
|
+
successServerStatus: [200, 201], // optional; else default 2xx = success
|
|
50
|
+
failedServerResStatus: [500, 502, 503],
|
|
51
|
+
// per-rule hook: runs only for THIS endpoint's transitions
|
|
52
|
+
onStateChange: (e) => {
|
|
53
|
+
if (e.to === "OPEN") alertOncall(`createPolicy breaker open`);
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
],
|
|
57
|
+
defaults: { failureThreshold: 5, cooldownMs: 30_000, successThreshold: 2 },
|
|
58
|
+
matchOn: "path", // default: strips query string so tokens/PII are never matched
|
|
59
|
+
onStateChange: (e) =>
|
|
60
|
+
console.warn(`[breaker] ${e.level} "${e.key}" ${e.from} -> ${e.to}`),
|
|
61
|
+
});
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Rule fields
|
|
65
|
+
|
|
66
|
+
| Field | Applies to | Meaning |
|
|
67
|
+
| ----------------------- | ---------------- | ------------------------------------------------------------- |
|
|
68
|
+
| `type` | both | `"service"` or `"endpoint"` |
|
|
69
|
+
| `match` | both | substring searched in the request path; rule applies if found |
|
|
70
|
+
| `skipList` | service | endpoint substrings excluded from the service's count |
|
|
71
|
+
| `successServerStatus` | both (optional) | statuses counted as success |
|
|
72
|
+
| `failedServerResStatus` | both (optional) | statuses counted as failure |
|
|
73
|
+
| `failureThreshold` | both (optional) | count that opens the breaker |
|
|
74
|
+
| `cooldownMs` | both (optional) | OPEN duration before a HALF_OPEN probe |
|
|
75
|
+
| `successThreshold` | both (optional) | trial successes needed to close |
|
|
76
|
+
|
|
77
|
+
Status classification precedence: `failedServerResStatus` -> `successServerStatus` -> default (`defaultIsSuccess`, 2xx). A status with no response (network error) is always a failure.
|
|
78
|
+
|
|
79
|
+
## Use it
|
|
80
|
+
|
|
81
|
+
### axios (guards the whole instance)
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
import axios from "axios";
|
|
85
|
+
import { attachAxios } from "circuit-breaker";
|
|
86
|
+
|
|
87
|
+
const client = axios.create({ baseURL: "https://insurer-x.com" });
|
|
88
|
+
attachAxios(client, breaker);
|
|
89
|
+
|
|
90
|
+
await client.post("/policies/create", payload); // guarded; rejects if open
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### fetch
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
import { wrapFetch } from "circuit-breaker";
|
|
97
|
+
|
|
98
|
+
const gfetch = wrapFetch(breaker); // wraps global fetch (Node 18+)
|
|
99
|
+
const res = await gfetch("https://insurer-x.com/policies/create", { method: "POST", body });
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Any promise-returning call
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import { isCircuitOpenError } from "circuit-breaker";
|
|
106
|
+
|
|
107
|
+
try {
|
|
108
|
+
const result = await breaker.guard(
|
|
109
|
+
{ url: "https://insurer-x.com/policies/create", method: "POST" },
|
|
110
|
+
() => doRequest(), // must resolve to something with a numeric `status`
|
|
111
|
+
);
|
|
112
|
+
} catch (err) {
|
|
113
|
+
if (isCircuitOpenError(err)) {
|
|
114
|
+
// fail fast: queue, fall back, or return 503. err.retryAt = when to retry.
|
|
115
|
+
} else {
|
|
116
|
+
throw err;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Or wrap once:
|
|
121
|
+
const createPolicy = breaker.wrap(
|
|
122
|
+
{ url: "https://insurer-x.com/policies/create", method: "POST" },
|
|
123
|
+
(body) => doRequest(body),
|
|
124
|
+
);
|
|
125
|
+
await createPolicy(body);
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## Inspect / operate
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
breaker.stateOf("service", "insurer-x.com"); // { state, count, openedAt } | null
|
|
132
|
+
breaker.stateOf("endpoint", "/policies/create");
|
|
133
|
+
breaker.reset("endpoint", "/policies/create"); // force one breaker CLOSED
|
|
134
|
+
breaker.resetAll(); // force everything CLOSED
|
|
135
|
+
|
|
136
|
+
breaker.snapshots(); // { service: {key: snap}, endpoint: {key: snap} }
|
|
137
|
+
breaker.printStatus(); // one line per live breaker -> console.log
|
|
138
|
+
breaker.printStatus(log.info); // ...or to your own logger sink
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### State-change callbacks
|
|
142
|
+
|
|
143
|
+
Two levels, both optional, both receive `{ level, key, from, to, at }`:
|
|
144
|
+
|
|
145
|
+
- **registry-wide** `onStateChange` in the config — every breaker.
|
|
146
|
+
- **per-rule** `onStateChange` on a rule — only that endpoint/service. Runs first, then the registry-wide one.
|
|
147
|
+
|
|
148
|
+
### Email alerts (nodemailer)
|
|
149
|
+
|
|
150
|
+
`emailAlerter` builds an `onStateChange` handler that mails an alert when a breaker trips. The transporter is injected — **SMTP credentials stay in your env/secrets manager, never in this package**. Default trigger: OPEN only. Recipients come from each rule's `alertEmails` (falling back to `to`). Sends are non-blocking and never throw into the breaker (failures are caught + logged).
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
import nodemailer from "nodemailer";
|
|
154
|
+
import { createBreaker, emailAlerter } from "circuit-breaker";
|
|
155
|
+
|
|
156
|
+
const transporter = nodemailer.createTransport({
|
|
157
|
+
host: process.env.SMTP_HOST,
|
|
158
|
+
port: Number(process.env.SMTP_PORT),
|
|
159
|
+
auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS }, // from env, not code
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
const alert = emailAlerter({
|
|
163
|
+
transporter,
|
|
164
|
+
from: "alerts@yourco.test",
|
|
165
|
+
// when: [BreakerState.OPEN] // default
|
|
166
|
+
// to: ["ops@yourco.test"] // fallback if a rule omits alertEmails
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
const breaker = createBreaker({
|
|
170
|
+
rules: [
|
|
171
|
+
{ type: "endpoint", match: "/policies/create", failureThreshold: 5,
|
|
172
|
+
alertEmails: ["oncall@yourco.test", "insurer-team@yourco.test"] }, // per-row list
|
|
173
|
+
{ type: "service", match: "icicilombard.com", failureThreshold: 10,
|
|
174
|
+
alertEmails: ["ops@yourco.test"] },
|
|
175
|
+
],
|
|
176
|
+
onStateChange: alert, // attach registry-wide; fires for every rule
|
|
177
|
+
});
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Each rule mails its own `alertEmails` list. Use `subject`/`body` options to customize the message.
|
|
181
|
+
|
|
182
|
+
## Scope / limits
|
|
183
|
+
|
|
184
|
+
- **In-memory per process.** Behind multiple replicas, each replica trips independently. No shared/distributed state.
|
|
185
|
+
- **HALF_OPEN admits concurrent probes** (no in-flight reservation); a burst right after cooldown can all probe at once.
|
|
186
|
+
- **No timeout wrapping.** Wrap your own request timeout inside the call.
|
|
187
|
+
- **Substring matching is loose.** `"/policy"` also matches `"/policy-archive"`. Order rules deliberately (first match wins) and prefer specific `match` strings.
|
|
188
|
+
- A cancelled axios request that already passed the open check records no outcome.
|
|
189
|
+
|
|
190
|
+
## Develop
|
|
191
|
+
|
|
192
|
+
```bash
|
|
193
|
+
npm install
|
|
194
|
+
npm test
|
|
195
|
+
npm run build
|
|
196
|
+
```
|