all files / lib/replicate/ backoff.js

100% Statements 34/34
95% Branches 19/20
100% Functions 4/4
100% Lines 34/34
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                          163× 55× 55× 55×   108×   108× 108× 105× 105× 105× 105×       108× 108× 108×    
'use strict';
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
var STARTING_BACK_OFF = 0;
 
function randomNumber(min, max) {
  min = parseInt(min, 10) || 0;
  max = parseInt(max, 10);
  if (max !== max || max <= min) {
    max = (min || 1) << 1; //doubling
  } else {
      max = max + 1;
    }
  var ratio = Math.random();
  var range = max - min;
 
  return ~ ~(range * ratio + min); // ~~ coerces to an int, but fast.
}
 
function defaultBackOff(min) {
  var max = 0;
  if (!min) {
    max = 2000;
  }
  return randomNumber(min, max);
}
 
function backOff(opts, returnValue, error, callback) {
  if (opts.retry === false) {
    returnValue.emit('error', error);
    returnValue.removeAllListeners();
    return;
  }
  if (typeof opts.back_off_function !== 'function') {
    opts.back_off_function = defaultBackOff;
  }
  returnValue.emit('requestError', error);
  if (returnValue.state === 'active' || returnValue.state === 'pending') {
    returnValue.emit('paused', error);
    returnValue.state = 'stopped';
    returnValue.once('active', function () {
      opts.current_back_off = STARTING_BACK_OFF;
    });
  }
 
  opts.current_back_off = opts.current_back_off || STARTING_BACK_OFF;
  opts.current_back_off = opts.back_off_function(opts.current_back_off);
  setTimeout(callback, opts.current_back_off);
}
 
exports.default = backOff;
module.exports = exports['default'];