|
| 1 | +/** |
| 2 | + * 테스트용 재시도 유틸리티 |
| 3 | + * API eventual consistency 문제를 해결하기 위한 재시도 로직 제공 |
| 4 | + */ |
| 5 | + |
| 6 | +interface RetryOptions { |
| 7 | + maxRetries?: number; |
| 8 | + initialDelayMs?: number; |
| 9 | + maxDelayMs?: number; |
| 10 | + backoffMultiplier?: number; |
| 11 | +} |
| 12 | + |
| 13 | +const DEFAULT_OPTIONS: Required<RetryOptions> = { |
| 14 | + maxRetries: 5, |
| 15 | + initialDelayMs: 100, |
| 16 | + maxDelayMs: 2000, |
| 17 | + backoffMultiplier: 2, |
| 18 | +}; |
| 19 | + |
| 20 | +const sleep = (ms: number): Promise<void> => |
| 21 | + new Promise(resolve => setTimeout(resolve, ms)); |
| 22 | + |
| 23 | +/** |
| 24 | + * 지수 백오프를 사용한 재시도 함수 |
| 25 | + * @param fn 실행할 비동기 함수 |
| 26 | + * @param options 재시도 옵션 |
| 27 | + * @returns 함수 실행 결과 |
| 28 | + */ |
| 29 | +export async function retryWithBackoff<T>( |
| 30 | + fn: () => Promise<T>, |
| 31 | + options: RetryOptions = {}, |
| 32 | +): Promise<T> { |
| 33 | + const opts = {...DEFAULT_OPTIONS, ...options}; |
| 34 | + let lastError: Error | undefined; |
| 35 | + let delay = opts.initialDelayMs; |
| 36 | + |
| 37 | + for (let attempt = 0; attempt <= opts.maxRetries; attempt++) { |
| 38 | + try { |
| 39 | + return await fn(); |
| 40 | + } catch (error) { |
| 41 | + lastError = error instanceof Error ? error : new Error(String(error)); |
| 42 | + |
| 43 | + if (attempt < opts.maxRetries) { |
| 44 | + await sleep(delay); |
| 45 | + delay = Math.min(delay * opts.backoffMultiplier, opts.maxDelayMs); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + throw lastError; |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * 특정 조건이 충족될 때까지 재시도 |
| 55 | + * @param fn 실행할 비동기 함수 |
| 56 | + * @param predicate 조건 검사 함수 |
| 57 | + * @param options 재시도 옵션 |
| 58 | + * @returns 조건을 충족한 결과 |
| 59 | + */ |
| 60 | +export async function retryUntil<T>( |
| 61 | + fn: () => Promise<T>, |
| 62 | + predicate: (result: T) => boolean, |
| 63 | + options: RetryOptions = {}, |
| 64 | +): Promise<T> { |
| 65 | + const opts = {...DEFAULT_OPTIONS, ...options}; |
| 66 | + let delay = opts.initialDelayMs; |
| 67 | + |
| 68 | + for (let attempt = 0; attempt <= opts.maxRetries; attempt++) { |
| 69 | + const result = await fn(); |
| 70 | + |
| 71 | + if (predicate(result)) { |
| 72 | + return result; |
| 73 | + } |
| 74 | + |
| 75 | + if (attempt < opts.maxRetries) { |
| 76 | + await sleep(delay); |
| 77 | + delay = Math.min(delay * opts.backoffMultiplier, opts.maxDelayMs); |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + throw new Error(`Condition not met after ${opts.maxRetries + 1} attempts`); |
| 82 | +} |
0 commit comments