* Creates a retryable async generator that handles errors during iteration
( generator: AsyncGenerator<T>, config: Required<RetryOptions>, originalMethod: Function, context: any, args: any[], initialAttempt: number, )
| 331 | * Creates a retryable async generator that handles errors during iteration |
| 332 | */ |
| 333 | async function* createRetryableAsyncGenerator<T>( |
| 334 | generator: AsyncGenerator<T>, |
| 335 | config: Required<RetryOptions>, |
| 336 | originalMethod: Function, |
| 337 | context: any, |
| 338 | args: any[], |
| 339 | initialAttempt: number, |
| 340 | ): AsyncGenerator<T> { |
| 341 | let currentGenerator = generator; |
| 342 | let attempt = initialAttempt; |
| 343 | |
| 344 | try { |
| 345 | for await (const value of currentGenerator) { |
| 346 | yield value; |
| 347 | } |
| 348 | } catch (error) { |
| 349 | // If we encounter an error during iteration, we can retry by creating a new generator |
| 350 | let lastError = error; |
| 351 | |
| 352 | for ( |
| 353 | let retryAttempt = attempt + 1; |
| 354 | retryAttempt <= config.maxAttempts; |
| 355 | retryAttempt++ |
| 356 | ) { |
| 357 | // Check if we should retry this error |
| 358 | if (!config.shouldRetry(error, retryAttempt)) { |
| 359 | throw error; |
| 360 | } |
| 361 | |
| 362 | // Don't delay on the last attempt |
| 363 | if (retryAttempt === config.maxAttempts) { |
| 364 | break; |
| 365 | } |
| 366 | |
| 367 | // Calculate delay and wait |
| 368 | const delay = calculateDelay( |
| 369 | retryAttempt, |
| 370 | config.baseDelay, |
| 371 | config.maxDelay, |
| 372 | config.jitterFactor, |
| 373 | error, |
| 374 | ); |
| 375 | |
| 376 | config.onRetry(error, retryAttempt, delay); |
| 377 | await sleep(delay); |
| 378 | |
| 379 | try { |
| 380 | // Create a new generator and continue iteration |
| 381 | const newGenerator = await originalMethod.apply(context, args); |
| 382 | |
| 383 | if ( |
| 384 | newGenerator && |
| 385 | typeof newGenerator[Symbol.asyncIterator] === "function" |
| 386 | ) { |
| 387 | for await (const value of newGenerator) { |
| 388 | yield value; |
| 389 | } |
| 390 | return; // Successfully completed |
no test coverage detected