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

p-circuit-breaker

v0.0.3

Published

A fast circuit breaker for promise

Downloads

5,302

Readme

Node.js Circuit Breaker

Description

This project is an implementation of a Circuit Breaker to ensure the resilience and stability of services that make calls to external resources. A Circuit Breaker is a design pattern used to detect failures and encapsulate the logic of preventing a failure from constantly recurring, helping to maintain system stability. It allows controlling and isolating failures in distributed systems, helping to prevent total system degradation.

Installation

To install the dependencies, run the following command:

npm install p-circuit-breaker

Initial Configuration

You can instantiate a Circuit Breaker with the following options:

import { CircuitBreaker } from 'p-circuit-breaker';

const breaker = new CircuitBreaker({
  failureThresholdPercentage: 50,
  windowSize: 10000,
  timeout: 5000
});

Usage Examples

Here is an example of how to use the Circuit Breaker to protect an asynchronous operation:

function fetchTodo() {
    return fetch('https://jsonplaceholder.typicode.com/todos/1');
}

async function exampleFunction() {
    const breaker = new CircuitBreaker({ timeout: 2000 });
    try {
        const response = await breaker.execute(fetchTodo);
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('Request failed:', error);
    }
}

This example shows how to catch failures during the execution of a function protected by the Circuit Breaker.

Circuit Breaker Concepts

The Circuit Breaker can be in three different states:

  • Closed: All requests are allowed normally.
  • Open: Requests are immediately blocked to avoid overloading the resource.
  • Half-Open: An intermediate state where only a few requests are allowed to test if the resource has recovered.

For more information, refer to Martin Fowler's article on Circuit Breaker.

Configuration Options

  • failureThresholdPercentage: Percentage of failures allowed before opening the circuit. (default: 5)
  • windowSize: Number of requests considered in the window to calculate the failure rate. (default: 60000 ms)
  • timeout: Maximum execution time before considering the request failed. (default: undefined)
  • resetTimeout: Time after which the Circuit Breaker will attempt to change from "open" to "half-open" to check resource recovery. (default: undefined)
  • isError: Custom function to determine if an error should count as a failure. (default: undefined)
  • autoRenewAbortController: Defines whether the AbortController should be automatically renewed for each new request when the circuit is closed. (default: false)
  • failureThresholdCount: Alternative to failureThresholdPercentage; opens the circuit when failures reach this count within the window. (default: 0)
  • retryAttempts: Number of allowed retry attempts in the half-open state before opening the circuit again if failures persist. (default: 1)
  • successThreshold: Number of consecutive successes required in the half-open state to fully close the circuit. (default: 1)

Emitted Events

The Circuit Breaker emits different events during its execution:

  • 'open': Occurs when the circuit is opened due to excessive failures.
  • 'close': Occurs when the circuit closes and resumes normal execution.
  • 'halfOpen': Occurs when the circuit enters the half-open state.
  • 'success': Emitted when a request is successful.
  • 'error': Emitted when a request fails.

You can use these events to log or trigger other actions:

breaker.event.on('open', () => {
  console.log('Circuit opened');
});

breaker.event.on('close', () => {
  console.log('Circuit closed');
});

breaker.event.on('halfOpen', () => {
  console.log('Circuit is half-open: Testing if the resource has recovered');
});

breaker.event.on('success', () => {
  console.log('Request succeeded while the circuit was closed or half-open');
});

breaker.event.on('error', () => {
  console.log('Request failed: Recording failure in the circuit');
});

Contribution

Contributions are welcome! Please follow these steps to contribute:

  1. Fork this repository.
  2. Create a branch for your feature (git checkout -b my-feature).
  3. Submit a pull request for us to review your changes.

License

This project is licensed under the MIT license. See the LICENSE file for more details.

Tests

To run the tests:

npm test