|
| 1 | +import { appInsightsService } from '@/services/appInsightsService'; |
| 2 | + |
| 3 | +const DEFAULT_MAX_RETRIES = 3; |
| 4 | +const DEFAULT_INITIAL_DELAY_MS = 1000; |
| 5 | +const DEFAULT_MAX_DELAY_MS = 10000; |
| 6 | +const DEFAULT_BACKOFF_MULTIPLIER = 2; |
| 7 | +const DEFAULT_RETRYABLE_STATUS_CODES = [408, 429, 500, 502, 503, 504]; |
| 8 | + |
| 9 | +const FIRST_ATTEMPT = 1; |
| 10 | + |
| 11 | +export interface RetryConfig { |
| 12 | + maxRetries?: number; |
| 13 | + initialDelayMs?: number; |
| 14 | + maxDelayMs?: number; |
| 15 | + backoffMultiplier?: number; |
| 16 | + retryableStatusCodes?: number[]; |
| 17 | +} |
| 18 | + |
| 19 | +export interface ErrorWithStatus extends Error { |
| 20 | + status?: number; |
| 21 | + statusCode?: number; |
| 22 | + code?: string; |
| 23 | +} |
| 24 | + |
| 25 | +const DEFAULT_RETRY_CONFIG: Required<RetryConfig> = { |
| 26 | + maxRetries: DEFAULT_MAX_RETRIES, |
| 27 | + initialDelayMs: DEFAULT_INITIAL_DELAY_MS, |
| 28 | + maxDelayMs: DEFAULT_MAX_DELAY_MS, |
| 29 | + backoffMultiplier: DEFAULT_BACKOFF_MULTIPLIER, |
| 30 | + retryableStatusCodes: DEFAULT_RETRYABLE_STATUS_CODES, |
| 31 | +}; |
| 32 | + |
| 33 | +function isRetryableError(error: unknown, retryableStatusCodes: number[]): boolean { |
| 34 | + if (!error) return false; |
| 35 | + |
| 36 | + const err = error as ErrorWithStatus; |
| 37 | + |
| 38 | + const statusCode = err.status || err.statusCode; |
| 39 | + if (statusCode && retryableStatusCodes.includes(statusCode)) { |
| 40 | + return true; |
| 41 | + } |
| 42 | + |
| 43 | + const errorText = [err.message, err.name, err.code].join(' ').toLowerCase(); |
| 44 | + const patterns = ['network', 'timeout', 'connection', 'service', 'not found']; |
| 45 | + |
| 46 | + return patterns.some((pattern) => errorText.includes(pattern)); |
| 47 | +} |
| 48 | + |
| 49 | +function calculateDelay( |
| 50 | + attemptNumber: number, |
| 51 | + initialDelayMs: number, |
| 52 | + maxDelayMs: number, |
| 53 | + backoffMultiplier: number, |
| 54 | +): number { |
| 55 | + const exponentialDelay = |
| 56 | + initialDelayMs * Math.pow(backoffMultiplier, attemptNumber - FIRST_ATTEMPT); |
| 57 | + return Math.min(exponentialDelay, maxDelayMs); |
| 58 | +} |
| 59 | + |
| 60 | +function delay(ms: number): Promise<void> { |
| 61 | + return new Promise((resolve) => setTimeout(resolve, ms)); |
| 62 | +} |
| 63 | + |
| 64 | +function shouldRetry( |
| 65 | + attempt: number, |
| 66 | + maxAttempts: number, |
| 67 | + error: unknown, |
| 68 | + retryableStatusCodes: number[], |
| 69 | +): boolean { |
| 70 | + const hasRetriesLeft = attempt < maxAttempts; |
| 71 | + const isRetryable = isRetryableError(error, retryableStatusCodes); |
| 72 | + return hasRetriesLeft && isRetryable; |
| 73 | +} |
| 74 | + |
| 75 | +function logRetryAttempt(operationName: string, attempt: number, maxAttempts: number): void { |
| 76 | + if (attempt > FIRST_ATTEMPT) { |
| 77 | + console.info(`[Retry] Attempting ${operationName} (attempt ${attempt}/${maxAttempts})`); |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +function logRetrySuccess(operationName: string, attempt: number): void { |
| 82 | + if (attempt > FIRST_ATTEMPT) { |
| 83 | + console.info(`[Retry] ${operationName} succeeded on attempt ${attempt}`); |
| 84 | + appInsightsService.trackEvent({ |
| 85 | + name: 'Auth0RetrySuccess', |
| 86 | + properties: { |
| 87 | + operation: operationName, |
| 88 | + attempt: attempt.toString(), |
| 89 | + totalRetries: (attempt - FIRST_ATTEMPT).toString(), |
| 90 | + }, |
| 91 | + }); |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +function logAndTrackFailure( |
| 96 | + operationName: string, |
| 97 | + attempt: number, |
| 98 | + error: unknown, |
| 99 | + isRetryable: boolean, |
| 100 | +): void { |
| 101 | + if (!isRetryable) { |
| 102 | + console.error(`[Retry] ${operationName} failed with non-retryable error`, error); |
| 103 | + } else { |
| 104 | + console.error(`[Retry] ${operationName} failed after ${attempt} attempts`, error); |
| 105 | + appInsightsService.trackEvent({ |
| 106 | + name: 'Auth0RetryFailure', |
| 107 | + properties: { |
| 108 | + operation: operationName, |
| 109 | + totalAttempts: attempt.toString(), |
| 110 | + errorMessage: error instanceof Error ? error.message : 'Unknown error', |
| 111 | + }, |
| 112 | + }); |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +async function executeRetryDelay( |
| 117 | + operationName: string, |
| 118 | + attempt: number, |
| 119 | + initialDelayMs: number, |
| 120 | + maxDelayMs: number, |
| 121 | + backoffMultiplier: number, |
| 122 | + error: unknown, |
| 123 | +): Promise<void> { |
| 124 | + const delayMs = calculateDelay(attempt, initialDelayMs, maxDelayMs, backoffMultiplier); |
| 125 | + console.info( |
| 126 | + `[Retry] ${operationName} failed on attempt ${attempt}, retrying in ${delayMs}ms...`, |
| 127 | + ); |
| 128 | + |
| 129 | + appInsightsService.trackEvent({ |
| 130 | + name: 'Auth0RetryAttempt', |
| 131 | + properties: { |
| 132 | + operation: operationName, |
| 133 | + attempt: attempt.toString(), |
| 134 | + delayMs: delayMs.toString(), |
| 135 | + errorMessage: error instanceof Error ? error.message : 'Unknown error', |
| 136 | + }, |
| 137 | + }); |
| 138 | + |
| 139 | + await delay(delayMs); |
| 140 | +} |
| 141 | + |
| 142 | +export async function retryAuth0Operation<T>( |
| 143 | + fn: () => Promise<T>, |
| 144 | + operationName: string, |
| 145 | + config?: RetryConfig, |
| 146 | +): Promise<T> { |
| 147 | + const { maxRetries, initialDelayMs, maxDelayMs, backoffMultiplier, retryableStatusCodes } = { |
| 148 | + ...DEFAULT_RETRY_CONFIG, |
| 149 | + ...config, |
| 150 | + }; |
| 151 | + |
| 152 | + let attempt = FIRST_ATTEMPT; |
| 153 | + const maxAttempts = maxRetries + FIRST_ATTEMPT; |
| 154 | + |
| 155 | + while (attempt <= maxAttempts) { |
| 156 | + try { |
| 157 | + logRetryAttempt(operationName, attempt, maxAttempts); |
| 158 | + |
| 159 | + const result = await fn(); |
| 160 | + |
| 161 | + logRetrySuccess(operationName, attempt); |
| 162 | + |
| 163 | + return result; |
| 164 | + } catch (error) { |
| 165 | + const canRetry = shouldRetry(attempt, maxAttempts, error, retryableStatusCodes); |
| 166 | + |
| 167 | + if (!canRetry) { |
| 168 | + const isRetryable = isRetryableError(error, retryableStatusCodes); |
| 169 | + logAndTrackFailure(operationName, attempt, error, isRetryable); |
| 170 | + throw error; |
| 171 | + } |
| 172 | + |
| 173 | + await executeRetryDelay( |
| 174 | + operationName, |
| 175 | + attempt, |
| 176 | + initialDelayMs, |
| 177 | + maxDelayMs, |
| 178 | + backoffMultiplier, |
| 179 | + error, |
| 180 | + ); |
| 181 | + |
| 182 | + attempt++; |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + // This should never be reached due to the logic above, but TypeScript needs it |
| 187 | + throw new Error(`[Retry] ${operationName} exhausted all attempts without throwing`); |
| 188 | +} |
0 commit comments