|
| 1 | +/** |
| 2 | + * HTTP utilities with retry mechanism |
| 3 | + */ |
| 4 | +import type { AMCConfig } from '../connector/amc-config'; |
| 5 | +import { DEFAULT_AMC_CONFIG } from '../connector/amc-config'; |
| 6 | + |
| 7 | +/** |
| 8 | + * Calculate backoff time with exponential backoff and jitter |
| 9 | + * @param retryCount - Current retry count (1-based) |
| 10 | + * @param baseInterval - Base interval in milliseconds |
| 11 | + * @param backoffFactor - Exponential backoff factor |
| 12 | + * @param maxBackoff - Maximum backoff time in milliseconds |
| 13 | + * @returns Backoff time in milliseconds |
| 14 | + */ |
| 15 | +export function calculateBackoff( |
| 16 | + retryCount: number, |
| 17 | + baseInterval: number, |
| 18 | + backoffFactor: number, |
| 19 | + maxBackoff: number |
| 20 | +): number { |
| 21 | + const backoff = baseInterval * backoffFactor ** (retryCount - 1); |
| 22 | + const jitter = Math.random() * backoff * 0.1; |
| 23 | + return Math.min(backoff + jitter, maxBackoff); |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * Sleep for specified milliseconds |
| 28 | + */ |
| 29 | +function sleep(ms: number): Promise<void> { |
| 30 | + return new Promise((resolve) => setTimeout(resolve, ms)); |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * Options for fetchWithRetry |
| 35 | + */ |
| 36 | +export interface FetchWithRetryOptions extends Omit<RequestInit, 'signal'> { |
| 37 | + /** Whether to check response.ok (default: true) */ |
| 38 | + checkOk?: boolean; |
| 39 | +} |
| 40 | + |
| 41 | +/** |
| 42 | + * Check if HTTP status code is retryable (5xx server errors) |
| 43 | + */ |
| 44 | +function isRetryableStatus(status: number): boolean { |
| 45 | + return status >= 500 && status < 600; |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * Fetch with automatic retry on timeout/network errors and 5xx errors |
| 50 | + * @param url - URL to fetch |
| 51 | + * @param config - AMC configuration (uses timeout, retryLimit, retryInterval, maxBackoff, backoffFactor) |
| 52 | + * @param options - Fetch options (RequestInit without signal) |
| 53 | + * @returns Response |
| 54 | + * @throws Error on all retries exhausted or non-retryable errors (4xx) |
| 55 | + */ |
| 56 | +export async function fetchWithRetry( |
| 57 | + url: string, |
| 58 | + config: AMCConfig = DEFAULT_AMC_CONFIG, |
| 59 | + options: FetchWithRetryOptions = {} |
| 60 | +): Promise<Response> { |
| 61 | + const { checkOk = true, ...fetchOptions } = options; |
| 62 | + |
| 63 | + for (let attempt = 0; attempt < config.retryLimit; attempt++) { |
| 64 | + try { |
| 65 | + const response = await fetch(url, { |
| 66 | + ...fetchOptions, |
| 67 | + signal: AbortSignal.timeout(config.timeout), |
| 68 | + }); |
| 69 | + |
| 70 | + // Don't retry 4xx errors - they are client errors that won't change on retry |
| 71 | + if (checkOk && !response.ok) { |
| 72 | + if (!isRetryableStatus(response.status)) { |
| 73 | + throw new Error(`HTTP ${response.status}: ${response.statusText}`); |
| 74 | + } |
| 75 | + // 5xx errors are retryable, continue to retry logic below |
| 76 | + throw new Error(`HTTP ${response.status}: ${response.statusText}`); |
| 77 | + } |
| 78 | + return response; |
| 79 | + } catch (error) { |
| 80 | + // Don't retry if it's a non-retryable HTTP error (4xx) |
| 81 | + if (error instanceof Error && error.message.startsWith('HTTP 4')) { |
| 82 | + throw error; |
| 83 | + } |
| 84 | + if (attempt >= config.retryLimit - 1) { |
| 85 | + throw error; |
| 86 | + } |
| 87 | + const backoff = calculateBackoff( |
| 88 | + attempt + 1, |
| 89 | + config.retryInterval, |
| 90 | + config.backoffFactor, |
| 91 | + config.maxBackoff |
| 92 | + ); |
| 93 | + await sleep(backoff); |
| 94 | + } |
| 95 | + } |
| 96 | + throw new Error('Unreachable'); |
| 97 | +} |
0 commit comments