Elffuss BraidHub

kikocis/continue public

main · 12.6 KiBRawPermalink
1/**
2 * Configuration options for the retry decorator
3 */
4export interface RetryOptions {
5 /** Maximum number of retry attempts (default: 3) */
6 maxAttempts?: number;
7 /** Base delay in milliseconds (default: 1000) */
8 baseDelay?: number;
9 /** Maximum delay in milliseconds (default: 30000) */
10 maxDelay?: number;
11 /** Jitter factor between 0 and 1 (default: 0.3) */
12 jitterFactor?: number;
13 /** Custom function to determine if an error should be retried */
14 shouldRetry?: (error: any, attempt: number) => boolean;
15 /** Custom function called on each retry attempt */
16 onRetry?: (error: any, attempt: number, delay: number) => void;
17}
18
19/**
20 * Default configuration for retry behavior
21 */
22const DEFAULT_RETRY_OPTIONS: Required<RetryOptions> = {
23 maxAttempts: 3,
24 baseDelay: 1000,
25 maxDelay: 30000,
26 jitterFactor: 0.3,
27 shouldRetry: defaultShouldRetry,
28 onRetry: defaultOnRetry,
29};
30
31/**
32 * Default function to determine if an error should be retried
33 * Retries on:
34 * - Network errors
35 * - HTTP 429 (Too Many Requests)
36 * - HTTP 5xx (Server errors)
37 * - Specific AWS errors
38 * - Timeout errors
39 */
40function defaultShouldRetry(error: any, attempt: number): boolean {
41 // Note: maxAttempts check is handled by the retry logic itself
42 // This function only determines if the error type is retryable
43
44 // Network/connection errors
45 if (
46 error.code === "ENOTFOUND" ||
47 error.code === "ECONNRESET" ||
48 error.code === "ECONNREFUSED" ||
49 error.code === "ETIMEDOUT"
50 ) {
51 return true;
52 }
53
54 // AWS SDK specific errors (v3 - check for AWS error structure and retryable types)
55 const isAwsError =
56 error.$fault || error.$metadata || (error.name && error.__type);
57 const awsRetryableErrors = [
58 "ThrottlingException",
59 "ServiceUnavailableException",
60 "InternalServerError",
61 "RequestTimeout",
62 "ModelNotReadyException",
63 "ModelTimeoutException",
64 "ResourceNotFoundException",
65 ];
66
67 if (isAwsError && error.name && awsRetryableErrors.includes(error.name)) {
68 return true;
69 }
70
71 // HTTP status codes
72 if (error.status || error.statusCode) {
73 const status = error.status || error.statusCode;
74
75 // Rate limiting
76 if (status === 429) {
77 return true;
78 }
79
80 // Server errors (5xx)
81 if (status >= 500 && status < 600) {
82 return true;
83 }
84
85 // Don't retry client errors (4xx except 429)
86 if (status >= 400 && status < 500) {
87 return false;
88 }
89 }
90
91 // Timeout errors
92 if (
93 error.name === "TimeoutError" ||
94 error.message?.includes("timeout") ||
95 error.message?.includes("TIMEOUT")
96 ) {
97 return true;
98 }
99
100 // Abort signal errors should not be retried
101 if (error.name === "AbortError" || error.code === "ABORT_ERR") {
102 return false;
103 }
104
105 // Default to not retrying unknown errors
106 return false;
107}
108
109/**
110 * Default function called on each retry attempt
111 */
112function defaultOnRetry(error: any, attempt: number, delay: number): void {
113 console.warn(
114 `Retry attempt ${attempt} after ${delay}ms delay. Error: ${error.message || error}`,
115 );
116}
117
118/**
119 * Calculate delay with rate limit header awareness and exponential backoff fallback
120 */
121function calculateDelay(
122 attempt: number,
123 baseDelay: number,
124 maxDelay: number,
125 jitterFactor: number,
126 error?: any,
127): number {
128 // Check for rate limiting headers first (more accurate than exponential backoff)
129 if (error?.headers) {
130 const retryAfter =
131 error.headers["retry-after"] ||
132 error.headers["x-ratelimit-reset"] ||
133 error.headers["ratelimit-reset"] ||
134 error.headers["Retry-After"] ||
135 error.headers["X-RateLimit-Reset"] ||
136 error.headers["RateLimit-Reset"];
137
138 if (retryAfter) {
139 let delayMs: number;
140
141 // Parse retry-after header (can be seconds or HTTP date)
142 if (typeof retryAfter === "string" && isNaN(Number(retryAfter))) {
143 // HTTP date format
144 const resetTime = new Date(retryAfter).getTime();
145 const now = Date.now();
146 delayMs = Math.max(0, resetTime - now);
147 } else {
148 // Seconds format
149 delayMs = Number(retryAfter) * 1000;
150 }
151
152 // Apply small jitter to spread requests, then respect maxDelay as hard limit
153 const jitterMultiplier = 1 + (Math.random() * 0.1 - 0.05); // Small jitter ±5%
154 const jitteredDelay = delayMs * jitterMultiplier;
155 return Math.max(0, Math.floor(Math.min(jitteredDelay, maxDelay)));
156 }
157 }
158
159 // Fallback to exponential backoff if no rate limit headers
160 const exponentialDelay = baseDelay * Math.pow(2, attempt - 1);
161 const cappedDelay = Math.min(exponentialDelay, maxDelay);
162
163 // Add jitter: random value between (1 - jitterFactor) and (1 + jitterFactor)
164 const jitterMultiplier = 1 + (Math.random() * 2 - 1) * jitterFactor;
165 const jitteredDelay = cappedDelay * jitterMultiplier;
166
167 return Math.max(0, Math.floor(jitteredDelay));
168}
169
170/**
171 * Sleep for the specified number of milliseconds
172 */
173function sleep(ms: number): Promise<void> {
174 return new Promise((resolve) => setTimeout(resolve, ms));
175}
176
177/**
178 * Retry decorator for async functions with exponential backoff and jitter
179 *
180 * @param options Retry configuration options
181 * @returns Decorator function
182 *
183 * @example
184 * ```typescript
185 * class MyLLM {
186 * @withRetry({ maxAttempts: 5, baseDelay: 2000 })
187 * async streamChat(messages: ChatMessage[]): Promise<AsyncGenerator<ChatMessage>> {
188 * // Implementation that might fail
189 * }
190 * }
191 * ```
192 */
193export function withRetry(options: RetryOptions = {}) {
194 const config = { ...DEFAULT_RETRY_OPTIONS, ...options };
195
196 return function (...args: any[]): any {
197 // Handle different decorator calling patterns
198 const [target, propertyName, descriptor] = args;
199
200 // Get the original method
201 let originalMethod: Function;
202 if (descriptor && descriptor.value) {
203 originalMethod = descriptor.value;
204 } else {
205 // Get method from prototype
206 originalMethod = target[propertyName];
207 }
208
209 if (!originalMethod || typeof originalMethod !== "function") {
210 throw new Error(`@withRetry can only be applied to methods`);
211 }
212
213 // Check if the original method is an async generator function
214 const isAsyncGenerator =
215 originalMethod.constructor.name === "AsyncGeneratorFunction";
216
217 const wrappedMethod = isAsyncGenerator
218 ? async function* (this: any, ...methodArgs: any[]) {
219 let lastError: any;
220
221 for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
222 try {
223 const generator = originalMethod.apply(this, methodArgs);
224 yield* createRetryableAsyncGenerator(
225 generator,
226 config,
227 originalMethod,
228 this,
229 methodArgs,
230 attempt,
231 );
232 return; // Successfully completed
233 } catch (error) {
234 lastError = error;
235
236 // Check if we should retry this error
237 if (!config.shouldRetry(error, attempt)) {
238 throw error;
239 }
240
241 // Don't delay on the last attempt
242 if (attempt === config.maxAttempts) {
243 break;
244 }
245
246 // Calculate delay and wait
247 const delay = calculateDelay(
248 attempt,
249 config.baseDelay,
250 config.maxDelay,
251 config.jitterFactor,
252 error,
253 );
254
255 config.onRetry(error, attempt, delay);
256 await sleep(delay);
257 }
258 }
259
260 // If we get here, all attempts failed
261 throw lastError;
262 }
263 : async function (this: any, ...methodArgs: any[]) {
264 let lastError: any;
265
266 for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
267 try {
268 const result = originalMethod.apply(this, methodArgs);
269 return await result;
270 } catch (error) {
271 lastError = error;
272
273 // Check if we should retry this error
274 if (!config.shouldRetry(error, attempt)) {
275 throw error;
276 }
277
278 // Don't delay on the last attempt
279 if (attempt === config.maxAttempts) {
280 break;
281 }
282
283 // Calculate delay and wait
284 const delay = calculateDelay(
285 attempt,
286 config.baseDelay,
287 config.maxDelay,
288 config.jitterFactor,
289 error,
290 );
291
292 config.onRetry(error, attempt, delay);
293
294 await sleep(delay);
295 }
296 }
297
298 // If we get here, all attempts failed
299 throw lastError;
300 };
301
302 // Apply the wrapped method based on how the decorator was called
303 if (descriptor) {
304 descriptor.value = wrappedMethod;
305 return descriptor;
306 } else {
307 // Handle case where descriptor is not provided
308 target[propertyName] = wrappedMethod;
309 return wrappedMethod;
310 }
311 };
312}
313
314/**
315 * Creates a retryable async generator that handles errors during iteration
316 */
317async function* createRetryableAsyncGenerator<T>(
318 generator: AsyncGenerator<T>,
319 config: Required<RetryOptions>,
320 originalMethod: Function,
321 context: any,
322 args: any[],
323 initialAttempt: number,
324): AsyncGenerator<T> {
325 let currentGenerator = generator;
326 let attempt = initialAttempt;
327
328 try {
329 for await (const value of currentGenerator) {
330 yield value;
331 }
332 } catch (error) {
333 // If we encounter an error during iteration, we can retry by creating a new generator
334 let lastError = error;
335
336 for (
337 let retryAttempt = attempt + 1;
338 retryAttempt <= config.maxAttempts;
339 retryAttempt++
340 ) {
341 // Check if we should retry this error
342 if (!config.shouldRetry(error, retryAttempt)) {
343 throw error;
344 }
345
346 // Don't delay on the last attempt
347 if (retryAttempt === config.maxAttempts) {
348 break;
349 }
350
351 // Calculate delay and wait
352 const delay = calculateDelay(
353 retryAttempt,
354 config.baseDelay,
355 config.maxDelay,
356 config.jitterFactor,
357 error,
358 );
359
360 config.onRetry(error, retryAttempt, delay);
361 await sleep(delay);
362
363 try {
364 // Create a new generator and continue iteration
365 const newGenerator = await originalMethod.apply(context, args);
366
367 if (
368 newGenerator &&
369 typeof newGenerator[Symbol.asyncIterator] === "function"
370 ) {
371 for await (const value of newGenerator) {
372 yield value;
373 }
374 return; // Successfully completed
375 } else {
376 throw new Error("Method did not return an async generator on retry");
377 }
378 } catch (retryError) {
379 lastError = retryError;
380 error = retryError;
381 }
382 }
383
384 // If we get here, all retry attempts failed
385 throw lastError;
386 }
387}
388
389/**
390 * Functional version of retry for use without decorators
391 *
392 * @param fn Function to retry
393 * @param options Retry configuration options
394 * @returns Promise that resolves with the function result or rejects with the last error
395 *
396 * @example
397 * ```typescript
398 * const result = await retryAsync(
399 * () => someApiCall(),
400 * { maxAttempts: 3, baseDelay: 1000 }
401 * );
402 * ```
403 */
404export async function retryAsync<T>(
405 fn: () => Promise<T>,
406 options: RetryOptions = {},
407): Promise<T> {
408 const config = { ...DEFAULT_RETRY_OPTIONS, ...options };
409 let lastError: any;
410
411 for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
412 try {
413 return await fn();
414 } catch (error) {
415 lastError = error;
416
417 // Check if we should retry this error
418 if (!config.shouldRetry(error, attempt)) {
419 throw error;
420 }
421
422 // Don't delay on the last attempt
423 if (attempt === config.maxAttempts) {
424 break;
425 }
426
427 // Calculate delay and wait
428 const delay = calculateDelay(
429 attempt,
430 config.baseDelay,
431 config.maxDelay,
432 config.jitterFactor,
433 error,
434 );
435
436 config.onRetry(error, attempt, delay);
437
438 await sleep(delay);
439 }
440 }
441
442 // If we get here, all attempts failed
443 throw lastError;
444}
445
446/**
447 * Retry decorator specifically configured for LLM providers
448 * Uses sensible defaults for LLM API calls, including longer delays
449 * for capacity provisioning (e.g., AWS Bedrock can require up to 59+ seconds)
450 */
451export function withLLMRetry(options: Partial<RetryOptions> = {}) {
452 return withRetry({
453 maxAttempts: 5, // More attempts for capacity issues
454 baseDelay: 2000, // Start with 2 seconds
455 maxDelay: 90000, // Allow up to 90 seconds for capacity provisioning
456 jitterFactor: 0.4, // Slightly more jitter to spread load
457 ...options,
458 });
459}