-
Notifications
You must be signed in to change notification settings - Fork 2
/
retrier.ts
45 lines (38 loc) · 1.2 KB
/
retrier.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
import { delay } from './delay';
import { log } from './logger';
export type Retrier = (func: () => unknown) => Promise<void>;
export const createExponentialBackoffRetrier =
({
retries = 5,
initialDelayMs = 100,
maxDelayMs = 3000,
multiplier = 2,
onFailure = (error) => {
throw error;
},
}: {
retries?: number;
initialDelayMs?: number;
maxDelayMs?: number;
multiplier?: number;
onFailure?: (error: unknown) => unknown;
} = {}): Retrier =>
async (func): Promise<void> => {
let retriesLeft = retries;
let delayMs = initialDelayMs;
let lastError: unknown | undefined;
while (true) {
try {
await func();
return;
} catch (error) {
lastError = error;
}
log.debug(`Failed to process batch (retriesLeft: ${retriesLeft})`);
if (--retriesLeft < 1) break;
await delay(delayMs);
delayMs = Math.min(maxDelayMs, delayMs * multiplier);
}
await onFailure(lastError);
};
export const defaultRetrier = createExponentialBackoffRetrier();