connor4312 / cockatiel

🐦 A resilience and fault-handling library. Supports Backoffs, Retries, Circuit Breakers, Timeouts, Bulkhead Isolation, and Fallbacks.
MIT License
1.57k stars 48 forks source link

feature: retry delayBeforeStart #33

Closed xenoterracide closed 4 years ago

xenoterracide commented 4 years ago

So, I'm using retry to try to connect to rabbitmq, but when starting together it takes a long time for rabbit mq to come up. I'd like some way to say, don't even start retrying the exponential retry until 20 seconds, at that point it can start at the 128ms and go up. Maybe this should be an additional policy InitialDelay, i'm not sure on the right design.

connor4312 commented 4 years ago

You could use the delegate to supply your own backoff-generating function, that creates and call an exponential policy directly after a period of time. Would that work for you?

const { Policy, ExponentialBackoff } = require('./');

const startBackingOffAt = Date.now() + 5000;

const retry = Policy.handleAll()
  .retry()
  .delegate((_context, policy) => {
    if (Date.now() < startBackingOffAt) {
      return 200;
    } else if (policy) {
      return { delay: policy.duration(), state: policy.next() };
    } else {
      return { delay: 200, state: new ExponentialBackoff() };
    }
  });

retry.execute(() => {
  console.log(`Failing at ${new Date().toISOString()}`);
  throw new Error('oh no!');
});
xenoterracide commented 4 years ago

not as nice as having it in the library, but it'll do