| 1 | import { retryAsync, withLLMRetry, withRetry } from "./retry"; |
| 2 | |
| 3 | // Mock console.warn to avoid noise in tests |
| 4 | const consoleSpy = jest.spyOn(console, "warn").mockImplementation(() => {}); |
| 5 | |
| 6 | describe("Retry Functionality", () => { |
| 7 | beforeEach(() => { |
| 8 | jest.clearAllMocks(); |
| 9 | }); |
| 10 | |
| 11 | describe("retryAsync", () => { |
| 12 | it("should succeed on first attempt", async () => { |
| 13 | const mockFn = jest.fn().mockResolvedValue("success"); |
| 14 | |
| 15 | const result = await retryAsync(mockFn); |
| 16 | |
| 17 | expect(result).toBe("success"); |
| 18 | expect(mockFn).toHaveBeenCalledTimes(1); |
| 19 | }); |
| 20 | |
| 21 | it("should retry on retryable errors", async () => { |
| 22 | const error = new Error("ECONNRESET"); |
| 23 | (error as any).code = "ECONNRESET"; |
| 24 | const mockFn = jest |
| 25 | .fn() |
| 26 | .mockRejectedValueOnce(error) |
| 27 | .mockResolvedValue("success"); |
| 28 | |
| 29 | const result = await retryAsync(mockFn, { |
| 30 | maxAttempts: 2, |
| 31 | baseDelay: 10, // Very short delay for testing |
| 32 | }); |
| 33 | |
| 34 | expect(result).toBe("success"); |
| 35 | expect(mockFn).toHaveBeenCalledTimes(2); |
| 36 | }); |
| 37 | |
| 38 | it("should not retry on non-retryable errors", async () => { |
| 39 | const error = new Error("Bad Request"); |
| 40 | (error as any).status = 400; |
| 41 | const mockFn = jest.fn().mockRejectedValue(error); |
| 42 | |
| 43 | await expect(retryAsync(mockFn)).rejects.toThrow("Bad Request"); |
| 44 | expect(mockFn).toHaveBeenCalledTimes(1); |
| 45 | }); |
| 46 | |
| 47 | it("should respect max attempts", async () => { |
| 48 | const error = new Error("ECONNRESET"); |
| 49 | (error as any).code = "ECONNRESET"; |
| 50 | const mockFn = jest.fn().mockRejectedValue(error); |
| 51 | |
| 52 | await expect( |
| 53 | retryAsync(mockFn, { |
| 54 | maxAttempts: 3, |
| 55 | baseDelay: 10, |
| 56 | }), |
| 57 | ).rejects.toThrow("ECONNRESET"); |
| 58 | expect(mockFn).toHaveBeenCalledTimes(3); |
| 59 | }); |
| 60 | |
| 61 | it("should throw the last error when all retries are exhausted", async () => { |
| 62 | const firstError = new Error("First error"); |
| 63 | (firstError as any).code = "ECONNRESET"; |
| 64 | const secondError = new Error("Second error"); |
| 65 | (secondError as any).code = "ECONNRESET"; |
| 66 | const lastError = new Error("Last error"); |
| 67 | (lastError as any).code = "ECONNRESET"; |
| 68 | |
| 69 | const mockFn = jest |
| 70 | .fn() |
| 71 | .mockRejectedValueOnce(firstError) |
| 72 | .mockRejectedValueOnce(secondError) |
| 73 | .mockRejectedValueOnce(lastError); |
| 74 | |
| 75 | await expect( |
| 76 | retryAsync(mockFn, { |
| 77 | maxAttempts: 3, |
| 78 | baseDelay: 10, |
| 79 | }), |
| 80 | ).rejects.toThrow("Last error"); |
| 81 | expect(mockFn).toHaveBeenCalledTimes(3); |
| 82 | }); |
| 83 | |
| 84 | it("should handle HTTP 429 errors", async () => { |
| 85 | const error = new Error("Too Many Requests"); |
| 86 | (error as any).status = 429; |
| 87 | const mockFn = jest |
| 88 | .fn() |
| 89 | .mockRejectedValueOnce(error) |
| 90 | .mockResolvedValue("success"); |
| 91 | |
| 92 | const result = await retryAsync(mockFn, { |
| 93 | maxAttempts: 2, |
| 94 | baseDelay: 10, |
| 95 | }); |
| 96 | |
| 97 | expect(result).toBe("success"); |
| 98 | expect(mockFn).toHaveBeenCalledTimes(2); |
| 99 | }); |
| 100 | |
| 101 | it("should handle HTTP 5xx errors", async () => { |
| 102 | const error = new Error("Internal Server Error"); |
| 103 | (error as any).status = 500; |
| 104 | const mockFn = jest |
| 105 | .fn() |
| 106 | .mockRejectedValueOnce(error) |
| 107 | .mockResolvedValue("success"); |
| 108 | |
| 109 | const result = await retryAsync(mockFn, { |
| 110 | maxAttempts: 2, |
| 111 | baseDelay: 10, |
| 112 | }); |
| 113 | |
| 114 | expect(result).toBe("success"); |
| 115 | expect(mockFn).toHaveBeenCalledTimes(2); |
| 116 | }); |
| 117 | |
| 118 | it("should handle AWS SDK errors", async () => { |
| 119 | const error = new Error("Throttling"); |
| 120 | error.name = "ThrottlingException"; |
| 121 | (error as any).$fault = "client"; |
| 122 | (error as any).$metadata = { |
| 123 | httpStatusCode: 429, |
| 124 | requestId: "test-request-id", |
| 125 | }; |
| 126 | const mockFn = jest |
| 127 | .fn() |
| 128 | .mockRejectedValueOnce(error) |
| 129 | .mockResolvedValue("success"); |
| 130 | |
| 131 | const result = await retryAsync(mockFn, { |
| 132 | maxAttempts: 2, |
| 133 | baseDelay: 10, |
| 134 | }); |
| 135 | |
| 136 | expect(result).toBe("success"); |
| 137 | expect(mockFn).toHaveBeenCalledTimes(2); |
| 138 | }); |
| 139 | |
| 140 | it("should not retry AbortError", async () => { |
| 141 | const error = new Error("Aborted"); |
| 142 | error.name = "AbortError"; |
| 143 | const mockFn = jest.fn().mockRejectedValue(error); |
| 144 | |
| 145 | await expect(retryAsync(mockFn)).rejects.toThrow("Aborted"); |
| 146 | expect(mockFn).toHaveBeenCalledTimes(1); |
| 147 | }); |
| 148 | |
| 149 | it("should use custom shouldRetry function", async () => { |
| 150 | const mockFn = jest.fn().mockRejectedValue(new Error("Custom Error")); |
| 151 | const customShouldRetry = jest.fn().mockReturnValue(true); |
| 152 | |
| 153 | await expect( |
| 154 | retryAsync(mockFn, { |
| 155 | maxAttempts: 2, |
| 156 | shouldRetry: customShouldRetry, |
| 157 | baseDelay: 10, |
| 158 | }), |
| 159 | ).rejects.toThrow("Custom Error"); |
| 160 | |
| 161 | expect(customShouldRetry).toHaveBeenCalledWith(expect.any(Error), 1); |
| 162 | expect(mockFn).toHaveBeenCalledTimes(2); |
| 163 | }); |
| 164 | }); |
| 165 | |
| 166 | describe("withRetry decorator functional usage", () => { |
| 167 | it("should work when applied manually to methods", async () => { |
| 168 | const testClass = { |
| 169 | attempts: 0, |
| 170 | |
| 171 | async testMethod(): Promise<string> { |
| 172 | this.attempts++; |
| 173 | if (this.attempts < 3) { |
| 174 | const error = new Error("ECONNRESET"); |
| 175 | (error as any).code = "ECONNRESET"; |
| 176 | throw error; |
| 177 | } |
| 178 | return "success"; |
| 179 | }, |
| 180 | }; |
| 181 | |
| 182 | // Apply decorator manually |
| 183 | const decorator = withRetry({ |
| 184 | maxAttempts: 3, |
| 185 | baseDelay: 10, |
| 186 | }); |
| 187 | const descriptor = decorator(testClass, "testMethod", { |
| 188 | value: testClass.testMethod, |
| 189 | writable: true, |
| 190 | enumerable: false, |
| 191 | configurable: true, |
| 192 | }); |
| 193 | |
| 194 | if (descriptor?.value) { |
| 195 | testClass.testMethod = descriptor.value; |
| 196 | } |
| 197 | |
| 198 | const result = await testClass.testMethod(); |
| 199 | |
| 200 | expect(result).toBe("success"); |
| 201 | expect(testClass.attempts).toBe(3); |
| 202 | }); |
| 203 | |
| 204 | it("should throw the last error when all retries are exhausted", async () => { |
| 205 | const testClass = { |
| 206 | attempts: 0, |
| 207 | |
| 208 | async testMethod(): Promise<string> { |
| 209 | this.attempts++; |
| 210 | if (this.attempts === 1) { |
| 211 | const error = new Error("First decorator error"); |
| 212 | (error as any).code = "ECONNRESET"; |
| 213 | throw error; |
| 214 | } else if (this.attempts === 2) { |
| 215 | const error = new Error("Second decorator error"); |
| 216 | (error as any).code = "ECONNRESET"; |
| 217 | throw error; |
| 218 | } else { |
| 219 | const error = new Error("Last decorator error"); |
| 220 | (error as any).code = "ECONNRESET"; |
| 221 | throw error; |
| 222 | } |
| 223 | }, |
| 224 | }; |
| 225 | |
| 226 | // Apply decorator manually |
| 227 | const decorator = withRetry({ |
| 228 | maxAttempts: 3, |
| 229 | baseDelay: 10, |
| 230 | }); |
| 231 | const descriptor = decorator(testClass, "testMethod", { |
| 232 | value: testClass.testMethod, |
| 233 | writable: true, |
| 234 | enumerable: false, |
| 235 | configurable: true, |
| 236 | }); |
| 237 | |
| 238 | if (descriptor?.value) { |
| 239 | testClass.testMethod = descriptor.value; |
| 240 | } |
| 241 | |
| 242 | await expect(testClass.testMethod()).rejects.toThrow( |
| 243 | "Last decorator error", |
| 244 | ); |
| 245 | expect(testClass.attempts).toBe(3); |
| 246 | }); |
| 247 | }); |
| 248 | |
| 249 | describe("withLLMRetry decorator functional usage", () => { |
| 250 | it("should use LLM-specific defaults", async () => { |
| 251 | const testLLM = { |
| 252 | attempts: 0, |
| 253 | |
| 254 | async streamChat(): Promise<string> { |
| 255 | this.attempts++; |
| 256 | if (this.attempts < 2) { |
| 257 | const error = new Error("Too Many Requests"); |
| 258 | (error as any).status = 429; |
| 259 | throw error; |
| 260 | } |
| 261 | return "success"; |
| 262 | }, |
| 263 | }; |
| 264 | |
| 265 | // Apply decorator manually |
| 266 | const decorator = withLLMRetry({ baseDelay: 10 }); |
| 267 | const descriptor = decorator(testLLM, "streamChat", { |
| 268 | value: testLLM.streamChat, |
| 269 | writable: true, |
| 270 | enumerable: false, |
| 271 | configurable: true, |
| 272 | }); |
| 273 | |
| 274 | if (descriptor?.value) { |
| 275 | testLLM.streamChat = descriptor.value; |
| 276 | } |
| 277 | |
| 278 | const result = await testLLM.streamChat(); |
| 279 | |
| 280 | expect(result).toBe("success"); |
| 281 | expect(testLLM.attempts).toBe(2); |
| 282 | }); |
| 283 | }); |
| 284 | |
| 285 | describe("exponential backoff with jitter", () => { |
| 286 | it("should increase delay exponentially", async () => { |
| 287 | const delays: number[] = []; |
| 288 | const error = new Error("ECONNRESET"); |
| 289 | (error as any).code = "ECONNRESET"; |
| 290 | const mockFn = jest.fn().mockRejectedValue(error); |
| 291 | |
| 292 | await expect( |
| 293 | retryAsync(mockFn, { |
| 294 | maxAttempts: 3, |
| 295 | baseDelay: 1000, |
| 296 | jitterFactor: 0, // No jitter for predictable testing |
| 297 | onRetry: (error, attempt, delay) => { |
| 298 | delays.push(delay); |
| 299 | }, |
| 300 | }), |
| 301 | ).rejects.toThrow(); |
| 302 | |
| 303 | // First retry should be ~1000ms, second should be ~2000ms |
| 304 | expect(delays).toHaveLength(2); |
| 305 | expect(delays[0]).toBe(1000); |
| 306 | expect(delays[1]).toBe(2000); |
| 307 | }); |
| 308 | |
| 309 | it("should respect maxDelay", async () => { |
| 310 | const delays: number[] = []; |
| 311 | const error = new Error("ECONNRESET"); |
| 312 | (error as any).code = "ECONNRESET"; |
| 313 | const mockFn = jest.fn().mockRejectedValue(error); |
| 314 | |
| 315 | await expect( |
| 316 | retryAsync(mockFn, { |
| 317 | maxAttempts: 4, |
| 318 | baseDelay: 1000, |
| 319 | maxDelay: 2500, |
| 320 | jitterFactor: 0, |
| 321 | onRetry: (error, attempt, delay) => { |
| 322 | delays.push(delay); |
| 323 | }, |
| 324 | }), |
| 325 | ).rejects.toThrow(); |
| 326 | |
| 327 | // Delays should be: 1000, 2000, 2500 (capped) |
| 328 | expect(delays).toEqual([1000, 2000, 2500]); |
| 329 | }); |
| 330 | }); |
| 331 | |
| 332 | describe("rate limiting headers", () => { |
| 333 | it("should respect retry-after header in seconds", async () => { |
| 334 | const delays: number[] = []; |
| 335 | const error = new Error("Too Many Requests"); |
| 336 | (error as any).status = 429; |
| 337 | (error as any).headers = { "retry-after": "1" }; // 1 second for fast testing |
| 338 | const mockFn = jest |
| 339 | .fn() |
| 340 | .mockRejectedValueOnce(error) |
| 341 | .mockResolvedValue("success"); |
| 342 | |
| 343 | const result = await retryAsync(mockFn, { |
| 344 | maxAttempts: 2, |
| 345 | baseDelay: 100, // 100ms fallback |
| 346 | onRetry: (error, attempt, delay) => { |
| 347 | delays.push(delay); |
| 348 | }, |
| 349 | }); |
| 350 | |
| 351 | expect(result).toBe("success"); |
| 352 | expect(mockFn).toHaveBeenCalledTimes(2); |
| 353 | // Should use header value (1000ms) not exponential backoff (100ms) |
| 354 | expect(delays[0]).toBeGreaterThan(940); // 1000ms with wider tolerance for jitter and system performance |
| 355 | expect(delays[0]).toBeLessThan(1080); |
| 356 | }); |
| 357 | |
| 358 | it("should respect x-ratelimit-reset header", async () => { |
| 359 | const delays: number[] = []; |
| 360 | const error = new Error("Rate limited"); |
| 361 | (error as any).status = 429; |
| 362 | (error as any).headers = { "x-ratelimit-reset": "0.5" }; // 500ms for fast testing |
| 363 | const mockFn = jest |
| 364 | .fn() |
| 365 | .mockRejectedValueOnce(error) |
| 366 | .mockResolvedValue("success"); |
| 367 | |
| 368 | const result = await retryAsync(mockFn, { |
| 369 | maxAttempts: 2, |
| 370 | baseDelay: 100, |
| 371 | onRetry: (error, attempt, delay) => { |
| 372 | delays.push(delay); |
| 373 | }, |
| 374 | }); |
| 375 | |
| 376 | expect(result).toBe("success"); |
| 377 | // Should use header value (500ms) not exponential backoff (100ms) |
| 378 | expect(delays[0]).toBeGreaterThan(470); // 500ms with wider tolerance for jitter and system performance |
| 379 | expect(delays[0]).toBeLessThan(540); |
| 380 | }); |
| 381 | |
| 382 | it("should handle HTTP date format in retry-after header", async () => { |
| 383 | const delays: number[] = []; |
| 384 | const futureDate = new Date(Date.now() + 2000); // 2 seconds from now to avoid timing issues |
| 385 | const error = new Error("Rate limited"); |
| 386 | (error as any).status = 429; |
| 387 | (error as any).headers = { "retry-after": futureDate.toUTCString() }; |
| 388 | const mockFn = jest |
| 389 | .fn() |
| 390 | .mockRejectedValueOnce(error) |
| 391 | .mockResolvedValue("success"); |
| 392 | |
| 393 | const result = await retryAsync(mockFn, { |
| 394 | maxAttempts: 2, |
| 395 | baseDelay: 100, |
| 396 | maxDelay: 300, // Cap at 300ms for fast testing |
| 397 | onRetry: (error, attempt, delay) => { |
| 398 | delays.push(delay); |
| 399 | }, |
| 400 | }); |
| 401 | |
| 402 | expect(result).toBe("success"); |
| 403 | // Should be capped at maxDelay (300ms) since original would be ~2000ms |
| 404 | expect(delays[0]).toBeGreaterThan(280); |
| 405 | expect(delays[0]).toBeLessThan(320); |
| 406 | }); |
| 407 | |
| 408 | it("should fallback to exponential backoff when no headers present", async () => { |
| 409 | const delays: number[] = []; |
| 410 | const error = new Error("Server Error"); |
| 411 | (error as any).status = 500; |
| 412 | // No headers property |
| 413 | const mockFn = jest |
| 414 | .fn() |
| 415 | .mockRejectedValueOnce(error) |
| 416 | .mockResolvedValue("success"); |
| 417 | |
| 418 | const result = await retryAsync(mockFn, { |
| 419 | maxAttempts: 2, |
| 420 | baseDelay: 50, // Fast for testing |
| 421 | jitterFactor: 0, |
| 422 | onRetry: (error, attempt, delay) => { |
| 423 | delays.push(delay); |
| 424 | }, |
| 425 | }); |
| 426 | |
| 427 | expect(result).toBe("success"); |
| 428 | // Should use exponential backoff (50ms) since no headers |
| 429 | expect(delays[0]).toBe(50); |
| 430 | }); |
| 431 | |
| 432 | it("should respect maxDelay even with rate limit headers", async () => { |
| 433 | const delays: number[] = []; |
| 434 | const error = new Error("Rate limited"); |
| 435 | (error as any).status = 429; |
| 436 | (error as any).headers = { "retry-after": "10" }; // 10 seconds requested |
| 437 | const mockFn = jest |
| 438 | .fn() |
| 439 | .mockRejectedValueOnce(error) |
| 440 | .mockResolvedValue("success"); |
| 441 | |
| 442 | const result = await retryAsync(mockFn, { |
| 443 | maxAttempts: 2, |
| 444 | baseDelay: 100, |
| 445 | maxDelay: 200, // Cap at 200ms for fast testing |
| 446 | onRetry: (error, attempt, delay) => { |
| 447 | delays.push(delay); |
| 448 | }, |
| 449 | }); |
| 450 | |
| 451 | expect(result).toBe("success"); |
| 452 | // Should be capped at maxDelay (200ms) not header value (10000ms) |
| 453 | // Jitter is applied before maxDelay cap, so delay should never exceed maxDelay |
| 454 | expect(delays[0]).toBeGreaterThanOrEqual(190); |
| 455 | expect(delays[0]).toBeLessThanOrEqual(200); |
| 456 | }); |
| 457 | |
| 458 | it("should handle case-insensitive header names", async () => { |
| 459 | const delays: number[] = []; |
| 460 | const error = new Error("Rate limited"); |
| 461 | (error as any).status = 429; |
| 462 | (error as any).headers = { "Retry-After": "0.3" }; // 300ms for fast testing |
| 463 | const mockFn = jest |
| 464 | .fn() |
| 465 | .mockRejectedValueOnce(error) |
| 466 | .mockResolvedValue("success"); |
| 467 | |
| 468 | const result = await retryAsync(mockFn, { |
| 469 | maxAttempts: 2, |
| 470 | baseDelay: 100, |
| 471 | onRetry: (error, attempt, delay) => { |
| 472 | delays.push(delay); |
| 473 | }, |
| 474 | }); |
| 475 | |
| 476 | expect(result).toBe("success"); |
| 477 | // Should use header value (300ms) |
| 478 | expect(delays[0]).toBeGreaterThan(284); |
| 479 | expect(delays[0]).toBeLessThan(316); |
| 480 | }); |
| 481 | }); |
| 482 | }); |