Home

Awesome

<img align="right" width="350" height="auto" src="https://martinfowler.com/bliki/images/circuitBreaker/state.png">

easy-breaker

js-standard-style Build Status Coverage Status

A simple and low overhead circuit breaker utility.

<a name="install"></a>

Install

npm i easy-breaker

<a name="usage"></a>

Usage

Require the library and initialize it with the function you want to put under the Circuit Breaker.

const EasyBreaker = require('easy-breaker')
const simpleGet = require('simple-get')

const get = EasyBreaker(simpleGet)

get('http://example.com', function (err, res) {
  if (err) throw err
  console.log(res.statusCode)
})

If the function times out, the error will be a TimeoutError.<br> If the threshold has been reached and the circuit is open the error will be a CircuitOpenError.

You can access the errors constructors with require('easy-breaker').errors.<br> You can access the state constants with require('easy-breaker').states.

Options

You can pass some custom option to change the default behavior of EasyBreaker:

const EasyBreaker = require('easy-breaker')
const simpleGet = require('simple-get')

// the following options object contains the default values
const get = EasyBreaker(simpleGet, {
  threshold: 5
  timeout: 1000 * 10
  resetTimeout: 1000 * 10
  context: null,
  maxEventListeners: 100
  promise: false
})

<a name="promises"></a>

Promises

Promises and async-await are supported as well!<br/> Just pass the option { promise: true } and you are done!<br/> Note the if you use the promise version of the api also the function you are wrapping should return a promise.

const EasyBreaker = require('easy-breaker')
const got = require('got')

const get = EasyBreaker(got, { promise: true })

get('http://example.com')
  .then(console.log)
  .catch(console.log)

<a name="events"></a>

Events

This circuit breaker is an event emitter, if needed you can listen to its events:

<a name="caveats"></a>

Caveats

Run a timer for every function is pretty expensive, especially if you are running the code in a heavy load environment.<br/> To fix this problem and get better performances, EasyBreaker uses an atomic clock, in other words uses an interval that emits a tick event every timeout / 2 milliseconds.<br> Every running functions listens for that event and if the number of ticks received is higher than 3 it will return a TimeoutError.

Acknowledgements

Image curtesy of Martin Fowler.

<a name="license"></a>

License

MIT<br>

Copyright © 2018 Tomas Della Vedova