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

@stinoz/retry-policy

v2.0.0

Published

A retry policy framework for javascript

Downloads

199

Readme

CircleCI codecov

retry-policy

This library tries to help with making applications tolerant for temporary errors.

Features

  • Use waitStrategies to specify timeouts between retries
  • Use stopStrategies to specify number of attempts
  • Use errorDetectionStrategies to recognize retryable errors
  • Easily make your own strategies
  • Written in Typescript
  • Has an interceptor for Axios! (axios-retry-policy)

How to install

npm install @stinoz/retry-policy

Example

// import RetryPolicy and strategies 
const {
    afterAttemptStopStrategy,
    exponentialWaitStrategy,
    RetryPolicy} = require('@stinoz/retry-policy');
  
// Build the retry policy  
const retryPolicy = new RetryPolicy({
    stopStrategy: afterAttemptStopStrategy({attempts: 5}),
    waitStrategy: exponentialWaitStrategy({timeout: 500}),
});
  
// execute the unreliable action
retryPolicy.execute(() => {
    return unreliableAction();
});

API

RetryPolicy

The retry policy is responsible for executing retryable actions. Currently it only supports promise based actions (which should be easy to work around)

Make a new RetryPolicy

All parameters can be ommited.

These are the defaults:

const retryPolicy = new RetryPolicy({
    stopStrategy: neverStopStrategy(),
    waitStrategy: linearWaitStrategy({timeout: 100, slope: 100}),
    errorDetectionStrategies: [allErrorDetectionStrategy()],
});

Execute an action

Make sure to return the promise. All data of this promise will be passed in case it succeeds. In case it fails the last error will be passed unmodified.

// execute the unreliable action
retryPolicy.execute(() => {
    return unreliableAction();
})
.then((response) => {
    // this part is reached when:
    // - the action was successfull
    // - the action first was unsuccessfull but after x retries was
      
    console.log('success', response);
})
.catch((lastError) => {
    // This part is reached when:
    // - the action failed with a non retryable error
    // - the action was retried but the max attempts was reached
      
    console.error('failed', lastError);
});

WaitStrategy

Fixed (default)

This strategy keeps it simple and always uses the same timout.

const retryPolicy = new RetryPolicy({
    waitStrategy: fixedWaitStrategy({
        timeout: 100
    }),
});

Linear

This strategy increases its timeout steady: e.g. 200, 400, 600

const retryPolicy = new RetryPolicy({
    waitStrategy: linearWaitStrategy({
        timeout: 100, 
        slope: 1
    }),
});

Exponential

This strategy increases its timeout exponentially: e.g. 200, 400, 800

const retryPolicy = new RetryPolicy({
    waitStrategy: exponentialWaitStrategy({
        timeout: 100, 
        exponent: 2
    }),
});

Series

Pass an array with timeouts which will be used in order.

const retryPolicy = new RetryPolicy({
    waitStrategy: seriesWaitStrategy({
        delays: [100, 200, 600, 3000],
    }),
});

Make your own

In case you need to base your retry time on Retry-After headers, you can use the lastError.

const retryPolicy = new RetryPolicy({
    waitStrategy: (retryCount, lastError) => retryCount * 100 + Math.PI
});

StopStrategy

It is always advisable to not try infinitely. Using a stop strategy you can set when to stop.

NeverStopStrategy (default)

This strategy will never stop until it succeeds.

const retryPolicy = new RetryPolicy({
    stopStrategy: neverStopStrategy(),
});

AfterAttemptStopStrategy

When the number of attempts is reached it will stop.

const retryPolicy = new RetryPolicy({
    stopStrategy: afterAttemptStopStrategy({
        attempt: 10,
    }),
});

Make your own

const retryPolicy = new RetryPolicy({
    stopStrategy: (retryCount) => retryCount > 5 || retryCount + previousRetryCounts > 100,
});

ErrorDetectionStrategy

One or more ErrorDetectionStrategies can be set to filter errors.

AllErrorDetectionStrategy (default)

Simple sees all errors as retryable. As this is the default strategy it can be ommitted.

const retryPolicy = new RetryPolicy({
    errorDetectionStrategies: [
        allErrorDetectionStrategy(
    )],
});

GenericErrorDetectionStrategy

This strategy can be used to detect errors by class name.

const retryPolicy = new RetryPolicy({
    errorDetectionStrategies: [
        genericErrorDetectionStrategy({
            errors: [RangeError],
        }
    )],
});

Make your own

const retryPolicy = new RetryPolicy({
    errorDetectionStrategies: [
        (error) => error.message === 'My Retryable Error'
    ],
});

Custom strategy with parameters

When you want to make your own strategy that accepts parameters you can use this method:

const myWaitStrategy = (paramA) {
    return (retryCount) {
        return 500 * retryCount + paramA;
    }
}
  
const retryPolicy = new RetryPolicy({
    waitStrategy: myWaitStrategy(5000),
});