circuit-state
A flexible circuit breaker state machine.
The intent of this module is to provide a means of tracking a circuit breaker without forming opinions about how something is called. Use this API to blend circuit breaking into anything.
The reasoning behind this module is that too many libraries mix in the concept of timeouts, fallbacks, and promises vs callbacks into the circuit breaker pattern. These are implementation details that ultimately will vary from use case to use case, whereas the state machine itself will not.
What is a circuit breaker?
A circuit breaker is used to provide stability and prevent cascading failures in distributed systems. These should be used in conjunction with judicious timeouts at the interfaces between remote systems to prevent the failure of a single component from bringing down all components. -- Akka Documentation on Circuit Breaker
API
CircuitBreakerState(options)
- Constructor. Options:maxFailures
- Maximum number of failures before circuit breaker flips open. Default3
.resetTime
- Time in ms before an open circuit breaker returns to a half-open state. Default10000
.resetManually
- Boolean value representing whether or not to attempt reset manually vs on timer. Defaultfalse
.
CircuitBreakerState.create(options)
- Creates a newCircuitBreakerState
instance.
Instance functions:
succeed()
- Record a success.fail()
- Record a failure. This may trip open the circuit breaker.test()
- Tests for the state being open. If so, returns an error (may be returned to user).tryReset()
- Flips to half-open and cancels reset timer (if any).open
- Istrue
if this circuit breaker is open. Read-only.closed
- Istrue
if this circuit breaker is closed. Read-only.halfOpen
- Istrue
if this circuit breaker is half-open. Read-only.stats
- The stats tracker object.maxFailures
- Read-only.resetTime
- Read-only.
Stats object:
increment(name)
- Increment the givenname
count.reset(name)
- Reset the givenname
count.resetAll()
- Reset all counts.snapshot()
- Take a snapshot of the stats object.
Example usage
Wrapping a callback based function.
const CircuitBreakerState = ; { this_func = func; this_cb = ; } { const callback = argsargslength - 1; const error = this_cb; // Fail fast if error ; return; // Wrap original callback argsargslength - 1 = { if error // Record a failure this_cb; ; return; // Record a success this_cb; ; }; return this_func; }
Here's an example with wrapping promises.
{ this_promise = promise; this_cb = ; } async { const error = this_cb; if error throw error; try const result = await this; this_cb; return result; catch error this_cb; throw error; }