| 1 | export interface APIError extends Error { |
| 2 | response?: Response; |
| 3 | } |
| 4 | |
| 5 | export const RETRY_AFTER_HEADER = "Retry-After"; |
| 6 | |
| 7 | const withExponentialBackoff = async <T>( |
| 8 | apiCall: () => Promise<T>, |
| 9 | maxTries = 5, |
| 10 | initialDelaySeconds = 1, |
| 11 | ) => { |
| 12 | for (let attempt = 0; attempt < maxTries; attempt++) { |
| 13 | try { |
| 14 | const result = await apiCall(); |
| 15 | return result; |
| 16 | } catch (error: any) { |
| 17 | if ((error as APIError).response?.status === 429) { |
| 18 | const retryAfter = (error as APIError).response?.headers.get( |
| 19 | RETRY_AFTER_HEADER, |
| 20 | ); |
| 21 | const delay = retryAfter |
| 22 | ? parseInt(retryAfter, 10) |
| 23 | : initialDelaySeconds * 2 ** attempt; |
| 24 | console.log( |
| 25 | `Hit rate limit. Retrying in ${delay} seconds (attempt ${ |
| 26 | attempt + 1 |
| 27 | })`, |
| 28 | ); |
| 29 | await new Promise((resolve) => setTimeout(resolve, delay * 1000)); |
| 30 | } else { |
| 31 | throw error; // Re-throw other errors |
| 32 | } |
| 33 | } |
| 34 | } |
| 35 | throw new Error(`Failed to make API call after ${maxTries} retries`); |
| 36 | }; |
| 37 | |
| 38 | export { withExponentialBackoff }; |