mirror of https://github.com/lukechilds/node.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
50 lines
1.1 KiB
50 lines
1.1 KiB
var RetryOperation = require('./retry_operation');
|
|
|
|
exports.operation = function(options) {
|
|
var timeouts = exports.timeouts(options);
|
|
return new RetryOperation(timeouts);
|
|
};
|
|
|
|
exports.timeouts = function(options) {
|
|
if (options instanceof Array) {
|
|
return [].concat(options);
|
|
}
|
|
|
|
var opts = {
|
|
retries: 10,
|
|
factor: 2,
|
|
minTimeout: 1 * 1000,
|
|
maxTimeout: Infinity,
|
|
randomize: false
|
|
};
|
|
for (var key in options) {
|
|
opts[key] = options[key];
|
|
}
|
|
|
|
if (opts.minTimeout > opts.maxTimeout) {
|
|
throw new Error('minTimeout is greater than maxTimeout');
|
|
}
|
|
|
|
var timeouts = [];
|
|
for (var i = 0; i < opts.retries; i++) {
|
|
timeouts.push(this._createTimeout(i, opts));
|
|
}
|
|
|
|
// sort the array numerically ascending
|
|
timeouts.sort(function(a,b) {
|
|
return a - b;
|
|
});
|
|
|
|
return timeouts;
|
|
};
|
|
|
|
exports._createTimeout = function(attempt, opts) {
|
|
var random = (opts.randomize)
|
|
? (Math.random() + 1)
|
|
: 1;
|
|
|
|
var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
|
|
timeout = Math.min(timeout, opts.maxTimeout);
|
|
|
|
return timeout;
|
|
};
|