forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtime.ts
More file actions
46 lines (43 loc) · 1.75 KB
/
Copy pathtime.ts
File metadata and controls
46 lines (43 loc) · 1.75 KB
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
export async function delay(milliseconds: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, milliseconds);
});
}
export function exponentialBackoffDelay(currentFailureCount: number, minDelay: number, maxDelay: number, maxFailureCount: number) {
let maxDelayRet = minDelay + ((maxDelay - minDelay) / maxFailureCount) * Math.max(currentFailureCount, maxFailureCount);
return Math.round(Math.random() * maxDelayRet);
}
export type BackoffFunc = <T>(callback: () => Promise<T>) => Promise<T>;
export function createBackoff(
opts?: {
onError?: (e: any, failuresCount: number) => void,
minDelay?: number,
maxDelay?: number,
maxFailureCount?: number
}): BackoffFunc {
return async <T>(callback: () => Promise<T>): Promise<T> => {
let currentFailureCount = 0;
const minDelay = opts && opts.minDelay !== undefined ? opts.minDelay : 250;
const maxDelay = opts && opts.maxDelay !== undefined ? opts.maxDelay : 1000;
const maxFailureCount = opts && opts.maxFailureCount !== undefined ? opts.maxFailureCount : 50;
while (true) {
try {
return await callback();
} catch (e) {
if (currentFailureCount < maxFailureCount) {
currentFailureCount++;
}
if (opts && opts.onError) {
opts.onError(e, currentFailureCount);
}
let waitForRequest = exponentialBackoffDelay(currentFailureCount, minDelay, maxDelay, maxFailureCount);
await delay(waitForRequest);
}
}
};
}
export const backoff = createBackoff({
onError(e, failuresCount) {
console.warn(e);
},
});