* Main refill job loop * Runs periodically to proactively refill token buckets
(logger)
| 69 | * Runs periodically to proactively refill token buckets |
| 70 | */ |
| 71 | function startRefillJob(logger) { |
| 72 | logger.info('starting token refill job', { |
| 73 | refillIntervalMs: REFILL_INTERVAL_MS, |
| 74 | cleanupIntervalMs: CLEANUP_INTERVAL_MS, |
| 75 | }); |
| 76 | |
| 77 | const tick = async () => { |
| 78 | try { |
| 79 | const stats = await refillTokenBuckets(logger); |
| 80 | |
| 81 | if (stats.refilled > 0) { |
| 82 | logger.trace('refill tick completed', stats); |
| 83 | } |
| 84 | |
| 85 | // Periodic cleanup (every CLEANUP_INTERVAL_MS) |
| 86 | cleanupCounter++; |
| 87 | if (cleanupCounter * REFILL_INTERVAL_MS >= CLEANUP_INTERVAL_MS) { |
| 88 | const removed = cleanupTokenBuckets(); |
| 89 | if (removed > 0) { |
| 90 | logger.debug('cleaned up expired token buckets', { |
| 91 | removed, |
| 92 | }); |
| 93 | } |
| 94 | cleanupCounter = 0; |
| 95 | } |
| 96 | } catch (err) { |
| 97 | logger.error('refill job error', { |
| 98 | method: 'rateLimit.refillJob', |
| 99 | error: err.message, |
| 100 | stack: err.stack, |
| 101 | }); |
| 102 | } |
| 103 | |
| 104 | refillTimer = setTimeout(tick, REFILL_INTERVAL_MS); |
| 105 | }; |
| 106 | |
| 107 | // Start timer |
| 108 | refillTimer = setTimeout(tick, REFILL_INTERVAL_MS); |
| 109 | } |
| 110 | |
| 111 | /** |
| 112 | * Stop the refill job |