breaker-box 1.0.0 → 3.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
@@ -27,9 +27,10 @@ async function unreliableApiCall(data: string) {
27
27
  }
28
28
 
29
29
  const protectedApiCall = createCircuitBreaker(unreliableApiCall, {
30
- failureThreshold: 1, // Open circuit after first failure
31
- resetAfter: 30_000, // Try again after 30 seconds
32
- errorIsFailure: (error) => true,
30
+ errorIsFailure: () => true, // Any error is considered a failure
31
+ failureThreshold: 1, // Open circuit after first failure
32
+ fallback: undefined, // No fallback, errors are propagated
33
+ resetAfter: 30_000, // Try again after 30 seconds
33
34
  })
34
35
 
35
36
  try {
@@ -43,22 +44,13 @@ try {
43
44
  ### Event Monitoring
44
45
 
45
46
  ```typescript
46
- const protectedFunction = createCircuitBreaker(unreliableApiCall)
47
-
48
- protectedFunction.on("open", (cause) => {
49
- console.log("Circuit opened due to:", cause.message)
50
- })
51
-
52
- protectedFunction.on("close", () => {
53
- console.log("Circuit closed - normal operation resumed")
54
- })
55
-
56
- protectedFunction.on("reject", (error) => {
57
- console.log("Function call rejected:", error.message)
58
- })
59
-
60
- protectedFunction.on("resolve", () => {
61
- console.log("Function call succeeded")
47
+ const protectedFunction = createCircuitBreaker(unreliableApiCall, {
48
+ onClose: () => {
49
+ console.log("Circuit closed - normal operation resumed")
50
+ },
51
+ onOpen: (cause) => {
52
+ console.log("Circuit opened due to:", cause.message)
53
+ },
62
54
  })
63
55
 
64
56
  // Check current state
@@ -83,26 +75,20 @@ Creates a circuit breaker around the provided async function.
83
75
 
84
76
  - `fn`: The async function to protect
85
77
  - `options`: Configuration object (optional)
78
+ - `errorIsFailure`: Function to determine if an error counts as failure (default: all errors)
86
79
  - `failureThreshold`: Number of failures before opening circuit (default: 1)
80
+ - `fallback`: Function to call when circuit is open (default: undefined)
81
+ - `onClose`: Function to call when circuit is closed (default: undefined)
82
+ - `onOpen`: Function to call when circuit is opened (default: undefined)
87
83
  - `resetAfter`: Milliseconds to wait before trying again (default: 30000)
88
- - `errorIsFailure`: Function to determine if an error counts as failure (default: all errors)
89
- - `fallback`: Function to call when circuit is open (default: throws CircuitOpenError)
90
84
 
91
85
  #### Returns
92
86
 
93
87
  A function with the same signature as `fn` and additional methods:
94
88
 
95
- - `.getState()`: Returns current circuit state
96
- - `.on(event, listener)`: Add event listener
97
- - `.off(event, listener)`: Remove event listener
98
89
  - `.dispose()`: Clean up resources
99
-
100
- #### Events
101
-
102
- - `open`: Circuit opened due to failures
103
- - `close`: Circuit closed and resumed normal operation
104
- - `reject`: Function call was rejected
105
- - `resolve`: Function call succeeded
90
+ - `.getLatestError()`: Returns the error which triggered the circuit breaker
91
+ - `.getState()`: Returns current circuit state
106
92
 
107
93
  ### Development
108
94
 
package/dist/index.cjs CHANGED
@@ -1,88 +1,81 @@
1
1
  'use strict';
2
2
 
3
- var EventEmitter = require('node:events');
4
-
5
- const assertNever = (value, message = "Unexpected value") => (
6
- /* v8 ignore next */
7
- new TypeError(`${message}: ${value}`)
8
- );
3
+ const assertNever = (val, msg = "Unexpected value") => {
4
+ throw new TypeError(`${msg}: ${val}`);
5
+ };
6
+ const resolvedPromise = Promise.resolve();
7
+ const nextTick = (fn) => resolvedPromise.then(fn);
9
8
 
10
9
  function createCircuitBreaker(main, options = {}) {
11
- const events = new EventEmitter();
12
10
  const {
13
11
  errorIsFailure = () => true,
14
12
  failureThreshold = 1,
15
- fallback = () => {
16
- const cause = failureCause;
17
- const msg = cause instanceof Error ? cause.message : "Unknown";
18
- throw new Error(`CircuitOpenError: ${msg}`, { cause });
19
- },
13
+ onClose,
14
+ onOpen,
20
15
  resetAfter = 3e4
21
16
  } = options;
17
+ let fallback = options.fallback || (() => Promise.reject(failureCause));
18
+ let halfOpenPending;
22
19
  let state = "closed";
23
- let failureCause = void 0;
20
+ let failureCause;
24
21
  let failureCount = 0;
25
- let resetTimer = void 0;
22
+ let resetTimer;
23
+ function clearFailure() {
24
+ failureCause = void 0;
25
+ failureCount = 0;
26
+ }
26
27
  function openCircuit(cause) {
27
- if (state === "disposed") return;
28
- state = "open";
29
- events.emit("open", cause);
30
28
  failureCause = cause;
29
+ state = "open";
31
30
  clearTimeout(resetTimer);
32
31
  resetTimer = setTimeout(() => state = "halfOpen", resetAfter);
32
+ onOpen?.(cause);
33
33
  }
34
- function closeCircuit() {
35
- if (state === "disposed") return;
36
- if (state === "halfOpen") events.emit("close");
37
- state = "closed";
38
- failureCause = void 0;
39
- failureCount = 0;
40
- clearTimeout(resetTimer);
41
- }
42
- const mainWithEmit = async (...args) => {
43
- try {
44
- const result = await main(...args);
45
- events.emit("resolve");
46
- closeCircuit();
47
- return result;
48
- } catch (cause) {
49
- events.emit("reject", cause);
50
- throw cause;
51
- }
52
- };
53
- async function protectedFunction(...args) {
54
- if (state === "open") {
34
+ function protectedFunction(...args) {
35
+ if (state === "closed") {
36
+ const thisFallback = fallback;
37
+ return main(...args).then(
38
+ (result) => {
39
+ if (state === "closed") clearFailure();
40
+ return result;
41
+ },
42
+ (cause) => {
43
+ if (thisFallback !== fallback) throw cause;
44
+ failureCount += errorIsFailure(cause) ? 1 : 0;
45
+ if (failureCount === failureThreshold) openCircuit(cause);
46
+ return nextTick(() => protectedFunction(...args));
47
+ }
48
+ );
49
+ } else if (state === "open" || halfOpenPending) {
55
50
  return fallback(...args);
56
51
  } else if (state === "halfOpen") {
57
- return mainWithEmit(...args).catch((cause) => {
58
- openCircuit(cause);
59
- return fallback(...args);
60
- });
61
- } else if (state === "closed") {
62
- return mainWithEmit(...args).catch((cause) => {
63
- failureCause = cause;
64
- failureCount += errorIsFailure(cause) ? 1 : 0;
65
- if (failureCount >= failureThreshold) openCircuit(cause);
66
- return fallback(...args);
67
- });
68
- } else if (state === "disposed")
69
- throw new Error("Circuit breaker has been disposed");
70
- else throw assertNever(state);
52
+ const thisFallback = fallback;
53
+ return (halfOpenPending = main(...args)).finally(() => halfOpenPending = void 0).then(
54
+ (result) => {
55
+ if (thisFallback !== fallback) return result;
56
+ state = "closed";
57
+ clearFailure();
58
+ clearTimeout(resetTimer);
59
+ onClose?.();
60
+ return result;
61
+ },
62
+ (cause) => {
63
+ if (thisFallback !== fallback) throw cause;
64
+ openCircuit(cause);
65
+ return nextTick(() => protectedFunction(...args));
66
+ }
67
+ );
68
+ }
69
+ return assertNever(state);
71
70
  }
72
71
  protectedFunction.dispose = () => {
73
- events.removeAllListeners();
74
- closeCircuit();
75
- state = "disposed";
72
+ clearFailure();
73
+ clearTimeout(resetTimer);
74
+ fallback = () => Promise.reject(new ReferenceError("ERR_CIRCUIT_BREAKER_DISPOSED"));
75
+ state = "open";
76
76
  };
77
+ protectedFunction.getLatestError = () => failureCause;
77
78
  protectedFunction.getState = () => state;
78
- protectedFunction.off = (event, listener) => {
79
- events.removeListener(event, listener);
80
- return protectedFunction;
81
- };
82
- protectedFunction.on = (event, listener) => {
83
- events.addListener(event, listener);
84
- return protectedFunction;
85
- };
86
79
  return protectedFunction;
87
80
  }
88
81
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../lib/util.ts","../lib/index.ts"],"sourcesContent":["export type AnyFn = (...args: any[]) => any\n\n/**\n * `[TypeScript]` For exhaustive checks in switch statements or if/else. Add\n * this check to `default` case or final `else` to ensure all possible values\n * have been handled. If a new value is added to the type, TypeScript will\n * throw an error and the editor will underline the `value`.\n */\nexport const assertNever = (value: never, message = \"Unexpected value\") =>\n\t/* v8 ignore next */\n\tnew TypeError(`${message}: ${value}`)\n","import { type AnyFn, assertNever } from \"./util.js\"\nimport EventEmitter from \"node:events\"\n\nexport type CircuitState = \"closed\" | \"disposed\" | \"halfOpen\" | \"open\"\n\nexport interface CircuitBreakerOptions<Args extends unknown[], Ret> {\n\t/**\n\t * Whether an error should be considered a failure that could trigger\n\t * the circuit breaker. Use this to prevent certain errors from\n\t * incrementing the failure count.\n\t * \n\t * @default () => true // Every error is considered a failure\n\t */\n\terrorIsFailure?: (error: unknown) => boolean\n\n\t/**\n\t * The number of failures before the circuit breaker opens.\n\t * \n\t * @default 1 // The first error opens the circuit\n\t */\n\tfailureThreshold?: number\n\n\t/**\n\t * If provided, then all rejected calls to `main` will be forwarded to\n\t * this function instead.\n\t * \n\t * @default undefined // No fallback, throws `CircuitOpenError`\n\t */\n\tfallback?: (...args: Args) => Promise<Ret>\n\n\t/**\n\t * The amount of time to wait before allowing a half-open state.\n\t * \n\t * @default 30_000 // 30 seconds\n\t */\n\tresetAfter?: number\n}\n\nexport interface EventMap {\n\tclose: []\n\topen: [cause: unknown]\n\treject: [cause: unknown]\n\tresolve: []\n}\n\nexport interface ProtectedFunction<Args extends unknown[], Ret> {\n\t(...args: Args): Promise<Ret>\n\n\t/** Free memory and stop timers */\n\tdispose(): void\n\n\t/** Get the current state of the circuit breaker */\n\tgetState(): CircuitState\n\n\t/** Remove a listener from the circuit breaker */\n\toff<T extends keyof EventMap>(\n\t\tevent: T,\n\t\tlistener: (...args: EventMap[T]) => void\n\t): this\n\n\t/** Add a listener to the circuit breaker */\n\ton<T extends keyof EventMap>(\n\t\tevent: T,\n\t\tlistener: (...args: EventMap[T]) => void\n\t): this\n}\n\nexport function createCircuitBreaker<Args extends unknown[], Ret>(\n\tmain: (...args: Args) => Promise<Ret>,\n\toptions: CircuitBreakerOptions<Args, Ret> = {}\n): ProtectedFunction<Args, Ret> {\n\tconst events = new EventEmitter<EventMap>()\n\tconst {\n\t\terrorIsFailure = () => true,\n\t\tfailureThreshold = 1,\n\t\tfallback = () => {\n\t\t\tconst cause = failureCause\n\t\t\tconst msg = cause instanceof Error ? cause.message : \"Unknown\"\n\t\t\tthrow new Error(`CircuitOpenError: ${msg}`, { cause })\n\t\t},\n\t\tresetAfter = 30_000,\n\t} = options\n\tlet state: CircuitState = \"closed\"\n\tlet failureCause: unknown | undefined = undefined\n\tlet failureCount = 0\n\tlet resetTimer: NodeJS.Timeout | undefined = undefined\n\n\t/**\n\t * Break the circuit and wait for a reset\n\t */\n\tfunction openCircuit(cause: unknown) {\n\t\tif (state === \"disposed\") return\n\t\tstate = \"open\"\n\t\tevents.emit(\"open\", cause)\n\t\tfailureCause = cause\n\t\tclearTimeout(resetTimer)\n\t\tresetTimer = setTimeout(() => (state = \"halfOpen\"), resetAfter)\n\t}\n\n\t/**\n\t * Restart the circuit and resume normal operation\n\t */\n\tfunction closeCircuit() {\n\t\tif (state === \"disposed\") return\n\t\tif (state === \"halfOpen\") events.emit(\"close\")\n\t\tstate = \"closed\"\n\t\tfailureCause = undefined\n\t\tfailureCount = 0\n\t\tclearTimeout(resetTimer)\n\t}\n\n\tconst mainWithEmit = async (...args: Args) => {\n\t\ttry {\n\t\t\tconst result = await main(...args)\n\t\t\tevents.emit(\"resolve\")\n\t\t\tcloseCircuit()\n\t\t\treturn result\n\t\t} catch (cause) {\n\t\t\tevents.emit(\"reject\", cause)\n\t\t\tthrow cause\n\t\t}\n\t}\n\n\t/**\n\t * Wrap calls to `main` with circuit breaker logic\n\t */\n\tasync function protectedFunction(...args: Args): Promise<Ret> {\n\t\t// Use the fallback while the circuit is open\n\t\tif (state === \"open\") {\n\t\t\treturn fallback(...args)\n\t\t}\n\n\t\t// While the circuit is half-open, try the main function once. If it\n\t\t// success, close the circuit and resume normal operation. If it fails,\n\t\t// re-open the circuit and run the fallback instead.\n\t\telse if (state === \"halfOpen\") {\n\t\t\treturn mainWithEmit(...args).catch((cause) => {\n\t\t\t\topenCircuit(cause)\n\t\t\t\treturn fallback(...args)\n\t\t\t})\n\t\t}\n\n\t\t// Normal operation when circuit is closed. If an error occurs, keep track\n\t\t// of the failure count and open the circuit if it exceeds the threshold.\n\t\telse if (state === \"closed\") {\n\t\t\treturn mainWithEmit(...args).catch((cause) => {\n\t\t\t\tfailureCause = cause\n\t\t\t\tfailureCount += errorIsFailure(cause) ? 1 : 0\n\t\t\t\tif (failureCount >= failureThreshold) openCircuit(cause)\n\t\t\t\treturn fallback(...args)\n\t\t\t})\n\t\t}\n\n\t\t// Shutting down...\n\t\telse if (state === \"disposed\")\n\t\t\tthrow new Error(\"Circuit breaker has been disposed\")\n\t\telse throw assertNever(state)\n\t}\n\n\tprotectedFunction.dispose = () => {\n\t\tevents.removeAllListeners()\n\t\tcloseCircuit()\n\t\tstate = \"disposed\"\n\t}\n\n\tprotectedFunction.getState = () => state\n\n\tprotectedFunction.off = (event: keyof EventMap, listener: AnyFn) => {\n\t\tevents.removeListener(event, listener)\n\t\treturn protectedFunction\n\t}\n\n\tprotectedFunction.on = (event: keyof EventMap, listener: AnyFn) => {\n\t\tevents.addListener(event, listener)\n\t\treturn protectedFunction\n\t}\n\n\treturn protectedFunction\n}\n"],"names":[],"mappings":";;;;AACO,MAAM,WAAW,GAAG,CAAC,KAAK,EAAE,OAAO,GAAG,kBAAkB;AAC/D;AACA,EAAE,IAAI,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;AACtC,CAAC;;ACDM,SAAS,oBAAoB,CAAC,IAAI,EAAE,OAAO,GAAG,EAAE,EAAE;AACzD,EAAE,MAAM,MAAM,GAAG,IAAI,YAAY,EAAE;AACnC,EAAE,MAAM;AACR,IAAI,cAAc,GAAG,MAAM,IAAI;AAC/B,IAAI,gBAAgB,GAAG,CAAC;AACxB,IAAI,QAAQ,GAAG,MAAM;AACrB,MAAM,MAAM,KAAK,GAAG,YAAY;AAChC,MAAM,MAAM,GAAG,GAAG,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,SAAS;AACpE,MAAM,MAAM,IAAI,KAAK,CAAC,CAAC,kBAAkB,EAAE,GAAG,CAAC,CAAC,EAAE,EAAE,KAAK,EAAE,CAAC;AAC5D,IAAI,CAAC;AACL,IAAI,UAAU,GAAG;AACjB,GAAG,GAAG,OAAO;AACb,EAAE,IAAI,KAAK,GAAG,QAAQ;AACtB,EAAE,IAAI,YAAY,GAAG,MAAM;AAC3B,EAAE,IAAI,YAAY,GAAG,CAAC;AACtB,EAAE,IAAI,UAAU,GAAG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AAE,QAAQ,CAAC;AACvC,IAAI,OAAO,iBAAiB;AAC5B,EAAE,CAAC;AACH,EAAE,OAAO,iBAAiB;AAC1B;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":["../lib/util.ts","../lib/index.ts"],"sourcesContent":["export type AnyFn = (...args: any[]) => any\n\n/**\n * `[TypeScript]` For exhaustive checks in switch statements or if/else. Add\n * this check to `default` case or final `else` to ensure all possible values\n * have been handled. If a new value is added to the type, TypeScript will\n * throw an error and the editor will underline the `value`.\n */\n/* v8 ignore next 3 */\nexport const assertNever = (val: never, msg = \"Unexpected value\") => {\n\tthrow new TypeError(`${msg}: ${val}`)\n}\n\n/**\n * Returns a promise that resolves after the specified number of milliseconds.\n */\nexport const delayMs = (ms: number): Promise<void> =>\n\tnew Promise((next) => setTimeout(next, ms))\n\nconst resolvedPromise = Promise.resolve()\n\nexport const nextTick = <T>(fn: () => T | PromiseLike<T>): Promise<T> =>\n\tresolvedPromise.then(fn)\n","import { type AnyFn, assertNever, nextTick } from \"./util.js\"\n\nexport type CircuitState = \"closed\" | \"halfOpen\" | \"open\"\n\nexport interface CircuitBreakerOptions<Fallback extends AnyFn = AnyFn> {\n\t/**\n\t * Whether an error should be considered a failure that could trigger\n\t * the circuit breaker. Use this to prevent certain errors from\n\t * incrementing the failure count.\n\t *\n\t * @default () => true // Every error is considered a failure\n\t */\n\terrorIsFailure?: (error: unknown) => boolean\n\n\t/**\n\t * The number of failures before the circuit breaker opens.\n\t *\n\t * @default 1 // The first error opens the circuit\n\t */\n\tfailureThreshold?: number\n\n\t/**\n\t * If provided, then all rejected calls to `main` will be forwarded to\n\t * this function instead.\n\t *\n\t * @default undefined // No fallback, errors are propagated\n\t */\n\tfallback?: Fallback\n\n\t/** Called when the circuit breaker is closed */\n\tonClose?: () => void\n\n\t/** Called when the circuit breaker is opened */\n\tonOpen?: (cause: unknown) => void\n\n\t/**\n\t * The amount of time to wait before allowing a half-open state.\n\t *\n\t * @default 30_000 // 30 seconds\n\t */\n\tresetAfter?: number\n}\n\nexport interface CircuitBreakerProtectedFn<\n\tRet = unknown,\n\tArgs extends unknown[] = never[]\n> {\n\t(...args: Args): Promise<Ret>\n\n\t/** Free memory and stop timers */\n\tdispose(): void\n\n\t/** Get the last error which triggered the circuit breaker */\n\tgetLatestError(): unknown | undefined\n\n\t/** Get the current state of the circuit breaker */\n\tgetState(): CircuitState\n}\n\nexport function createCircuitBreaker<\n\tRet,\n\tArgs extends unknown[],\n\tFallback extends AnyFn = (...args: Args) => Promise<Ret>\n>(\n\tmain: (...args: Args) => Promise<Ret>,\n\toptions: CircuitBreakerOptions<Fallback> = {}\n): CircuitBreakerProtectedFn<Ret, Args> {\n\tconst {\n\t\terrorIsFailure = () => true,\n\t\tfailureThreshold = 1,\n\t\tonClose,\n\t\tonOpen,\n\t\tresetAfter = 30_000,\n\t} = options\n\tlet fallback = options.fallback || (() => Promise.reject(failureCause))\n\tlet halfOpenPending: Promise<unknown> | undefined\n\tlet state: CircuitState = \"closed\"\n\tlet failureCause: unknown | undefined\n\tlet failureCount = 0\n\tlet resetTimer: NodeJS.Timeout | undefined\n\n\tfunction clearFailure() {\n\t\tfailureCause = undefined\n\t\tfailureCount = 0\n\t}\n\n\t/**\n\t * Break the circuit and wait for a reset\n\t */\n\tfunction openCircuit(cause: unknown) {\n\t\tfailureCause = cause\n\t\tstate = \"open\"\n\t\tclearTimeout(resetTimer)\n\t\tresetTimer = setTimeout(() => (state = \"halfOpen\"), resetAfter)\n\t\tonOpen?.(cause)\n\t}\n\n\t/**\n\t * Wrap calls to `main` with circuit breaker logic\n\t */\n\tfunction protectedFunction(...args: Args): Promise<Ret> {\n\t\t// Normal operation when circuit is closed. If an error occurs, keep track\n\t\t// of the failure count and open the circuit if it exceeds the threshold.\n\t\tif (state === \"closed\") {\n\t\t\tconst thisFallback = fallback\n\t\t\treturn main(...args).then(\n\t\t\t\t(result) => {\n\t\t\t\t\t// Reset accumulated failures if circuit is still closed\n\t\t\t\t\tif (state === \"closed\") clearFailure()\n\t\t\t\t\treturn result\n\t\t\t\t},\n\t\t\t\t(cause: unknown) => {\n\t\t\t\t\t// Was the circuit breaker disposed while the call was in flight?\n\t\t\t\t\tif (thisFallback !== fallback) throw cause\n\t\t\t\t\tfailureCount += errorIsFailure(cause) ? 1 : 0\n\t\t\t\t\tif (failureCount === failureThreshold) openCircuit(cause)\n\t\t\t\t\treturn nextTick(() => protectedFunction(...args))\n\t\t\t\t}\n\t\t\t)\n\t\t}\n\n\t\t// Use the fallback while the circuit is open, or if a half-open trial\n\t\t// attempt was already made.\n\t\telse if (state === \"open\" || halfOpenPending) {\n\t\t\treturn fallback(...args)\n\t\t}\n\n\t\t// If the circuit is half-open, make one attempt. If it succeeds, close\n\t\t// the circuit and resume normal operation. If it fails, re-open the\n\t\t// circuit and run the fallback instead.\n\t\telse if (state === \"halfOpen\") {\n\t\t\tconst thisFallback = fallback\n\t\t\treturn (halfOpenPending = main(...args))\n\t\t\t\t.finally(() => (halfOpenPending = undefined))\n\t\t\t\t.then(\n\t\t\t\t\t(result) => {\n\t\t\t\t\t\t// Was the circuit breaker disposed while the call was\n\t\t\t\t\t\t// in flight?\n\t\t\t\t\t\tif (thisFallback !== fallback) return result\n\t\t\t\t\t\t// Close the circuit and resume normal operation\n\t\t\t\t\t\tstate = \"closed\"\n\t\t\t\t\t\tclearFailure()\n\t\t\t\t\t\tclearTimeout(resetTimer)\n\t\t\t\t\t\tonClose?.()\n\t\t\t\t\t\treturn result\n\t\t\t\t\t},\n\t\t\t\t\t(cause: unknown) => {\n\t\t\t\t\t\t// Was the circuit breaker disposed while the call was\n\t\t\t\t\t\t// in flight?\n\t\t\t\t\t\tif (thisFallback !== fallback) throw cause\n\t\t\t\t\t\topenCircuit(cause)\n\t\t\t\t\t\treturn nextTick(() => protectedFunction(...args))\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t/* v8 ignore next */\n\t\t}\n\n\t\t// exhaustive check\n\t\t/* v8 ignore next */\n\t\treturn assertNever(state)\n\t}\n\n\tprotectedFunction.dispose = () => {\n\t\tclearFailure()\n\t\tclearTimeout(resetTimer)\n\t\tfallback = () =>\n\t\t\tPromise.reject(new ReferenceError(\"ERR_CIRCUIT_BREAKER_DISPOSED\"))\n\t\tstate = \"open\"\n\t}\n\n\tprotectedFunction.getLatestError = () => failureCause\n\n\tprotectedFunction.getState = () => state\n\n\treturn protectedFunction\n}\n"],"names":[],"mappings":";;AACO,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE,GAAG,GAAG,kBAAkB,KAAK;AAC9D,EAAE,MAAM,IAAI,SAAS,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC;AACvC,CAAC;AAED,MAAM,eAAe,GAAG,OAAO,CAAC,OAAO,EAAE;AAClC,MAAM,QAAQ,GAAG,CAAC,EAAE,KAAK,eAAe,CAAC,IAAI,CAAC,EAAE,CAAC;;ACJjD,SAAS,oBAAoB,CAAC,IAAI,EAAE,OAAO,GAAG,EAAE,EAAE;AACzD,EAAE,MAAM;AACR,IAAI,cAAc,GAAG,MAAM,IAAI;AAC/B,IAAI,gBAAgB,GAAG,CAAC;AACxB,IAAI,OAAO;AACX,IAAI,MAAM;AACV,IAAI,UAAU,GAAG;AACjB,GAAG,GAAG,OAAO;AACb,EAAE,IAAI,QAAQ,GAAG,OAAO,CAAC,QAAQ,KAAK,MAAM,OAAO,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;AACzE,EAAE,IAAI,eAAe;AACrB,EAAE,IAAI,KAAK,GAAG,QAAQ;AACtB,EAAE,IAAI,YAAY;AAClB,EAAE,IAAI,YAAY,GAAG,CAAC;AACtB,EAAE,IAAI,UAAU;AAChB,EAAE,SAAS,YAAY,GAAG;AAC1B,IAAI,YAAY,GAAG,MAAM;AACzB,IAAI,YAAY,GAAG,CAAC;AACpB,EAAE;AACF,EAAE,SAAS,WAAW,CAAC,KAAK,EAAE;AAC9B,IAAI,YAAY,GAAG,KAAK;AACxB,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,QAAQ,EAAE,OAAO,MAAM;AACtD,UAAU,KAAK,GAAG,QAAQ;AAC1B,UAAU,YAAY,EAAE;AACxB,UAAU,YAAY,CAAC,UAAU,CAAC;AAClC,UAAU,OAAO,IAAI;AACrB,UAAU,OAAO,MAAM;AACvB,QAAQ,CAAC;AACT,QAAQ,CAAC,KAAK,KAAK;AACnB,UAAU,IAAI,YAAY,KAAK,QAAQ,EAAE,MAAM,KAAK;AACpD,UAAU,WAAW,CAAC,KAAK,CAAC;AAC5B,UAAU,OAAO,QAAQ,CAAC,MAAM,iBAAiB,CAAC,GAAG,IAAI,CAAC,CAAC;AAC3D,QAAQ;AACR,OAAO;AACP,IAAI;AACJ,IAAI,OAAO,WAAW,CAAC,KAAK,CAAC;AAC7B,EAAE;AACF,EAAE,iBAAiB,CAAC,OAAO,GAAG,MAAM;AACpC,IAAI,YAAY,EAAE;AAClB,IAAI,YAAY,CAAC,UAAU,CAAC;AAC5B,IAAI,QAAQ,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,IAAI,cAAc,CAAC,8BAA8B,CAAC,CAAC;AACvF,IAAI,KAAK,GAAG,MAAM;AAClB,EAAE,CAAC;AACH,EAAE,iBAAiB,CAAC,cAAc,GAAG,MAAM,YAAY;AACvD,EAAE,iBAAiB,CAAC,QAAQ,GAAG,MAAM,KAAK;AAC1C,EAAE,OAAO,iBAAiB;AAC1B;;;;"}
package/dist/index.d.cts CHANGED
@@ -1,5 +1,7 @@
1
- type CircuitState = "closed" | "disposed" | "halfOpen" | "open";
2
- interface CircuitBreakerOptions<Args extends unknown[], Ret> {
1
+ type AnyFn = (...args: any[]) => any;
2
+
3
+ type CircuitState = "closed" | "halfOpen" | "open";
4
+ interface CircuitBreakerOptions<Fallback extends AnyFn = AnyFn> {
3
5
  /**
4
6
  * Whether an error should be considered a failure that could trigger
5
7
  * the circuit breaker. Use this to prevent certain errors from
@@ -18,9 +20,13 @@ interface CircuitBreakerOptions<Args extends unknown[], Ret> {
18
20
  * If provided, then all rejected calls to `main` will be forwarded to
19
21
  * this function instead.
20
22
  *
21
- * @default undefined // No fallback, throws `CircuitOpenError`
23
+ * @default undefined // No fallback, errors are propagated
22
24
  */
23
- fallback?: (...args: Args) => Promise<Ret>;
25
+ fallback?: Fallback;
26
+ /** Called when the circuit breaker is closed */
27
+ onClose?: () => void;
28
+ /** Called when the circuit breaker is opened */
29
+ onOpen?: (cause: unknown) => void;
24
30
  /**
25
31
  * The amount of time to wait before allowing a half-open state.
26
32
  *
@@ -28,24 +34,16 @@ interface CircuitBreakerOptions<Args extends unknown[], Ret> {
28
34
  */
29
35
  resetAfter?: number;
30
36
  }
31
- interface EventMap {
32
- close: [];
33
- open: [cause: unknown];
34
- reject: [cause: unknown];
35
- resolve: [];
36
- }
37
- interface ProtectedFunction<Args extends unknown[], Ret> {
37
+ interface CircuitBreakerProtectedFn<Ret = unknown, Args extends unknown[] = never[]> {
38
38
  (...args: Args): Promise<Ret>;
39
39
  /** Free memory and stop timers */
40
40
  dispose(): void;
41
+ /** Get the last error which triggered the circuit breaker */
42
+ getLatestError(): unknown | undefined;
41
43
  /** Get the current state of the circuit breaker */
42
44
  getState(): CircuitState;
43
- /** Remove a listener from the circuit breaker */
44
- off<T extends keyof EventMap>(event: T, listener: (...args: EventMap[T]) => void): this;
45
- /** Add a listener to the circuit breaker */
46
- on<T extends keyof EventMap>(event: T, listener: (...args: EventMap[T]) => void): this;
47
45
  }
48
- declare function createCircuitBreaker<Args extends unknown[], Ret>(main: (...args: Args) => Promise<Ret>, options?: CircuitBreakerOptions<Args, Ret>): ProtectedFunction<Args, Ret>;
46
+ declare function createCircuitBreaker<Ret, Args extends unknown[], Fallback extends AnyFn = (...args: Args) => Promise<Ret>>(main: (...args: Args) => Promise<Ret>, options?: CircuitBreakerOptions<Fallback>): CircuitBreakerProtectedFn<Ret, Args>;
49
47
 
50
48
  export { createCircuitBreaker };
51
- export type { CircuitBreakerOptions, CircuitState, EventMap, ProtectedFunction };
49
+ export type { CircuitBreakerOptions, CircuitBreakerProtectedFn, CircuitState };
package/dist/index.d.mts CHANGED
@@ -1,5 +1,7 @@
1
- type CircuitState = "closed" | "disposed" | "halfOpen" | "open";
2
- interface CircuitBreakerOptions<Args extends unknown[], Ret> {
1
+ type AnyFn = (...args: any[]) => any;
2
+
3
+ type CircuitState = "closed" | "halfOpen" | "open";
4
+ interface CircuitBreakerOptions<Fallback extends AnyFn = AnyFn> {
3
5
  /**
4
6
  * Whether an error should be considered a failure that could trigger
5
7
  * the circuit breaker. Use this to prevent certain errors from
@@ -18,9 +20,13 @@ interface CircuitBreakerOptions<Args extends unknown[], Ret> {
18
20
  * If provided, then all rejected calls to `main` will be forwarded to
19
21
  * this function instead.
20
22
  *
21
- * @default undefined // No fallback, throws `CircuitOpenError`
23
+ * @default undefined // No fallback, errors are propagated
22
24
  */
23
- fallback?: (...args: Args) => Promise<Ret>;
25
+ fallback?: Fallback;
26
+ /** Called when the circuit breaker is closed */
27
+ onClose?: () => void;
28
+ /** Called when the circuit breaker is opened */
29
+ onOpen?: (cause: unknown) => void;
24
30
  /**
25
31
  * The amount of time to wait before allowing a half-open state.
26
32
  *
@@ -28,24 +34,16 @@ interface CircuitBreakerOptions<Args extends unknown[], Ret> {
28
34
  */
29
35
  resetAfter?: number;
30
36
  }
31
- interface EventMap {
32
- close: [];
33
- open: [cause: unknown];
34
- reject: [cause: unknown];
35
- resolve: [];
36
- }
37
- interface ProtectedFunction<Args extends unknown[], Ret> {
37
+ interface CircuitBreakerProtectedFn<Ret = unknown, Args extends unknown[] = never[]> {
38
38
  (...args: Args): Promise<Ret>;
39
39
  /** Free memory and stop timers */
40
40
  dispose(): void;
41
+ /** Get the last error which triggered the circuit breaker */
42
+ getLatestError(): unknown | undefined;
41
43
  /** Get the current state of the circuit breaker */
42
44
  getState(): CircuitState;
43
- /** Remove a listener from the circuit breaker */
44
- off<T extends keyof EventMap>(event: T, listener: (...args: EventMap[T]) => void): this;
45
- /** Add a listener to the circuit breaker */
46
- on<T extends keyof EventMap>(event: T, listener: (...args: EventMap[T]) => void): this;
47
45
  }
48
- declare function createCircuitBreaker<Args extends unknown[], Ret>(main: (...args: Args) => Promise<Ret>, options?: CircuitBreakerOptions<Args, Ret>): ProtectedFunction<Args, Ret>;
46
+ declare function createCircuitBreaker<Ret, Args extends unknown[], Fallback extends AnyFn = (...args: Args) => Promise<Ret>>(main: (...args: Args) => Promise<Ret>, options?: CircuitBreakerOptions<Fallback>): CircuitBreakerProtectedFn<Ret, Args>;
49
47
 
50
48
  export { createCircuitBreaker };
51
- export type { CircuitBreakerOptions, CircuitState, EventMap, ProtectedFunction };
49
+ export type { CircuitBreakerOptions, CircuitBreakerProtectedFn, CircuitState };
package/dist/index.mjs CHANGED
@@ -1,86 +1,79 @@
1
- import EventEmitter from 'node:events';
2
-
3
- const assertNever = (value, message = "Unexpected value") => (
4
- /* v8 ignore next */
5
- new TypeError(`${message}: ${value}`)
6
- );
1
+ const assertNever = (val, msg = "Unexpected value") => {
2
+ throw new TypeError(`${msg}: ${val}`);
3
+ };
4
+ const resolvedPromise = Promise.resolve();
5
+ const nextTick = (fn) => resolvedPromise.then(fn);
7
6
 
8
7
  function createCircuitBreaker(main, options = {}) {
9
- const events = new EventEmitter();
10
8
  const {
11
9
  errorIsFailure = () => true,
12
10
  failureThreshold = 1,
13
- fallback = () => {
14
- const cause = failureCause;
15
- const msg = cause instanceof Error ? cause.message : "Unknown";
16
- throw new Error(`CircuitOpenError: ${msg}`, { cause });
17
- },
11
+ onClose,
12
+ onOpen,
18
13
  resetAfter = 3e4
19
14
  } = options;
15
+ let fallback = options.fallback || (() => Promise.reject(failureCause));
16
+ let halfOpenPending;
20
17
  let state = "closed";
21
- let failureCause = void 0;
18
+ let failureCause;
22
19
  let failureCount = 0;
23
- let resetTimer = void 0;
20
+ let resetTimer;
21
+ function clearFailure() {
22
+ failureCause = void 0;
23
+ failureCount = 0;
24
+ }
24
25
  function openCircuit(cause) {
25
- if (state === "disposed") return;
26
- state = "open";
27
- events.emit("open", cause);
28
26
  failureCause = cause;
27
+ state = "open";
29
28
  clearTimeout(resetTimer);
30
29
  resetTimer = setTimeout(() => state = "halfOpen", resetAfter);
30
+ onOpen?.(cause);
31
31
  }
32
- function closeCircuit() {
33
- if (state === "disposed") return;
34
- if (state === "halfOpen") events.emit("close");
35
- state = "closed";
36
- failureCause = void 0;
37
- failureCount = 0;
38
- clearTimeout(resetTimer);
39
- }
40
- const mainWithEmit = async (...args) => {
41
- try {
42
- const result = await main(...args);
43
- events.emit("resolve");
44
- closeCircuit();
45
- return result;
46
- } catch (cause) {
47
- events.emit("reject", cause);
48
- throw cause;
49
- }
50
- };
51
- async function protectedFunction(...args) {
52
- if (state === "open") {
32
+ function protectedFunction(...args) {
33
+ if (state === "closed") {
34
+ const thisFallback = fallback;
35
+ return main(...args).then(
36
+ (result) => {
37
+ if (state === "closed") clearFailure();
38
+ return result;
39
+ },
40
+ (cause) => {
41
+ if (thisFallback !== fallback) throw cause;
42
+ failureCount += errorIsFailure(cause) ? 1 : 0;
43
+ if (failureCount === failureThreshold) openCircuit(cause);
44
+ return nextTick(() => protectedFunction(...args));
45
+ }
46
+ );
47
+ } else if (state === "open" || halfOpenPending) {
53
48
  return fallback(...args);
54
49
  } else if (state === "halfOpen") {
55
- return mainWithEmit(...args).catch((cause) => {
56
- openCircuit(cause);
57
- return fallback(...args);
58
- });
59
- } else if (state === "closed") {
60
- return mainWithEmit(...args).catch((cause) => {
61
- failureCause = cause;
62
- failureCount += errorIsFailure(cause) ? 1 : 0;
63
- if (failureCount >= failureThreshold) openCircuit(cause);
64
- return fallback(...args);
65
- });
66
- } else if (state === "disposed")
67
- throw new Error("Circuit breaker has been disposed");
68
- else throw assertNever(state);
50
+ const thisFallback = fallback;
51
+ return (halfOpenPending = main(...args)).finally(() => halfOpenPending = void 0).then(
52
+ (result) => {
53
+ if (thisFallback !== fallback) return result;
54
+ state = "closed";
55
+ clearFailure();
56
+ clearTimeout(resetTimer);
57
+ onClose?.();
58
+ return result;
59
+ },
60
+ (cause) => {
61
+ if (thisFallback !== fallback) throw cause;
62
+ openCircuit(cause);
63
+ return nextTick(() => protectedFunction(...args));
64
+ }
65
+ );
66
+ }
67
+ return assertNever(state);
69
68
  }
70
69
  protectedFunction.dispose = () => {
71
- events.removeAllListeners();
72
- closeCircuit();
73
- state = "disposed";
70
+ clearFailure();
71
+ clearTimeout(resetTimer);
72
+ fallback = () => Promise.reject(new ReferenceError("ERR_CIRCUIT_BREAKER_DISPOSED"));
73
+ state = "open";
74
74
  };
75
+ protectedFunction.getLatestError = () => failureCause;
75
76
  protectedFunction.getState = () => state;
76
- protectedFunction.off = (event, listener) => {
77
- events.removeListener(event, listener);
78
- return protectedFunction;
79
- };
80
- protectedFunction.on = (event, listener) => {
81
- events.addListener(event, listener);
82
- return protectedFunction;
83
- };
84
77
  return protectedFunction;
85
78
  }
86
79
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../lib/util.ts","../lib/index.ts"],"sourcesContent":["export type AnyFn = (...args: any[]) => any\n\n/**\n * `[TypeScript]` For exhaustive checks in switch statements or if/else. Add\n * this check to `default` case or final `else` to ensure all possible values\n * have been handled. If a new value is added to the type, TypeScript will\n * throw an error and the editor will underline the `value`.\n */\nexport const assertNever = (value: never, message = \"Unexpected value\") =>\n\t/* v8 ignore next */\n\tnew TypeError(`${message}: ${value}`)\n","import { type AnyFn, assertNever } from \"./util.js\"\nimport EventEmitter from \"node:events\"\n\nexport type CircuitState = \"closed\" | \"disposed\" | \"halfOpen\" | \"open\"\n\nexport interface CircuitBreakerOptions<Args extends unknown[], Ret> {\n\t/**\n\t * Whether an error should be considered a failure that could trigger\n\t * the circuit breaker. Use this to prevent certain errors from\n\t * incrementing the failure count.\n\t * \n\t * @default () => true // Every error is considered a failure\n\t */\n\terrorIsFailure?: (error: unknown) => boolean\n\n\t/**\n\t * The number of failures before the circuit breaker opens.\n\t * \n\t * @default 1 // The first error opens the circuit\n\t */\n\tfailureThreshold?: number\n\n\t/**\n\t * If provided, then all rejected calls to `main` will be forwarded to\n\t * this function instead.\n\t * \n\t * @default undefined // No fallback, throws `CircuitOpenError`\n\t */\n\tfallback?: (...args: Args) => Promise<Ret>\n\n\t/**\n\t * The amount of time to wait before allowing a half-open state.\n\t * \n\t * @default 30_000 // 30 seconds\n\t */\n\tresetAfter?: number\n}\n\nexport interface EventMap {\n\tclose: []\n\topen: [cause: unknown]\n\treject: [cause: unknown]\n\tresolve: []\n}\n\nexport interface ProtectedFunction<Args extends unknown[], Ret> {\n\t(...args: Args): Promise<Ret>\n\n\t/** Free memory and stop timers */\n\tdispose(): void\n\n\t/** Get the current state of the circuit breaker */\n\tgetState(): CircuitState\n\n\t/** Remove a listener from the circuit breaker */\n\toff<T extends keyof EventMap>(\n\t\tevent: T,\n\t\tlistener: (...args: EventMap[T]) => void\n\t): this\n\n\t/** Add a listener to the circuit breaker */\n\ton<T extends keyof EventMap>(\n\t\tevent: T,\n\t\tlistener: (...args: EventMap[T]) => void\n\t): this\n}\n\nexport function createCircuitBreaker<Args extends unknown[], Ret>(\n\tmain: (...args: Args) => Promise<Ret>,\n\toptions: CircuitBreakerOptions<Args, Ret> = {}\n): ProtectedFunction<Args, Ret> {\n\tconst events = new EventEmitter<EventMap>()\n\tconst {\n\t\terrorIsFailure = () => true,\n\t\tfailureThreshold = 1,\n\t\tfallback = () => {\n\t\t\tconst cause = failureCause\n\t\t\tconst msg = cause instanceof Error ? cause.message : \"Unknown\"\n\t\t\tthrow new Error(`CircuitOpenError: ${msg}`, { cause })\n\t\t},\n\t\tresetAfter = 30_000,\n\t} = options\n\tlet state: CircuitState = \"closed\"\n\tlet failureCause: unknown | undefined = undefined\n\tlet failureCount = 0\n\tlet resetTimer: NodeJS.Timeout | undefined = undefined\n\n\t/**\n\t * Break the circuit and wait for a reset\n\t */\n\tfunction openCircuit(cause: unknown) {\n\t\tif (state === \"disposed\") return\n\t\tstate = \"open\"\n\t\tevents.emit(\"open\", cause)\n\t\tfailureCause = cause\n\t\tclearTimeout(resetTimer)\n\t\tresetTimer = setTimeout(() => (state = \"halfOpen\"), resetAfter)\n\t}\n\n\t/**\n\t * Restart the circuit and resume normal operation\n\t */\n\tfunction closeCircuit() {\n\t\tif (state === \"disposed\") return\n\t\tif (state === \"halfOpen\") events.emit(\"close\")\n\t\tstate = \"closed\"\n\t\tfailureCause = undefined\n\t\tfailureCount = 0\n\t\tclearTimeout(resetTimer)\n\t}\n\n\tconst mainWithEmit = async (...args: Args) => {\n\t\ttry {\n\t\t\tconst result = await main(...args)\n\t\t\tevents.emit(\"resolve\")\n\t\t\tcloseCircuit()\n\t\t\treturn result\n\t\t} catch (cause) {\n\t\t\tevents.emit(\"reject\", cause)\n\t\t\tthrow cause\n\t\t}\n\t}\n\n\t/**\n\t * Wrap calls to `main` with circuit breaker logic\n\t */\n\tasync function protectedFunction(...args: Args): Promise<Ret> {\n\t\t// Use the fallback while the circuit is open\n\t\tif (state === \"open\") {\n\t\t\treturn fallback(...args)\n\t\t}\n\n\t\t// While the circuit is half-open, try the main function once. If it\n\t\t// success, close the circuit and resume normal operation. If it fails,\n\t\t// re-open the circuit and run the fallback instead.\n\t\telse if (state === \"halfOpen\") {\n\t\t\treturn mainWithEmit(...args).catch((cause) => {\n\t\t\t\topenCircuit(cause)\n\t\t\t\treturn fallback(...args)\n\t\t\t})\n\t\t}\n\n\t\t// Normal operation when circuit is closed. If an error occurs, keep track\n\t\t// of the failure count and open the circuit if it exceeds the threshold.\n\t\telse if (state === \"closed\") {\n\t\t\treturn mainWithEmit(...args).catch((cause) => {\n\t\t\t\tfailureCause = cause\n\t\t\t\tfailureCount += errorIsFailure(cause) ? 1 : 0\n\t\t\t\tif (failureCount >= failureThreshold) openCircuit(cause)\n\t\t\t\treturn fallback(...args)\n\t\t\t})\n\t\t}\n\n\t\t// Shutting down...\n\t\telse if (state === \"disposed\")\n\t\t\tthrow new Error(\"Circuit breaker has been disposed\")\n\t\telse throw assertNever(state)\n\t}\n\n\tprotectedFunction.dispose = () => {\n\t\tevents.removeAllListeners()\n\t\tcloseCircuit()\n\t\tstate = \"disposed\"\n\t}\n\n\tprotectedFunction.getState = () => state\n\n\tprotectedFunction.off = (event: keyof EventMap, listener: AnyFn) => {\n\t\tevents.removeListener(event, listener)\n\t\treturn protectedFunction\n\t}\n\n\tprotectedFunction.on = (event: keyof EventMap, listener: AnyFn) => {\n\t\tevents.addListener(event, listener)\n\t\treturn protectedFunction\n\t}\n\n\treturn protectedFunction\n}\n"],"names":[],"mappings":";;AACO,MAAM,WAAW,GAAG,CAAC,KAAK,EAAE,OAAO,GAAG,kBAAkB;AAC/D;AACA,EAAE,IAAI,SAAS,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;AACtC,CAAC;;ACDM,SAAS,oBAAoB,CAAC,IAAI,EAAE,OAAO,GAAG,EAAE,EAAE;AACzD,EAAE,MAAM,MAAM,GAAG,IAAI,YAAY,EAAE;AACnC,EAAE,MAAM;AACR,IAAI,cAAc,GAAG,MAAM,IAAI;AAC/B,IAAI,gBAAgB,GAAG,CAAC;AACxB,IAAI,QAAQ,GAAG,MAAM;AACrB,MAAM,MAAM,KAAK,GAAG,YAAY;AAChC,MAAM,MAAM,GAAG,GAAG,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,SAAS;AACpE,MAAM,MAAM,IAAI,KAAK,CAAC,CAAC,kBAAkB,EAAE,GAAG,CAAC,CAAC,EAAE,EAAE,KAAK,EAAE,CAAC;AAC5D,IAAI,CAAC;AACL,IAAI,UAAU,GAAG;AACjB,GAAG,GAAG,OAAO;AACb,EAAE,IAAI,KAAK,GAAG,QAAQ;AACtB,EAAE,IAAI,YAAY,GAAG,MAAM;AAC3B,EAAE,IAAI,YAAY,GAAG,CAAC;AACtB,EAAE,IAAI,UAAU,GAAG,MAAM;AACzB,EAAE,SAAS,WAAW,CAAC,KAAK,EAAE;AAC9B,IAAI,IAAI,KAAK,KAAK,UAAU,EAAE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C1B;;;;"}
1
+ {"version":3,"file":"index.mjs","sources":["../lib/util.ts","../lib/index.ts"],"sourcesContent":["export type AnyFn = (...args: any[]) => any\n\n/**\n * `[TypeScript]` For exhaustive checks in switch statements or if/else. Add\n * this check to `default` case or final `else` to ensure all possible values\n * have been handled. If a new value is added to the type, TypeScript will\n * throw an error and the editor will underline the `value`.\n */\n/* v8 ignore next 3 */\nexport const assertNever = (val: never, msg = \"Unexpected value\") => {\n\tthrow new TypeError(`${msg}: ${val}`)\n}\n\n/**\n * Returns a promise that resolves after the specified number of milliseconds.\n */\nexport const delayMs = (ms: number): Promise<void> =>\n\tnew Promise((next) => setTimeout(next, ms))\n\nconst resolvedPromise = Promise.resolve()\n\nexport const nextTick = <T>(fn: () => T | PromiseLike<T>): Promise<T> =>\n\tresolvedPromise.then(fn)\n","import { type AnyFn, assertNever, nextTick } from \"./util.js\"\n\nexport type CircuitState = \"closed\" | \"halfOpen\" | \"open\"\n\nexport interface CircuitBreakerOptions<Fallback extends AnyFn = AnyFn> {\n\t/**\n\t * Whether an error should be considered a failure that could trigger\n\t * the circuit breaker. Use this to prevent certain errors from\n\t * incrementing the failure count.\n\t *\n\t * @default () => true // Every error is considered a failure\n\t */\n\terrorIsFailure?: (error: unknown) => boolean\n\n\t/**\n\t * The number of failures before the circuit breaker opens.\n\t *\n\t * @default 1 // The first error opens the circuit\n\t */\n\tfailureThreshold?: number\n\n\t/**\n\t * If provided, then all rejected calls to `main` will be forwarded to\n\t * this function instead.\n\t *\n\t * @default undefined // No fallback, errors are propagated\n\t */\n\tfallback?: Fallback\n\n\t/** Called when the circuit breaker is closed */\n\tonClose?: () => void\n\n\t/** Called when the circuit breaker is opened */\n\tonOpen?: (cause: unknown) => void\n\n\t/**\n\t * The amount of time to wait before allowing a half-open state.\n\t *\n\t * @default 30_000 // 30 seconds\n\t */\n\tresetAfter?: number\n}\n\nexport interface CircuitBreakerProtectedFn<\n\tRet = unknown,\n\tArgs extends unknown[] = never[]\n> {\n\t(...args: Args): Promise<Ret>\n\n\t/** Free memory and stop timers */\n\tdispose(): void\n\n\t/** Get the last error which triggered the circuit breaker */\n\tgetLatestError(): unknown | undefined\n\n\t/** Get the current state of the circuit breaker */\n\tgetState(): CircuitState\n}\n\nexport function createCircuitBreaker<\n\tRet,\n\tArgs extends unknown[],\n\tFallback extends AnyFn = (...args: Args) => Promise<Ret>\n>(\n\tmain: (...args: Args) => Promise<Ret>,\n\toptions: CircuitBreakerOptions<Fallback> = {}\n): CircuitBreakerProtectedFn<Ret, Args> {\n\tconst {\n\t\terrorIsFailure = () => true,\n\t\tfailureThreshold = 1,\n\t\tonClose,\n\t\tonOpen,\n\t\tresetAfter = 30_000,\n\t} = options\n\tlet fallback = options.fallback || (() => Promise.reject(failureCause))\n\tlet halfOpenPending: Promise<unknown> | undefined\n\tlet state: CircuitState = \"closed\"\n\tlet failureCause: unknown | undefined\n\tlet failureCount = 0\n\tlet resetTimer: NodeJS.Timeout | undefined\n\n\tfunction clearFailure() {\n\t\tfailureCause = undefined\n\t\tfailureCount = 0\n\t}\n\n\t/**\n\t * Break the circuit and wait for a reset\n\t */\n\tfunction openCircuit(cause: unknown) {\n\t\tfailureCause = cause\n\t\tstate = \"open\"\n\t\tclearTimeout(resetTimer)\n\t\tresetTimer = setTimeout(() => (state = \"halfOpen\"), resetAfter)\n\t\tonOpen?.(cause)\n\t}\n\n\t/**\n\t * Wrap calls to `main` with circuit breaker logic\n\t */\n\tfunction protectedFunction(...args: Args): Promise<Ret> {\n\t\t// Normal operation when circuit is closed. If an error occurs, keep track\n\t\t// of the failure count and open the circuit if it exceeds the threshold.\n\t\tif (state === \"closed\") {\n\t\t\tconst thisFallback = fallback\n\t\t\treturn main(...args).then(\n\t\t\t\t(result) => {\n\t\t\t\t\t// Reset accumulated failures if circuit is still closed\n\t\t\t\t\tif (state === \"closed\") clearFailure()\n\t\t\t\t\treturn result\n\t\t\t\t},\n\t\t\t\t(cause: unknown) => {\n\t\t\t\t\t// Was the circuit breaker disposed while the call was in flight?\n\t\t\t\t\tif (thisFallback !== fallback) throw cause\n\t\t\t\t\tfailureCount += errorIsFailure(cause) ? 1 : 0\n\t\t\t\t\tif (failureCount === failureThreshold) openCircuit(cause)\n\t\t\t\t\treturn nextTick(() => protectedFunction(...args))\n\t\t\t\t}\n\t\t\t)\n\t\t}\n\n\t\t// Use the fallback while the circuit is open, or if a half-open trial\n\t\t// attempt was already made.\n\t\telse if (state === \"open\" || halfOpenPending) {\n\t\t\treturn fallback(...args)\n\t\t}\n\n\t\t// If the circuit is half-open, make one attempt. If it succeeds, close\n\t\t// the circuit and resume normal operation. If it fails, re-open the\n\t\t// circuit and run the fallback instead.\n\t\telse if (state === \"halfOpen\") {\n\t\t\tconst thisFallback = fallback\n\t\t\treturn (halfOpenPending = main(...args))\n\t\t\t\t.finally(() => (halfOpenPending = undefined))\n\t\t\t\t.then(\n\t\t\t\t\t(result) => {\n\t\t\t\t\t\t// Was the circuit breaker disposed while the call was\n\t\t\t\t\t\t// in flight?\n\t\t\t\t\t\tif (thisFallback !== fallback) return result\n\t\t\t\t\t\t// Close the circuit and resume normal operation\n\t\t\t\t\t\tstate = \"closed\"\n\t\t\t\t\t\tclearFailure()\n\t\t\t\t\t\tclearTimeout(resetTimer)\n\t\t\t\t\t\tonClose?.()\n\t\t\t\t\t\treturn result\n\t\t\t\t\t},\n\t\t\t\t\t(cause: unknown) => {\n\t\t\t\t\t\t// Was the circuit breaker disposed while the call was\n\t\t\t\t\t\t// in flight?\n\t\t\t\t\t\tif (thisFallback !== fallback) throw cause\n\t\t\t\t\t\topenCircuit(cause)\n\t\t\t\t\t\treturn nextTick(() => protectedFunction(...args))\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t/* v8 ignore next */\n\t\t}\n\n\t\t// exhaustive check\n\t\t/* v8 ignore next */\n\t\treturn assertNever(state)\n\t}\n\n\tprotectedFunction.dispose = () => {\n\t\tclearFailure()\n\t\tclearTimeout(resetTimer)\n\t\tfallback = () =>\n\t\t\tPromise.reject(new ReferenceError(\"ERR_CIRCUIT_BREAKER_DISPOSED\"))\n\t\tstate = \"open\"\n\t}\n\n\tprotectedFunction.getLatestError = () => failureCause\n\n\tprotectedFunction.getState = () => state\n\n\treturn protectedFunction\n}\n"],"names":[],"mappings":"AACO,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE,GAAG,GAAG,kBAAkB,KAAK;AAC9D,EAAE,MAAM,IAAI,SAAS,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC,CAAC;AACvC,CAAC;AAED,MAAM,eAAe,GAAG,OAAO,CAAC,OAAO,EAAE;AAClC,MAAM,QAAQ,GAAG,CAAC,EAAE,KAAK,eAAe,CAAC,IAAI,CAAC,EAAE,CAAC;;ACJjD,SAAS,oBAAoB,CAAC,IAAI,EAAE,OAAO,GAAG,EAAE,EAAE;AACzD,EAAE,MAAM;AACR,IAAI,cAAc,GAAG,MAAM,IAAI;AAC/B,IAAI,gBAAgB,GAAG,CAAC;AACxB,IAAI,OAAO;AACX,IAAI,MAAM;AACV,IAAI,UAAU,GAAG;AACjB,GAAG,GAAG,OAAO;AACb,EAAE,IAAI,QAAQ,GAAG,OAAO,CAAC,QAAQ,KAAK,MAAM,OAAO,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;AACzE,EAAE,IAAI,eAAe;AACrB,EAAE,IAAI,KAAK,GAAG,QAAQ;AACtB,EAAE,IAAI,YAAY;AAClB,EAAE,IAAI,YAAY,GAAG,CAAC;AACtB,EAAE,IAAI,UAAU;AAChB,EAAE,SAAS,YAAY,GAAG;AAC1B,IAAI,YAAY,GAAG,MAAM;AACzB,IAAI,YAAY,GAAG,CAAC;AACpB,EAAE;AACF,EAAE,SAAS,WAAW,CAAC,KAAK,EAAE;AAC9B,IAAI,YAAY,GAAG,KAAK;AACxB,IAAI,KAAK,GAAG,MAAM;AAClB,IAAI,YAAY,CAAC,UAAU,CAAC;AAC5B,IAAI,UAAU,GAAG,UAAU,C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U,YAAY,CAAC,UAAU,CAAC;AAClC,UAAU,OAAO,IAAI;AACrB,UAAU,OAAO,MAAM;AACvB,QAAQ,CAAC;AACT,QAAQ,CAAC,KAAK,KAAK;AACnB,UAAU,IAAI,YAAY,KAAK,QAAQ,EAAE,MAAM,KAAK;AACpD,UAAU,WAAW,CAAC,KAAK,CAAC;AAC5B,UAAU,OAAO,QAAQ,CAAC,MAAM,iBAAiB,CAAC,GAAG,IAAI,CAAC,CAAC;AAC3D,QAAQ;AACR,OAAO;AACP,IAAI;AACJ,IAAI,OAAO,WAAW,CAAC,KAAK,CAAC;AAC7B,EAAE;AACF,EAAE,iBAAiB,CAAC,OAAO,GAAG,MAAM;AACpC,IAAI,YAAY,EAAE;AAClB,IAAI,YAAY,CAAC,UAAU,CAAC;AAC5B,IAAI,QAAQ,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,IAAI,cAAc,CAAC,8BAA8B,CAAC,CAAC;AACvF,IAAI,KAAK,GAAG,MAAM;AAClB,EAAE,CAAC;AACH,EAAE,iBAAiB,CAAC,cAAc,GAAG,MAAM,YAAY;AACvD,EAAE,iBAAiB,CAAC,QAAQ,GAAG,MAAM,KAAK;AAC1C,EAAE,OAAO,iBAAiB;AAC1B;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "breaker-box",
3
- "version": "1.0.0",
3
+ "version": "3.0.0",
4
4
  "description": "A zero-dependency circuit breaker implementation for Node.js",
5
5
  "repository": "github:sirlancelot/breaker-box",
6
6
  "main": "./dist/index.cjs",
@@ -20,14 +20,16 @@
20
20
  "dist"
21
21
  ],
22
22
  "scripts": {
23
- "build": "pkgroll --clean-dist --src lib --target=node18 --sourcemap",
23
+ "build": "pkgroll --clean-dist --src lib --target=node18 --sourcemap --env.NODE_ENV=production",
24
24
  "dev": "vitest",
25
25
  "prepublishOnly": "npm run build",
26
26
  "test": "vitest --run"
27
27
  },
28
28
  "keywords": [
29
29
  "circuit-breaker",
30
- "breaker-box"
30
+ "fallback",
31
+ "reliability",
32
+ "try-again"
31
33
  ],
32
34
  "author": "Matthew Pietz <sirlancelot@gmail.com>",
33
35
  "license": "ISC",