masto
Version:
Mastodon API client for JavaScript, TypeScript, Node.js, browsers
43 lines (42 loc) • 1.29 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExponentialBackoff = exports.ExponentialBackoffError = void 0;
const ts_custom_error_1 = require("ts-custom-error");
const sleep_js_1 = require("./sleep.js");
class ExponentialBackoffError extends ts_custom_error_1.CustomError {
constructor(attempts, options) {
super(`Maximum number of attempts reached: ${attempts}`, options);
}
}
exports.ExponentialBackoffError = ExponentialBackoffError;
// https://en.wikipedia.org/wiki/Exponential_backoff
class ExponentialBackoff {
props;
attempts = 0;
constructor(props = {}) {
this.props = props;
}
async sleep() {
if (this.attempts >= this.maxAttempts) {
throw new ExponentialBackoffError(this.attempts);
}
await (0, sleep_js_1.sleep)(this.timeout);
this.attempts++;
}
clear() {
this.attempts = 0;
}
get factor() {
return this.props.factor ?? 1000;
}
get base() {
return this.props.base ?? 2;
}
get maxAttempts() {
return this.props.maxAttempts ?? Number.POSITIVE_INFINITY;
}
get timeout() {
return this.factor * this.base ** this.attempts;
}
}
exports.ExponentialBackoff = ExponentialBackoff;