UNPKG

@wavequery/conductor

Version:
60 lines 1.86 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RetryHandler = void 0; class RetryHandler { constructor(options) { this.options = { exponential: true, onRetry: () => { }, ...options, }; this.strategy = { shouldRetry: this.defaultShouldRetry.bind(this), getDelay: this.defaultGetDelay.bind(this), }; } async execute(fn) { let attempt = 0; let lastError; while (attempt < this.options.maxRetries) { try { return await fn(); } catch (error) { lastError = error; attempt++; if (!this.strategy.shouldRetry(error, attempt)) { throw error; } const delay = this.strategy.getDelay(attempt); this.options.onRetry(attempt, error); await this.delay(delay); } } throw lastError; } setStrategy(strategy) { this.strategy = { ...this.strategy, ...strategy, }; } defaultShouldRetry(error, attempt) { // Retry on network errors or rate limits return ((error.name === "NetworkError" || error.name === "RateLimitError" || error.message.includes("timeout")) && attempt < this.options.maxRetries); } defaultGetDelay(attempt) { if (this.options.exponential) { return Math.min(this.options.baseDelay * Math.pow(2, attempt - 1), this.options.maxDelay); } return this.options.baseDelay; } delay(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } } exports.RetryHandler = RetryHandler; //# sourceMappingURL=retry-handler.js.map