| 43 | } |
| 44 | |
| 45 | async function backoffRetryInternal<T>(fn: () => Promise<T>, maxAttempts: number, currentAttempt = 0): Promise<T> { |
| 46 | try { |
| 47 | return await fn(); |
| 48 | } catch (e) { |
| 49 | if (maxAttempts - 1 === currentAttempt) { |
| 50 | throw new BackoffError(e, {cause: e}); |
| 51 | } |
| 52 | await delay(Math.pow(2, currentAttempt)); |
| 53 | return backoffRetryInternal(fn, maxAttempts, currentAttempt + 1); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | export async function backoffRetry<T>(fn: () => Promise<T>, attempts = 5): Promise<T> { |
| 58 | return backoffRetryInternal(fn, attempts); |