Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 3 additions & 66 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

44 changes: 44 additions & 0 deletions src/utils/retry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
export interface RetryOptions {
maxAttempts: number;
delayMs: number;
backoff: number;
}

const DEFAULT_OPTIONS: RetryOptions = {
maxAttempts: 3,
delayMs: 1000,
backoff: 2,
};

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

export async function retry<T>(fn: () => Promise<T>, options: Partial<RetryOptions> = {}): Promise<T> {
const opts = { ...DEFAULT_OPTIONS, ...options };
let lastError: any;
let delay = opts.delayMs;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[ERROR] correctness

Off-by-one error: the loop condition i <= opts.maxAttempts iterates maxAttempts+1 times. For maxAttempts=3, the function body runs 4 times (i=0,1,2,3), meaning 4 attempts instead of the documented 3.

Suggestion: Change the loop condition to i < opts.maxAttempts so it runs exactly maxAttempts times.


for (let i = 0; i < opts.maxAttempts; i++) {
try {
return await fn();
} catch (err) {
lastError = err;
await sleep(delay);
delay *= opts.backoff;
}
}

throw lastError;
}

export function parseRetryAfter(header: string): number {
const val = parseInt(header, 10);
if (!Number.isNaN(val)) return val * 1000;
try {
const date = new Date(header);
const ms = date.getTime();
if (Number.isNaN(ms)) return 0;
return Math.max(0, ms - Date.now());
} catch {
return 0;
}
}