diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index 144ccccf4..a2ded72a2 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -10,7 +10,7 @@ import { parseArgs } from "./args.js"; import { MCPService } from "./mcp.js"; import { executeToolCall } from "./tools.js"; import { BUILTIN_TOOLS } from "./tools/index.js"; -import { chatCompletionStreamWithBackoff } from "./util/exponentialBackoff.js"; +import { chatCompletionStreamWithBackoff, withExponentialBackoff } from "./util/exponentialBackoff.js"; dotenv.config(); @@ -86,14 +86,9 @@ export async function streamChatResponse( let shouldContinueConversation = true; while (shouldContinueConversation) { - let stream; - - try { - // fs.appendFileSync( - // "chat.log", - // "---\n\n" + JSON.stringify(chatHistory, null, 2) + "\n\n" - // ); - stream = await chatCompletionStreamWithBackoff( + // Factory function to create the stream generator + const streamFactory = async () => { + return await chatCompletionStreamWithBackoff( llmApi, { model, @@ -103,13 +98,7 @@ export async function streamChatResponse( }, abortController.signal ); - } catch (error: any) { - console.error( - chalk.red("Error in streamChatResponse:"), - chalk.red(error.message) - ); - throw error; - } + }; let aiResponse = ""; currentToolCalls = []; @@ -117,7 +106,13 @@ export async function streamChatResponse( let toolArguments = ""; try { - for await (const chunk of stream) { + // Use the exponential backoff wrapper for the entire stream + const streamWithBackoff = withExponentialBackoff( + streamFactory, + abortController.signal + ); + + for await (const chunk of streamWithBackoff) { // Check if we should abort if (abortController?.signal.aborted) { break; @@ -206,6 +201,10 @@ export async function streamChatResponse( return fullResponse; } // For other errors, re-throw them + console.error( + chalk.red("Error in streamChatResponse:"), + chalk.red(error.message) + ); throw error; } diff --git a/src/util/exponentialBackoff.test.ts b/src/util/exponentialBackoff.test.ts index 22c634c05..a84cdbbd6 100644 --- a/src/util/exponentialBackoff.test.ts +++ b/src/util/exponentialBackoff.test.ts @@ -1,5 +1,5 @@ -import { ExponentialBackoffOptions } from './exponentialBackoff.js'; -import { jest } from '@jest/globals'; +import { jest } from "@jest/globals"; +import { ExponentialBackoffOptions } from "./exponentialBackoff.js"; // Since the functions are not exported, we need to recreate them for testing function isRetryableError(error: any): boolean { @@ -7,24 +7,28 @@ function isRetryableError(error: any): boolean { if (!error) { return false; } - + // Network errors are retryable - if (error.code === 'ECONNRESET' || error.code === 'ENOTFOUND' || error.code === 'ETIMEDOUT') { + if ( + error.code === "ECONNRESET" || + error.code === "ENOTFOUND" || + error.code === "ETIMEDOUT" + ) { return true; } - + // HTTP status codes that are retryable if (error.status) { const status = error.status; // 429 (Too Many Requests), 502 (Bad Gateway), 503 (Service Unavailable), 504 (Gateway Timeout) return status === 429 || status === 502 || status === 503 || status === 504; } - + // OpenAI specific errors - if (error.type === 'server_error' || error.type === 'rate_limit_exceeded') { + if (error.type === "server_error" || error.type === "rate_limit_exceeded") { return true; } - + return false; } @@ -32,147 +36,149 @@ function calculateDelay( attempt: number, options: Required ): number { - const baseDelay = options.initialDelay * Math.pow(options.backoffMultiplier, attempt); + const baseDelay = + options.initialDelay * Math.pow(options.backoffMultiplier, attempt); const cappedDelay = Math.min(baseDelay, options.maxDelay); - + if (options.jitter) { // Add jitter: randomize between 50% and 100% of the calculated delay return Math.floor(cappedDelay * (0.5 + Math.random() * 0.5)); } - + return cappedDelay; } -describe('exponentialBackoff utilities', () => { - describe('isRetryableError', () => { - it('should return true for network connection errors', () => { - const error = { code: 'ECONNRESET' }; +describe("exponentialBackoff utilities", () => { + describe("isRetryableError", () => { + it("should return true for network connection errors", () => { + const error = { code: "ECONNRESET" }; expect(isRetryableError(error)).toBe(true); }); - it('should return true for DNS resolution errors', () => { - const error = { code: 'ENOTFOUND' }; + it("should return true for DNS resolution errors", () => { + const error = { code: "ENOTFOUND" }; expect(isRetryableError(error)).toBe(true); }); - it('should return true for timeout errors', () => { - const error = { code: 'ETIMEDOUT' }; + it("should return true for timeout errors", () => { + const error = { code: "ETIMEDOUT" }; expect(isRetryableError(error)).toBe(true); }); - it('should return true for 429 Too Many Requests', () => { + it("should return true for 429 Too Many Requests", () => { const error = { status: 429 }; expect(isRetryableError(error)).toBe(true); }); - it('should return true for 502 Bad Gateway', () => { + it("should return true for 502 Bad Gateway", () => { const error = { status: 502 }; expect(isRetryableError(error)).toBe(true); }); - it('should return true for 503 Service Unavailable', () => { + it("should return true for 503 Service Unavailable", () => { const error = { status: 503 }; expect(isRetryableError(error)).toBe(true); }); - it('should return true for 504 Gateway Timeout', () => { + it("should return true for 504 Gateway Timeout", () => { const error = { status: 504 }; expect(isRetryableError(error)).toBe(true); }); - it('should return true for server errors', () => { - const error = { type: 'server_error' }; + it("should return true for server errors", () => { + const error = { type: "server_error" }; expect(isRetryableError(error)).toBe(true); }); - it('should return true for rate limit errors', () => { - const error = { type: 'rate_limit_exceeded' }; + it("should return true for rate limit errors", () => { + const error = { type: "rate_limit_exceeded" }; expect(isRetryableError(error)).toBe(true); }); - it('should return false for 400 Bad Request', () => { + it("should return false for 400 Bad Request", () => { const error = { status: 400 }; expect(isRetryableError(error)).toBe(false); }); - it('should return false for 401 Unauthorized', () => { + it("should return false for 401 Unauthorized", () => { const error = { status: 401 }; expect(isRetryableError(error)).toBe(false); }); - it('should return false for 403 Forbidden', () => { + it("should return false for 403 Forbidden", () => { const error = { status: 403 }; expect(isRetryableError(error)).toBe(false); }); - it('should return false for 404 Not Found', () => { + it("should return false for 404 Not Found", () => { const error = { status: 404 }; expect(isRetryableError(error)).toBe(false); }); - it('should return false for client errors', () => { - const error = { type: 'client_error' }; + it("should return false for client errors", () => { + const error = { type: "client_error" }; expect(isRetryableError(error)).toBe(false); }); - it('should return false for validation errors', () => { - const error = { type: 'validation_error' }; + it("should return false for validation errors", () => { + const error = { type: "validation_error" }; expect(isRetryableError(error)).toBe(false); }); - it('should return false for unknown errors', () => { - const error = { message: 'Unknown error' }; + it("should return false for unknown errors", () => { + const error = { message: "Unknown error" }; expect(isRetryableError(error)).toBe(false); }); - it('should return false for errors without relevant properties', () => { + it("should return false for errors without relevant properties", () => { const error = {}; expect(isRetryableError(error)).toBe(false); }); - it('should return false for null error', () => { + it("should return false for null error", () => { expect(isRetryableError(null)).toBe(false); }); - it('should return false for undefined error', () => { + it("should return false for undefined error", () => { expect(isRetryableError(undefined)).toBe(false); }); - it('should return false for string errors', () => { - expect(isRetryableError('Error message')).toBe(false); + it("should return false for string errors", () => { + expect(isRetryableError("Error message")).toBe(false); }); - it('should handle errors with both code and status', () => { - const retryableError = { code: 'ECONNRESET', status: 200 }; + it("should handle errors with both code and status", () => { + const retryableError = { code: "ECONNRESET", status: 200 }; expect(isRetryableError(retryableError)).toBe(true); - - const nonRetryableError = { code: 'INVALID_REQUEST', status: 429 }; + + const nonRetryableError = { code: "INVALID_REQUEST", status: 429 }; expect(isRetryableError(nonRetryableError)).toBe(true); // Status takes precedence }); - it('should handle errors with both status and type', () => { - const error = { status: 429, type: 'client_error' }; + it("should handle errors with both status and type", () => { + const error = { status: 429, type: "client_error" }; expect(isRetryableError(error)).toBe(true); // Status check comes first }); }); - describe('calculateDelay', () => { + describe("calculateDelay", () => { const defaultOptions: Required = { maxRetries: 3, initialDelay: 1000, maxDelay: 30000, backoffMultiplier: 2, jitter: false, + hiddenRetries: 2, }; - it('should calculate exponential backoff without jitter', () => { + it("should calculate exponential backoff without jitter", () => { expect(calculateDelay(0, defaultOptions)).toBe(1000); expect(calculateDelay(1, defaultOptions)).toBe(2000); expect(calculateDelay(2, defaultOptions)).toBe(4000); expect(calculateDelay(3, defaultOptions)).toBe(8000); }); - it('should respect maximum delay', () => { + it("should respect maximum delay", () => { const options = { ...defaultOptions, maxDelay: 5000 }; expect(calculateDelay(0, options)).toBe(1000); expect(calculateDelay(1, options)).toBe(2000); @@ -181,7 +187,7 @@ describe('exponentialBackoff utilities', () => { expect(calculateDelay(4, options)).toBe(5000); // Still capped }); - it('should handle different backoff multipliers', () => { + it("should handle different backoff multipliers", () => { const options = { ...defaultOptions, backoffMultiplier: 3 }; expect(calculateDelay(0, options)).toBe(1000); expect(calculateDelay(1, options)).toBe(3000); @@ -189,94 +195,94 @@ describe('exponentialBackoff utilities', () => { expect(calculateDelay(3, options)).toBe(27000); }); - it('should handle different initial delays', () => { + it("should handle different initial delays", () => { const options = { ...defaultOptions, initialDelay: 500 }; expect(calculateDelay(0, options)).toBe(500); expect(calculateDelay(1, options)).toBe(1000); expect(calculateDelay(2, options)).toBe(2000); }); - it('should add jitter when enabled', () => { + it("should add jitter when enabled", () => { const options = { ...defaultOptions, jitter: true }; - + // Mock Math.random to return 0.5 (middle of jitter range) const originalRandom = Math.random; Math.random = jest.fn(() => 0.5); - + // With jitter factor of 0.5 + 0.5 * 0.5 = 0.75 expect(calculateDelay(0, options)).toBe(750); // 1000 * 0.75 expect(calculateDelay(1, options)).toBe(1500); // 2000 * 0.75 - + // Restore Math.random Math.random = originalRandom; }); - it('should handle minimum jitter', () => { + it("should handle minimum jitter", () => { const options = { ...defaultOptions, jitter: true }; - + // Mock Math.random to return 0 (minimum jitter) const originalRandom = Math.random; Math.random = jest.fn(() => 0); - + // With jitter factor of 0.5 + 0.5 * 0 = 0.5 expect(calculateDelay(0, options)).toBe(500); // 1000 * 0.5 expect(calculateDelay(1, options)).toBe(1000); // 2000 * 0.5 - + // Restore Math.random Math.random = originalRandom; }); - it('should handle maximum jitter', () => { + it("should handle maximum jitter", () => { const options = { ...defaultOptions, jitter: true }; - + // Mock Math.random to return 1 (maximum jitter) const originalRandom = Math.random; Math.random = jest.fn(() => 1); - + // With jitter factor of 0.5 + 0.5 * 1 = 1.0 expect(calculateDelay(0, options)).toBe(1000); // 1000 * 1.0 expect(calculateDelay(1, options)).toBe(2000); // 2000 * 1.0 - + // Restore Math.random Math.random = originalRandom; }); - it('should apply jitter after applying max delay cap', () => { + it("should apply jitter after applying max delay cap", () => { const options = { ...defaultOptions, maxDelay: 3000, jitter: true }; - + // Mock Math.random to return 0.5 const originalRandom = Math.random; Math.random = jest.fn(() => 0.5); - + // calculateDelay(2, options) would be 4000, but capped at 3000 // Then jitter applied: 3000 * 0.75 = 2250 expect(calculateDelay(2, options)).toBe(2250); - + // Restore Math.random Math.random = originalRandom; }); - it('should handle zero attempt', () => { + it("should handle zero attempt", () => { expect(calculateDelay(0, defaultOptions)).toBe(1000); }); - it('should handle fractional multipliers', () => { + it("should handle fractional multipliers", () => { const options = { ...defaultOptions, backoffMultiplier: 1.5 }; expect(calculateDelay(0, options)).toBe(1000); expect(calculateDelay(1, options)).toBe(1500); expect(calculateDelay(2, options)).toBe(2250); }); - it('should handle edge case with multiplier of 1', () => { + it("should handle edge case with multiplier of 1", () => { const options = { ...defaultOptions, backoffMultiplier: 1 }; expect(calculateDelay(0, options)).toBe(1000); expect(calculateDelay(1, options)).toBe(1000); expect(calculateDelay(2, options)).toBe(1000); }); - it('should handle very large attempt numbers', () => { + it("should handle very large attempt numbers", () => { const options = { ...defaultOptions, maxDelay: 60000 }; expect(calculateDelay(10, options)).toBe(60000); // Should be capped }); }); -}); \ No newline at end of file +}); diff --git a/src/util/exponentialBackoff.ts b/src/util/exponentialBackoff.ts index e3f76c282..9a9fd3ded 100644 --- a/src/util/exponentialBackoff.ts +++ b/src/util/exponentialBackoff.ts @@ -1,6 +1,7 @@ import { BaseLlmApi } from "@continuedev/openai-adapters"; -import { warn, error } from "../logging.js"; import type { ChatCompletionCreateParamsStreaming } from "openai/resources.mjs"; +import { error, warn } from "../logging.js"; +import { formatError } from "./formatError.js"; export interface ExponentialBackoffOptions { /** Maximum number of retry attempts */ @@ -13,14 +14,17 @@ export interface ExponentialBackoffOptions { backoffMultiplier?: number; /** Jitter factor to add randomness */ jitter?: boolean; + /** Number of retries to hide from logging */ + hiddenRetries?: number; } const DEFAULT_OPTIONS: Required = { - maxRetries: 3, + maxRetries: 10, initialDelay: 1000, maxDelay: 30000, - backoffMultiplier: 2, + backoffMultiplier: 1.6, jitter: true, + hiddenRetries: 2, }; /** @@ -28,22 +32,32 @@ const DEFAULT_OPTIONS: Required = { */ function isRetryableError(error: any): boolean { // Network errors are retryable - if (error.code === 'ECONNRESET' || error.code === 'ENOTFOUND' || error.code === 'ETIMEDOUT') { + if ( + error.code === "ECONNRESET" || + error.code === "ENOTFOUND" || + error.code === "ETIMEDOUT" + ) { return true; } - + // HTTP status codes that are retryable if (error.status) { const status = error.status; // 429 (Too Many Requests), 502 (Bad Gateway), 503 (Service Unavailable), 504 (Gateway Timeout) return status === 429 || status === 502 || status === 503 || status === 504; } - + // OpenAI specific errors - if (error.type === 'server_error' || error.type === 'rate_limit_exceeded') { + if (error.type === "server_error" || error.type === "rate_limit_exceeded") { return true; } - + + // Anthropic specific errors + const lower = error.message?.toLowerCase(); + if (lower?.includes("overloaded")) { + return true; + } + return false; } @@ -54,14 +68,15 @@ function calculateDelay( attempt: number, options: Required ): number { - const baseDelay = options.initialDelay * Math.pow(options.backoffMultiplier, attempt); + const baseDelay = + options.initialDelay * Math.pow(options.backoffMultiplier, attempt); const cappedDelay = Math.min(baseDelay, options.maxDelay); - + if (options.jitter) { // Add jitter: randomize between 50% and 100% of the calculated delay return Math.floor(cappedDelay * (0.5 + Math.random() * 0.5)); } - + return cappedDelay; } @@ -76,45 +91,133 @@ export async function chatCompletionStreamWithBackoff( ): Promise> { const opts = { ...DEFAULT_OPTIONS, ...options }; let lastError: any; - + for (let attempt = 0; attempt <= opts.maxRetries; attempt++) { try { // Check if we should abort before making the request if (abortSignal.aborted) { - throw new Error('Request aborted'); + throw new Error("Request aborted"); } - + return llmApi.chatCompletionStream(params, abortSignal); } catch (err: any) { lastError = err; - + // Don't retry if the request was aborted if (abortSignal.aborted) { throw err; } - + // Don't retry on the last attempt if (attempt === opts.maxRetries) { break; } - + // Only retry if the error is retryable if (!isRetryableError(err)) { throw err; } - + const delay = calculateDelay(attempt, opts); - - warn( - `Retrying LLM API call (attempt ${attempt + 1}/${opts.maxRetries + 1}) after ${delay}ms delay. Error: ${err.message}` - ); - + + // Only log retry attempts after the first hiddenRetries attempts + if (attempt >= opts.hiddenRetries) { + warn( + `Retrying LLM API call (attempt ${attempt + 1 - opts.hiddenRetries}/${ + opts.maxRetries + 1 - opts.hiddenRetries + }) after ${delay}ms delay. Error: ${err.message}` + ); + } + // Wait before retrying - await new Promise(resolve => setTimeout(resolve, delay)); + await new Promise((resolve) => setTimeout(resolve, delay)); } } - + // If we get here, all retries failed - error(`LLM API call failed after ${opts.maxRetries + 1} attempts. Last error: ${lastError.message}`); + error( + `LLM API call failed after ${opts.maxRetries + 1} attempts. Last error: ${ + lastError.message + }` + ); throw lastError; -} \ No newline at end of file +} + +/** + * Wraps an async generator with exponential backoff retry logic. + * If the generator throws an error during iteration, it will retry the entire generator. + */ +export async function* withExponentialBackoff( + generatorFactory: () => Promise>, + abortSignal: AbortSignal, + options: ExponentialBackoffOptions = {} +): AsyncGenerator { + const opts = { ...DEFAULT_OPTIONS, ...options }; + let lastError: any; + + for (let attempt = 0; attempt <= opts.maxRetries; attempt++) { + let yieldedValues: T[] = []; + + try { + // Check if we should abort before creating the generator + if (abortSignal.aborted) { + throw new Error("Request aborted"); + } + + const generator = await generatorFactory(); + + // Iterate through the generator and yield each value + for await (const chunk of generator) { + // Check abort signal during iteration + if (abortSignal.aborted) { + throw new Error("Request aborted"); + } + + yieldedValues.push(chunk); + yield chunk; + } + + // If we successfully completed the generator, we're done + return; + } catch (err: any) { + lastError = err; + + // Don't retry if the request was aborted + if (abortSignal.aborted) { + throw err; + } + + // Don't retry on the last attempt + if (attempt === opts.maxRetries) { + break; + } + + // Only retry if the error is retryable + if (!isRetryableError(err)) { + throw err; + } + + const delay = calculateDelay(attempt, opts); + + // Only log retry attempts after the first opts.hiddenRetries attempts + if (attempt >= opts.hiddenRetries) { + warn( + `Retrying request (${attempt + 1 - opts.hiddenRetries}/${ + opts.maxRetries + 1 - opts.hiddenRetries + }). Error: ${formatError(err)}` + ); + } + + // Wait before retrying + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } + + // If we get here, all retries failed + error( + `Failed after ${opts.maxRetries + 1} attempts. Last error: ${ + lastError.message + }` + ); + throw lastError; +} diff --git a/src/util/withExponentialBackoff.test.ts b/src/util/withExponentialBackoff.test.ts new file mode 100644 index 000000000..6339fb01b --- /dev/null +++ b/src/util/withExponentialBackoff.test.ts @@ -0,0 +1,312 @@ +import { jest } from '@jest/globals'; +import { withExponentialBackoff } from './exponentialBackoff.js'; + +// Mock the logging functions +jest.mock('../logging.js', () => ({ + warn: jest.fn(), + error: jest.fn(), +})); + +describe('withExponentialBackoff', () => { + let abortController: AbortController; + + beforeEach(() => { + abortController = new AbortController(); + jest.clearAllMocks(); + }); + + it('should successfully yield all values from generator', async () => { + const mockData = ['chunk1', 'chunk2', 'chunk3']; + const generatorFactory = jest.fn(async () => { + return (async function* () { + for (const chunk of mockData) { + yield chunk; + } + })(); + }); + + const results: string[] = []; + const generator = withExponentialBackoff(generatorFactory, abortController.signal); + + for await (const chunk of generator) { + results.push(chunk); + } + + expect(results).toEqual(mockData); + expect(generatorFactory).toHaveBeenCalledTimes(1); + }); + + it('should retry on retryable errors during generator creation', async () => { + let callCount = 0; + const generatorFactory = jest.fn(async () => { + callCount++; + if (callCount === 1) { + const error = new Error('Connection reset'); + (error as any).code = 'ECONNRESET'; + throw error; + } + return (async function* () { + yield 'success'; + })(); + }); + + const results: string[] = []; + const generator = withExponentialBackoff(generatorFactory, abortController.signal, { + maxRetries: 2, + initialDelay: 10, // Short delay for testing + }); + + for await (const chunk of generator) { + results.push(chunk); + } + + expect(results).toEqual(['success']); + expect(generatorFactory).toHaveBeenCalledTimes(2); + }); + + it('should retry on retryable errors during generator iteration', async () => { + let callCount = 0; + const generatorFactory = jest.fn(async () => { + callCount++; + return (async function* () { + if (callCount === 1) { + yield 'first'; + const error = new Error('Rate limit exceeded'); + (error as any).status = 429; + throw error; + } + yield 'retry-success'; + })(); + }); + + const results: string[] = []; + const generator = withExponentialBackoff(generatorFactory, abortController.signal, { + maxRetries: 2, + initialDelay: 10, + }); + + for await (const chunk of generator) { + results.push(chunk); + } + + // Should get the partial result from first attempt, then the retry result + expect(results).toEqual(['first', 'retry-success']); + expect(generatorFactory).toHaveBeenCalledTimes(2); + }); + + it('should not retry on non-retryable errors', async () => { + const generatorFactory = jest.fn(async () => { + const error = new Error('Bad request'); + (error as any).status = 400; + throw error; + }); + + const generator = withExponentialBackoff(generatorFactory, abortController.signal); + + await expect(async () => { + for await (const chunk of generator) { + // Should not reach here + } + }).rejects.toThrow('Bad request'); + + expect(generatorFactory).toHaveBeenCalledTimes(1); + }); + + it('should throw error after max retries exceeded', async () => { + const generatorFactory = jest.fn(async () => { + const error = new Error('Service unavailable'); + (error as any).status = 503; + throw error; + }); + + const generator = withExponentialBackoff(generatorFactory, abortController.signal, { + maxRetries: 2, + initialDelay: 10, + }); + + await expect(async () => { + for await (const chunk of generator) { + // Should not reach here + } + }).rejects.toThrow('Service unavailable'); + + expect(generatorFactory).toHaveBeenCalledTimes(3); // Initial + 2 retries + }); + + it('should handle abort signal during generator creation', async () => { + const generatorFactory = jest.fn(async () => { + return (async function* () { + yield 'should-not-yield'; + })(); + }); + + // Abort immediately + abortController.abort(); + + const generator = withExponentialBackoff(generatorFactory, abortController.signal); + + await expect(async () => { + for await (const chunk of generator) { + // Should not reach here + } + }).rejects.toThrow('Request aborted'); + + expect(generatorFactory).toHaveBeenCalledTimes(0); + }); + + it('should handle abort signal during generator iteration', async () => { + const generatorFactory = jest.fn(async () => { + return (async function* () { + yield 'first'; + // Simulate a delay where abort can happen + await new Promise(resolve => setTimeout(resolve, 50)); + yield 'second'; + })(); + }); + + const results: string[] = []; + const generator = withExponentialBackoff(generatorFactory, abortController.signal); + + const asyncIterator = generator[Symbol.asyncIterator](); + + // Get first chunk + const firstResult = await asyncIterator.next(); + expect(firstResult.value).toBe('first'); + results.push(firstResult.value); + + // Abort before getting second chunk + abortController.abort(); + + // Should throw on next iteration + await expect(asyncIterator.next()).rejects.toThrow('Request aborted'); + + expect(results).toEqual(['first']); + }); + + it('should handle empty generator', async () => { + const generatorFactory = jest.fn(async () => { + return (async function* () { + // Empty generator + })(); + }); + + const results: string[] = []; + const generator = withExponentialBackoff(generatorFactory, abortController.signal); + + for await (const chunk of generator) { + results.push(chunk); + } + + expect(results).toEqual([]); + expect(generatorFactory).toHaveBeenCalledTimes(1); + }); + + it('should handle generator that throws after yielding some values', async () => { + let callCount = 0; + const generatorFactory = jest.fn(async () => { + callCount++; + return (async function* () { + if (callCount === 1) { + yield 'first'; + yield 'second'; + const error = new Error('Service unavailable'); + (error as any).status = 503; + throw error; + } + yield 'retry-first'; + yield 'retry-second'; + })(); + }); + + const results: string[] = []; + const generator = withExponentialBackoff(generatorFactory, abortController.signal, { + maxRetries: 1, + initialDelay: 10, + }); + + for await (const chunk of generator) { + results.push(chunk); + } + + // Should get values from both attempts since we yield as we go + expect(results).toEqual(['first', 'second', 'retry-first', 'retry-second']); + expect(generatorFactory).toHaveBeenCalledTimes(2); + }); + + it('should use custom retry options', async () => { + let callCount = 0; + const generatorFactory = jest.fn(async () => { + callCount++; + if (callCount <= 2) { + const error = new Error('Service unavailable'); + (error as any).status = 503; + throw error; + } + return (async function* () { + yield 'success'; + })(); + }); + + const results: string[] = []; + const generator = withExponentialBackoff(generatorFactory, abortController.signal, { + maxRetries: 3, + initialDelay: 5, + maxDelay: 20, + backoffMultiplier: 3, + jitter: false, + }); + + for await (const chunk of generator) { + results.push(chunk); + } + + expect(results).toEqual(['success']); + expect(generatorFactory).toHaveBeenCalledTimes(3); + }); + + it('should handle different types of retryable errors', async () => { + const retryableErrors = [ + { code: 'ECONNRESET', message: 'Connection reset' }, + { code: 'ENOTFOUND', message: 'Host not found' }, + { code: 'ETIMEDOUT', message: 'Connection timeout' }, + { status: 429, message: 'Too many requests' }, + { status: 502, message: 'Bad gateway' }, + { status: 503, message: 'Service unavailable' }, + { status: 504, message: 'Gateway timeout' }, + { type: 'server_error', message: 'Server error' }, + { type: 'rate_limit_exceeded', message: 'Rate limit exceeded' }, + ]; + + for (const errorData of retryableErrors) { + let callCount = 0; + const generatorFactory = jest.fn(async () => { + callCount++; + if (callCount === 1) { + const error = new Error(errorData.message); + Object.assign(error, errorData); + throw error; + } + return (async function* () { + yield 'success'; + })(); + }); + + const results: string[] = []; + const generator = withExponentialBackoff(generatorFactory, abortController.signal, { + maxRetries: 1, + initialDelay: 10, + }); + + for await (const chunk of generator) { + results.push(chunk); + } + + expect(results).toEqual(['success']); + expect(generatorFactory).toHaveBeenCalledTimes(2); + + // Reset for next test + abortController = new AbortController(); + jest.clearAllMocks(); + } + }); +}); \ No newline at end of file