forked from clerk/javascript
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunWithExponentialBackOff.ts
62 lines (54 loc) · 1.5 KB
/
runWithExponentialBackOff.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
type Milliseconds = number;
type BackoffOptions = Partial<{
firstDelay: Milliseconds;
maxDelay: Milliseconds;
timeMultiple: number;
shouldRetry: (error: unknown, iterationsCount: number) => boolean;
}>;
const defaultOptions: Required<BackoffOptions> = {
firstDelay: 125,
maxDelay: 0,
timeMultiple: 2,
shouldRetry: () => true,
};
const sleep = async (ms: Milliseconds) => new Promise(s => setTimeout(s, ms));
const createExponentialDelayAsyncFn = (opts: {
firstDelay: Milliseconds;
maxDelay: Milliseconds;
timeMultiple: number;
}) => {
let timesCalled = 0;
const calculateDelayInMs = () => {
const constant = opts.firstDelay;
const base = opts.timeMultiple;
const delay = constant * Math.pow(base, timesCalled);
return Math.min(opts.maxDelay || delay, delay);
};
return async (): Promise<void> => {
await sleep(calculateDelayInMs());
timesCalled++;
};
};
export const runWithExponentialBackOff = async <T>(
callback: () => T | Promise<T>,
options: BackoffOptions = {},
): Promise<T> => {
let iterationsCount = 0;
const { shouldRetry, firstDelay, maxDelay, timeMultiple } = {
...defaultOptions,
...options,
};
const delay = createExponentialDelayAsyncFn({ firstDelay, maxDelay, timeMultiple });
// eslint-disable-next-line no-constant-condition
while (true) {
try {
return await callback();
} catch (e) {
iterationsCount++;
if (!shouldRetry(e, iterationsCount)) {
throw e;
}
await delay();
}
}
};