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

@segment/localstorage-retry

v1.3.0

Published

[![Circle CI](https://circleci.com/gh/segmentio/localstorage-retry.svg?style=shield&circle-token=26daea4c3c8e5645f15841fdda51f14386bc5302)](https://circleci.com/gh/segmentio/localstorage-retry)

Downloads

111,703

Maintainers

harksinghharksinghfhalim-segmentfhalim-segmentcfreecfreeldelossantosldelossantoshjoonpmhjoonpmceline-segmentceline-segmentpmcanseco-segmentpmcanseco-segmentmasiramasiraamillet89amillet89cholt002cholt002av-segmentav-segmentaghotikaraghotikarvikrant-segmentvikrant-segmentlarryatsegmentlarryatsegmentscruwys1scruwys1kyliepedersenkyliepedersenjinaparkjinaparkcdignam-segmentcdignam-segmentsegmentiosegmentiojrupasinghejrupasingheshayan-golafshanishayan-golafshanilateefatlateefatrajulvaderarajulvaderayash-twilioyash-twiliosowjanyasegmentsowjanyasegmentebru.odokebru.odokryanligonryanligonlpediredlalpediredlabrookstaylorjrbrookstaylorjrnithan-twilionithan-twiliodean-huynhdean-huynhwdbettswdbettsn2parkon2parkojayakrishnannairjayakrishnannairrhall-twiliorhall-twiliokarimkeshwanikarimkeshwanityson_segmenttyson_segmentjgabe13jgabe13bgamwellbgamwellpoojasegmentpoojasegmentmaryam.sharifmaryam.sharifwally.tgwally.tgsalolivaressalolivareserikdwerikdwchenxiangzhangchenxiangzhangjusteenjusteenmericssonmericssonprayansh-segmenttprayansh-segmenttjeremylarkinjeremylarkinbsneedbsneeddanieljackinsdanieljackinssegment-sethsegment-sethsayan-das-insayan-das-injames9446james9446priscilla.giattipriscilla.giattinlsunnlsundrew-thompsondrew-thompsonsegment-jsinghsegment-jsinghmcoulibalimcoulibaliandrius-segmentandrius-segmentvalerieernstvalerieernstnithin-bennynithin-bennyainatancincoainatancincoskondamuriskondamuriclintz.segclintz.segreplateroreplateroslenin-twilioslenin-twilioakashyap91akashyap91csayusocsayusoseanhan-segmentseanhan-segmentnevermore2022nevermore2022gilomergilomermarcelopvmarcelopveric.rognereric.rognerkdharaiyakdharaiyajon.anderson-at-segment.comjon.anderson-at-segment.comstacy.songstacy.songrexatsegmentrexatsegmentnickaguilarnickaguilarbradenbeckerbradenbeckerreneewangreneewangdan.laskydan.laskysam.tapiasam.tapialnambalnambavikramkumar19vikramkumar19mpriyad25mpriyad25jeremy.parkerjeremy.parkersmidgessmidgesnageshgolemnageshgolemsudojatinsudojatinpmaidpmaidsethsegmentsethsegmentjair.avilesjair.avilesmanali-bhosalemanali-bhosaleelmoselyeeelmoselyeechtoombschtoombspeterdemartinipeterdemartinivincen7tranvincen7tranmayur-pitalemayur-pitalelfdelossantoslfdelossantosemmy.byrneemmy.byrnefelttripfelttripsa-jsootersa-jsooterlluque-twiliolluque-twiliokevinburkesegmentkevinburkesegmentafsha-nazim-segafsha-nazim-segsong4yousong4youdavid.anusontarangkul.segmentdavid.anusontarangkul.segmentjyim008jyim008michaelghsegmichaelghsegacharles14acharles14aishikawakiaishikawakitwjosiahtwjosiahtanya.gupta.segmenttanya.gupta.segmentsindhusegmentsindhusegmentprabhnoor1997prabhnoor1997chihchun-twiliochihchun-twiliopmiller-twiliopmiller-twiliovbatanovvbatanovsimpixelatedsimpixelatedmcullenmeyermcullenmeyerneeharikakondipatineeharikakondipatieric-hydeeric-hydearunlalam-segmentarunlalam-segmentmschaszbergermschaszbergershuvrajit9904shuvrajit9904abhinavsurekaabhinavsurekavaradarajan-twvaradarajan-twimmanojimmanojblangtwilioblangtwiliojsh-wujsh-wujahood-twiliojahood-twiliosethnutetwiliosethnutetwiliorrivera-segmentrrivera-segmentsegment-adminsegment-adminbgillanbgillantcgilberttcgilbertmckern_segmentmckern_segmentmaneesh.dharma29maneesh.dharma29joetessyjoetessygkochar123gkochar123dominicbarnesdominicbarnesmugelstadmugelstadjalexy12jalexy12lerahulramlerahulrampmuninpmuninwhaider_twiliowhaider_twilioariel.silvestriariel.silvestris3gm3nts3gm3ntama0223ama0223shraddha-twilioshraddha-twiliomichelrmichelrbrandon.scott-segmentbrandon.scott-segmentjfehrman.segmentjfehrman.segmentprayansh-twilioprayansh-twiliodangmai-segmentdangmai-segmentaaronklishaaronklishbrianhumphreystwiliobrianhumphreystwiliormukundanrmukundanashwitha.bgashwitha.bgryanrouleau-segmentryanrouleau-segmentfunlufunlutdibaccotdibaccofauzy.yyfauzy.yynlubchenconlubchencoricardo.rossiricardo.rossisahilsharma0709sahilsharma0709arubiochavezarubiochavezphillip.thomasphillip.thomasjkusa_segmentjkusa_segmentrollcoderollcodemeg1000meg1000nainy.agrawalnainy.agrawalseg-rustybaileyseg-rustybaileyjbandi-twiliojbandi-twiliosaisagarkappaganthulasaisagarkappaganthulaforgetfulfellowforgetfulfellowdbaik-twilio-segmentdbaik-twilio-segmentpooja.patilpooja.patiljoe.ayoub.segmentjoe.ayoub.segmenthmohanram_seghmohanram_segbrian.aguirrebrian.aguirreenyi.asonyeenyi.asonyefarhan0581farhan0581tbrennanjtbrennanjparag.pandaparag.pandacherylj-segmentcherylj-segmentharsh.vardhanharsh.vardhansshaikh_segmentsshaikh_segmentxinghao.huangxinghao.huangshupadhyayshupadhyayjohn.lee1100john.lee1100kx-segmentkx-segmentsegment_fansegment_fandazu70dazu70sbhodiwalsbhodiwalsai-patanjalisai-patanjaliemilyjiaemilyjiay.yuy.yuea_segmentea_segmentyli119yli119pooyajpooyajsungju.jinsungju.jinconniechenconniechenbharath.boregowdabharath.boregowdaigracheva-twilioigracheva-twiliobenattwiliobenattwiliomarinheromarinheroankit.gupta.unthinkableankit.gupta.unthinkabledobrin.ganevdobrin.ganevalfrimpongalfrimpongbrandonheyer-segmentbrandonheyer-segmentalecjacobs-segmentalecjacobs-segmentcjo2cjo2yashnit-segmentyashnit-segmentdltnbrks-segmentdltnbrks-segmentachandrashekaranachandrashekaranhimanshuphhimanshuphpraguptapraguptatw-dgarciatw-dgarciaalayvoraalayvoraaparna.singhalaparna.singhalynguyenynguyentimmyzsearcytimmyzsearcylweimersegmentlweimersegmentanton-vylushchakanton-vylushchakazhaotwilioazhaotwiliorokatyalrokatyalkjoerreskjoerresmsarafmsarafvikakumarvikakumaraditi.raveeshaditi.raveeshchenchensegmentcomchenchensegmentcomsanket.mishrasanket.mishraodoren_segmentodoren_segmentjxin_twiliojxin_twiliorcheedhallarcheedhallajbasiglio-segmentjbasiglio-segmentviveksainaneesegmentviveksainaneesegmentpriyanshispriyanshispreetyppreetypakash.gautam07akash.gautam07nanotimmnanotimmyshkpryshkprsrivig21srivig21ssunejassunejabala.singareddybala.singareddymoyara2moyara2arjunbhandagearjunbhandageakodankiryakodankiryrodhilton_twiliorodhilton_twiliocdelaomartinezcdelaomartinezgbatragbatraspencerattickspenceratticksegmentseansegmentseansundareswar.jayakumarsundareswar.jayakumarvaibhavnandavaibhavnandabannapplebannapplesrishti-nemasrishti-nemaar7devar7devgsolis_segmentgsolis_segmentitsarijitrayitsarijitraybhavanki-segmentbhavanki-segmentnitinpm432nitinpm432nikumarsegmentnikumarsegmentnanette.ranesnanette.ranesamigandhiamigandhiguthriesegmentguthriesegmentmiguelpdiaz8miguelpdiaz8mansarimansarisandhya16sandhya16hema-bahirwani-segmenthema-bahirwani-segmentbnakkinabnakkinapraveenugiripraveenugiriighorelaighorelanemery-segmentnemery-segmentwlumsegmentwlumsegmentnat-gridnat-gridneedcaffeineneedcaffeinekbhargavaram-sgkbhargavaram-sgirfan.ali.segmentirfan.ali.segmentharsh-joshi99harsh-joshi99ed-twilion-npmed-twilion-npmaubreysineaubreysinelight-bringer-blrlight-bringer-blrsethgrid_segmentsethgrid_segmentjibrangjibrangseg-leonelsanchesseg-leonelsanchessmccoy-twiliosmccoy-twiliodevthaledevthaleandwivediandwivedipoojapatilsegpoojapatilseggaprabhugaprabhuapackerapackermonusegmentmonusegmentehydesegmentehydesegment

Keywords

Readme

localstorage-retry

Circle CI

Provides durable retries with a queue held in localStorage (with graceful fallbacks to memory when necessary).

How It Works

Each page maintains its own list of queued and in-progress tasks, while constantly refreshing its ack time. If a queue goes more than 10s without updating its ack, another page will remove it, claim all queued tasks, and retry all in-progress tasks.

API

new Queue(name, [opts], processFunc(item, done(err, res)))

You can omit the opts argument to initialize the queue with defaults:

var Queue = require('@segment/localstorage-retry');

var queue = new Queue('my_queue_name', function process(item, done) {
  sendAsync(item, function(err, res) {
    if (err) return done(err);
    done(null, res);
  });
});

queue.on('processed', function(err, res, item) {
  if (err) return console.warn('processing %O failed with error %O', item, err);
  console.log('successfully sent %O with response %O', item, res);
});

queue.start();

Options

The queue can be initialized with the following options (defaults shown):

var options = {
  minRetryDelay: 1000,   // min retry delay in ms (used in exp. backoff calcs)
  maxRetryDelay: 30000,  // max retry delay in ms (used in exp. backoff calcs)
  backoffFactor: 2,      // exponential backoff factor (attempts^n)
  backoffJitter: 0,      // jitter factor for backoff calcs (0 is usually fine)
  maxItems: Infinity     // queue high water mark (we suggest 100 as a max)
  maxAttempts: Infinity  // max retry attempts before discarding
};

var queue = new Queue('my_queue_name', options, (item, done) => {
  sendAsync(item, (err, res) => {
    if (err) return done(err);
    done(null, res);
  });
});

queue.start();

.addItem(item)

Adds an item to the queue

queue.addItem({ a: 'b' });

.getDelay (attemptNumber) -> ms

Can be overridden to provide a custom retry delay in ms. You'll likely want to use the queue instance's backoff constants here.

this.backoff = {
  MIN_RETRY_DELAY: opts.minRetryDelay || 1000,
  MAX_RETRY_DELAY: opts.maxRetryDelay || 30000,
  FACTOR: opts.backoffFactor || 2,
  JITTER: opts.backoffJitter || 0
};

Default implementation:

queue.getDelay = function(attemptNumber) {
  var ms = this.backoff.MIN_RETRY_DELAY * Math.pow(this.backoff.FACTOR, attemptNumber);
  if (this.backoff.JITTER) {
    var rand =  Math.random();
    var deviation = Math.floor(rand * this.backoff.JITTER * ms);
    if (Math.floor(rand * 10) < 5) {
      ms -= deviation;
    } else {
      ms += deviation;
    }
  }
  return Number(Math.min(ms, this.backoff.MAX_RETRY_DELAY).toPrecision(1));
};

.shouldRetry (item, attemptNumber, error) -> boolean

Can be overridden to provide custom logic for whether to requeue the item. You'll likely want to use the queue instance's maxAttempts variable (which is overridable via constructor's opts argument).

Default:

queue.shouldRetry = function(item, attemptNumber, error) {
  if (attemptNumber > this.maxAttempts) return false;
  return true;
};

You may also want to selectively retry based on error returned by your process function or something in the item itself.

Override Example:

queue.shouldRetry = function(item, attemptNumber, error) {
  // max attempts
  if (attemptNumber > this.maxAttempts) return false;

  // based on something in the item itself
  if (new Date(item.timestamp) - new Date() > 86400000) return false;

  // selective error handling
  if (error.code === '429') return false;

  return true;
}

.start

Starts the queue processing items. Anything added before calling .start will be queued until .start is called.

queue.start();

.stop

Stops the queue from processing. Any retries queued may be picked claimed by another queue after a timeout.

queue.stop();

Emitter

You can listen for processed events, which are emitted with each invocation of the processFunc and passed any error or response provided along with the item itself.

If a message is discarded entirely because it does not pass your shouldRetry logic upon attempted re-enqueuing, the queue will emit a discard event.

If the queue is reclaiming events from an abandonded queue, and sees duplicate entries, we will keep the first, and discard the rest, emitting a duplication event for each.

processed

queue.on('processed', function(err, res, item) {
  if (err) return console.warn('processing %O failed with error %O', item, err);
  console.log('successfully sent %O with response %O', item, res);
});

discard

queue.on('discard', function(item, attempts) {
  console.error('discarding message %O after %d attempts', item, attempts);
})

duplication

queue.on('duplication', function(item, attempts) {
  console.error('discarding message %O due to duplicate entries', item, attempts);
})

License

Released under the MIT License