npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

circuit-state

v1.0.0

Published

Circuit breaker state machine.

Downloads

97

Readme

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

Circuit Breaker State Machine

API

  • CircuitBreakerState(options) - Constructor. Options:
    • maxFailures - Maximum number of failures before circuit breaker flips open. Default 3.
    • resetTime - Time in ms before an open circuit breaker returns to a half-open state. Default 10000.
    • resetManually - Boolean value representing whether or not to attempt reset manually vs on timer. Default false.
  • CircuitBreakerState.create(options) - Creates a new CircuitBreakerState 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 - Is true if this circuit breaker is open. Read-only.
  • closed - Is true if this circuit breaker is closed. Read-only.
  • halfOpen - Is true 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 given name count.
  • reset(name) - Reset the given name count.
  • resetAll() - Reset all counts.
  • snapshot() - Take a snapshot of the stats object.

Example usage

Wrapping a callback based function.

const CircuitBreakerState = require('circuit-state');

class Circuit {
    constructor(func) {
        this._func = func;
        this._cb = new CircuitBreakerState();
    }
    run(...args) {
        const callback = args[args.length - 1];

        const error = this._cb.test();

        // Fail fast
        if (error) {
            callback(error);
            return;
        }

        // Wrap original callback
        args[args.length - 1] = (error, ...result) => {
            if (error) {
                // Record a failure
                this._cb.fail();
                callback(error);
                return;
            }
            // Record a success
            this._cb.succeed();
            callback(null, ...result);
        };

        return this._func.call(null, ...args);
    }
}

Here's an example with wrapping promises.

class Circuit {
    constructor(promise) {
        this._promise = promise;
        this._cb = new CircuitBreakerState();
    }
    async run(...args) {
        const error = this._cb.test();

        if (error) {
            throw error;
        }

        try {
            const result = await this._promise(...args);
            this._cb.succeed();
            return result;
        }
        catch (error) {
            this._cb.fail();
            throw error;
        }
    }
}