Skip to content

Commit cdfda0d

Browse files
committed
Update retryWithBackoff.js
1 parent 9f59f68 commit cdfda0d

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

src/utils/retryWithBackoff.js

+20-5
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,17 @@ log.setLevel(log.levels.SILENT);
1212
* @param {number} options.retryMultiplier - Multiplier for the retry delay.
1313
* @param {string} errorType - The type of error to throw ('SendMessageError' or 'EmbeddingsError').
1414
* @returns {Promise<any>} - The result of the function call.
15-
* @throws {SendMessageError|EmbeddingsError} - Throws an error if all retry attempts fail.
15+
* @throws {SendMessageError|EmbeddingsError} - Throws an error if all retry attempts fail or on specific HTTP errors.
1616
*/
1717
async function retryWithBackoff(fn, options, errorType) {
1818
const start = hrtime();
1919
let { retryAttempts = 3, retryMultiplier = 0.3 } = options;
2020
let currentRetry = 0;
21+
let lastError;
2122

2223
while (retryAttempts > 0) {
2324
try {
24-
log.log(`retryWithBackoff:${retryAttempts}`);
25+
log.log(`retryWithBackoff: Attempt ${currentRetry + 1}`);
2526
let response = await fn();
2627
if (response?.results) {
2728
const end = hrtime(start);
@@ -31,6 +32,7 @@ async function retryWithBackoff(fn, options, errorType) {
3132
return response;
3233
}
3334
} catch (error) {
35+
lastError = error;
3436
const statusCode = error.response?.status;
3537
const delayTime = (currentRetry + 1) * retryMultiplier * 1000 + 500;
3638

@@ -46,13 +48,11 @@ async function retryWithBackoff(fn, options, errorType) {
4648
);
4749

4850
throw createError(errorType, statusCode, error);
49-
break;
5051

5152
case 429:
5253
case 503:
5354
// Retry after the specified time in the Retry-After header if present
5455
const retryAfter = error.response?.headers['retry-after'];
55-
5656
if (retryAfter) {
5757
log.log(
5858
`retryWithBackoff:error:${statusCode}: Retry after ${retryAfter} s`,
@@ -72,13 +72,28 @@ async function retryWithBackoff(fn, options, errorType) {
7272

7373
default:
7474
throw createError(errorType, statusCode || 'Unknown', error);
75-
break;
7675
}
7776
}
7877
currentRetry++;
7978
retryAttempts--;
8079
}
8180

81+
// If all retries are exhausted without specific HTTP errors, return the last response with additional info
82+
if (lastError) {
83+
const end = hrtime(start);
84+
const milliseconds = end[0] * 1e3 + end[1] / 1e6;
85+
86+
const results = {
87+
total_time: milliseconds.toFixed(5),
88+
retries: currentRetry,
89+
success: false,
90+
error: `HTTP ${statusCode}: ${
91+
lastError.response?.statusText || lastError.message
92+
}}`,
93+
};
94+
return results; // Return the last error with total_time and retries
95+
}
96+
8297
if (errorType === 'SendMessageError') {
8398
throw new SendMessageError('All retry attempts failed');
8499
} else if (errorType === 'EmbeddingsError') {

0 commit comments

Comments
 (0)