|
| 1 | +/** |
| 2 | + * Concurrency control utilities for rate limit handling |
| 3 | + * |
| 4 | + * These utilities allow limiting concurrent operations to prevent: |
| 5 | + * - API rate limit errors |
| 6 | + * - Resource exhaustion (too many open connections/files) |
| 7 | + * - Memory pressure from parallel processing |
| 8 | + */ |
| 9 | + |
| 10 | +/** |
| 11 | + * Execute promises in batches with controlled concurrency. |
| 12 | + * |
| 13 | + * Instead of running all promises at once (Promise.all), this executes |
| 14 | + * them in batches of `maxConcurrency` to prevent overwhelming APIs or resources. |
| 15 | + * |
| 16 | + * @param tasks - Array of functions that return promises |
| 17 | + * @param maxConcurrency - Maximum number of concurrent promises (default: Infinity = no limit) |
| 18 | + * @returns Promise that resolves when all tasks complete, with results in original order |
| 19 | + * |
| 20 | + * @example |
| 21 | + * ```typescript |
| 22 | + * // Limit to 3 concurrent API calls |
| 23 | + * const results = await promiseAllBatched( |
| 24 | + * urls.map(url => () => fetch(url)), |
| 25 | + * 3 |
| 26 | + * ); |
| 27 | + * ``` |
| 28 | + */ |
| 29 | +export async function promiseAllBatched<T>( |
| 30 | + tasks: Array<() => Promise<T>>, |
| 31 | + maxConcurrency: number = Infinity |
| 32 | +): Promise<T[]> { |
| 33 | + // Fast path: no concurrency limit |
| 34 | + if (maxConcurrency === Infinity || maxConcurrency >= tasks.length) { |
| 35 | + return Promise.all(tasks.map(task => task())); |
| 36 | + } |
| 37 | + |
| 38 | + const results: T[] = new Array(tasks.length); |
| 39 | + let currentIndex = 0; |
| 40 | + |
| 41 | + // Worker function that processes tasks from the queue |
| 42 | + async function worker(): Promise<void> { |
| 43 | + while (currentIndex < tasks.length) { |
| 44 | + const index = currentIndex++; |
| 45 | + const task = tasks[index]; |
| 46 | + results[index] = await task(); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + // Create pool of concurrent workers |
| 51 | + const workers = Array.from( |
| 52 | + { length: Math.min(maxConcurrency, tasks.length) }, |
| 53 | + () => worker() |
| 54 | + ); |
| 55 | + |
| 56 | + // Wait for all workers to complete |
| 57 | + await Promise.all(workers); |
| 58 | + |
| 59 | + return results; |
| 60 | +} |
| 61 | + |
| 62 | +/** |
| 63 | + * Rate limiter for API calls |
| 64 | + * |
| 65 | + * Ensures minimum delay between successive calls to prevent rate limit errors. |
| 66 | + * Uses token bucket algorithm for burst tolerance. |
| 67 | + * |
| 68 | + * @example |
| 69 | + * ```typescript |
| 70 | + * const limiter = new RateLimiter(10, 1000); // 10 calls per second |
| 71 | + * |
| 72 | + * for (const url of urls) { |
| 73 | + * await limiter.acquire(); |
| 74 | + * await fetch(url); |
| 75 | + * } |
| 76 | + * ``` |
| 77 | + */ |
| 78 | +export class RateLimiter { |
| 79 | + private tokens: number; |
| 80 | + private lastRefill: number; |
| 81 | + |
| 82 | + /** |
| 83 | + * @param maxTokens - Maximum number of tokens (burst capacity) |
| 84 | + * @param refillIntervalMs - Time to refill one token (ms) |
| 85 | + */ |
| 86 | + constructor( |
| 87 | + private readonly maxTokens: number, |
| 88 | + private readonly refillIntervalMs: number |
| 89 | + ) { |
| 90 | + this.tokens = maxTokens; |
| 91 | + this.lastRefill = Date.now(); |
| 92 | + } |
| 93 | + |
| 94 | + /** |
| 95 | + * Acquire a token, waiting if necessary |
| 96 | + */ |
| 97 | + async acquire(): Promise<void> { |
| 98 | + while (true) { |
| 99 | + this.refillTokens(); |
| 100 | + |
| 101 | + if (this.tokens > 0) { |
| 102 | + this.tokens--; |
| 103 | + return; |
| 104 | + } |
| 105 | + |
| 106 | + // Wait for next token refill |
| 107 | + const waitTime = this.refillIntervalMs; |
| 108 | + await new Promise(resolve => setTimeout(resolve, waitTime)); |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + private refillTokens(): void { |
| 113 | + const now = Date.now(); |
| 114 | + const elapsed = now - this.lastRefill; |
| 115 | + const tokensToAdd = Math.floor(elapsed / this.refillIntervalMs); |
| 116 | + |
| 117 | + if (tokensToAdd > 0) { |
| 118 | + this.tokens = Math.min(this.maxTokens, this.tokens + tokensToAdd); |
| 119 | + this.lastRefill = now; |
| 120 | + } |
| 121 | + } |
| 122 | +} |
0 commit comments