75 lines
1.6 KiB
JavaScript
75 lines
1.6 KiB
JavaScript
// Metro module 584 (f585).
|
|
class Backoff {
|
|
constructor(min = 500, max = null, jitter = true) {
|
|
const prototype = new.target.prototype;
|
|
if (min <= 0) {
|
|
throw Error("Backoff min value must be greater than zero or backoff will never back-off.");
|
|
}
|
|
const r8 = {
|
|
__proto__: prototype,
|
|
_fails: 0
|
|
};
|
|
r8.min = min;
|
|
if (max == null) {
|
|
max = 10 * min;
|
|
}
|
|
r8.max = max;
|
|
r8.jitter = jitter;
|
|
r8._current = min;
|
|
return r8;
|
|
}
|
|
get fails() {
|
|
return this._fails;
|
|
}
|
|
get current() {
|
|
return this._current;
|
|
}
|
|
get pending() {
|
|
return this._timeoutId != null;
|
|
}
|
|
succeed() {
|
|
this.cancel();
|
|
this._fails = 0;
|
|
this._current = this.min;
|
|
}
|
|
fail(a0, a1) {
|
|
this._fails = this._fails + 1;
|
|
const r1 = 2 * this._current;
|
|
const r19 = this.jitter ? r1 * Math.random() : r1;
|
|
let r23 = a1;
|
|
this._current = Math.min(this._current + r19, this.max);
|
|
if (!(a1 != null && a1 > this._current)) {
|
|
r23 = this._current;
|
|
}
|
|
if (a0 != null) {
|
|
if (this._timeoutId != null) {
|
|
if (this._callback !== a0) {
|
|
throw new Error("callback already pending");
|
|
}
|
|
this.cancel();
|
|
}
|
|
this._callback = a0;
|
|
this._timeoutId = setTimeout(() => {
|
|
try {
|
|
if (a0 != null) {
|
|
a0();
|
|
}
|
|
} catch (r9) {
|
|
this.cancel();
|
|
throw r9;
|
|
}
|
|
this.cancel();
|
|
}, r23);
|
|
}
|
|
return r23;
|
|
}
|
|
cancel() {
|
|
this._callback = null;
|
|
if (this._timeoutId != null) {
|
|
clearTimeout(this._timeoutId);
|
|
this._timeoutId = null;
|
|
}
|
|
}
|
|
}
|
|
export default Backoff;
|