@flatfile/safe-api
Version:
Flatfile Safe API client with streaming capabilities
55 lines (54 loc) • 2.12 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RateLimitManager = void 0;
const config_1 = require("./config");
class RateLimitManager {
constructor() {
this.config = config_1.config;
}
static getInstance() {
if (!RateLimitManager.instance) {
RateLimitManager.instance = new RateLimitManager();
}
return RateLimitManager.instance;
}
shouldRetry(status) {
const should = status === 429;
if (this.config.debug) {
console.log(`DEBUG: RateLimitManager: Should retry status ${status}? ${should}`);
}
return should;
}
getRetryDelay(headers) {
// Use retry-after header if present
const retryAfter = headers.get('retry-after');
if (retryAfter) {
const seconds = parseInt(retryAfter, 10);
if (!isNaN(seconds)) {
const delay = (seconds * 1000) + (Math.random() * 1000);
if (this.config.debug) {
console.log(`DEBUG: RateLimitManager: Using retry-after header. Delay: ${delay}ms`);
}
return delay;
}
}
// Fallback to x-ratelimit-reset if present
const reset = parseInt(headers.get('x-ratelimit-reset') || '0', 10);
if (reset) {
const now = Date.now() / 1000; // Convert to seconds
const baseDelay = Math.max(1000, (reset - now) * 1000); // Minimum 1 second delay
const delay = baseDelay + (Math.random() * 1000);
if (this.config.debug) {
console.log(`DEBUG: RateLimitManager: Using x-ratelimit-reset header. Delay: ${delay}ms`);
}
return delay;
}
// Default exponential backoff with jitter if no headers present
const delay = 5000 + (Math.random() * 1000);
if (this.config.debug) {
console.log(`DEBUG: RateLimitManager: No rate limit headers found. Using default delay: ${delay}ms`);
}
return delay;
}
}
exports.RateLimitManager = RateLimitManager;