asarfuckery/appasar/stable/common/Backoff.js

93 lines
1.8 KiB
JavaScript
Raw Normal View History

2019-01-17 18:22:05 +00:00
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
// copied from discord_app/lib because including from there is broken.
2019-03-12 17:01:00 +00:00
class Backoff {
2019-01-17 18:22:05 +00:00
/**
* Create a backoff instance can automatically backoff retries.
*/
2019-03-12 17:01:00 +00:00
constructor(min = 500, max = null, jitter = true) {
2019-01-17 18:22:05 +00:00
this.min = min;
this.max = max != null ? max : min * 10;
this.jitter = jitter;
this._current = min;
this._timeoutId = null;
this._fails = 0;
}
/**
* Return the number of failures.
*/
2019-03-12 17:01:00 +00:00
get fails() {
return this._fails;
}
2019-01-17 18:22:05 +00:00
2019-03-12 17:01:00 +00:00
/**
* Current backoff value in milliseconds.
*/
get current() {
return this._current;
}
2019-01-17 18:22:05 +00:00
2019-03-12 17:01:00 +00:00
/**
* A callback is going to fire.
*/
get pending() {
return this._timeoutId != null;
}
2019-01-17 18:22:05 +00:00
2019-03-12 17:01:00 +00:00
/**
* Clear any pending callbacks and reset the backoff.
*/
succeed() {
this.cancel();
this._fails = 0;
this._current = this.min;
}
2019-01-17 18:22:05 +00:00
2019-03-12 17:01:00 +00:00
/**
* Increment the backoff and schedule a callback if provided.
*/
fail(callback) {
this._fails += 1;
let delay = this._current * 2;
if (this.jitter) {
delay *= Math.random();
2019-01-17 18:22:05 +00:00
}
2019-03-12 17:01:00 +00:00
this._current = Math.min(this._current + delay, this.max);
if (callback != null) {
2019-01-17 18:22:05 +00:00
if (this._timeoutId != null) {
2019-03-12 17:01:00 +00:00
throw new Error('callback already pending');
2019-01-17 18:22:05 +00:00
}
2019-03-12 17:01:00 +00:00
this._timeoutId = setTimeout(() => {
try {
if (callback != null) {
callback();
}
} finally {
this._timeoutId = null;
}
}, this._current);
2019-01-17 18:22:05 +00:00
}
2019-03-12 17:01:00 +00:00
return this._current;
}
2019-01-17 18:22:05 +00:00
2019-03-12 17:01:00 +00:00
/**
* Clear any pending callbacks.
*/
cancel() {
if (this._timeoutId != null) {
clearTimeout(this._timeoutId);
this._timeoutId = null;
2019-01-17 18:22:05 +00:00
}
2019-03-12 17:01:00 +00:00
}
}
2019-01-17 18:22:05 +00:00
exports.default = Backoff;
module.exports = exports['default'];