-
-
Notifications
You must be signed in to change notification settings - Fork 253
/
retry-busy.ts
73 lines (68 loc) · 1.81 KB
/
retry-busy.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
63
64
65
66
67
68
69
70
71
72
73
// note: max backoff is the maximum that any *single* backoff will do
import { RimrafAsyncOptions, RimrafOptions } from './index.js'
export const MAXBACKOFF = 200
export const RATE = 1.2
export const MAXRETRIES = 10
export const codes = new Set(['EMFILE', 'ENFILE', 'EBUSY'])
export const retryBusy = (fn: (path: string) => Promise<any>) => {
const method = async (
path: string,
opt: RimrafAsyncOptions,
backoff = 1,
total = 0
) => {
const mbo = opt.maxBackoff || MAXBACKOFF
const rate = opt.backoff || RATE
const max = opt.maxRetries || MAXRETRIES
let retries = 0
while (true) {
try {
return await fn(path)
} catch (er) {
const fer = er as NodeJS.ErrnoException
if (fer?.path === path && fer?.code && codes.has(fer.code)) {
backoff = Math.ceil(backoff * rate)
total = backoff + total
if (total < mbo) {
return new Promise((res, rej) => {
setTimeout(() => {
method(path, opt, backoff, total).then(res, rej)
}, backoff)
})
}
if (retries < max) {
retries++
continue
}
}
throw er
}
}
}
return method
}
// just retries, no async so no backoff
export const retryBusySync = (fn: (path: string) => any) => {
const method = (path: string, opt: RimrafOptions) => {
const max = opt.maxRetries || MAXRETRIES
let retries = 0
while (true) {
try {
return fn(path)
} catch (er) {
const fer = er as NodeJS.ErrnoException
if (
fer?.path === path &&
fer?.code &&
codes.has(fer.code) &&
retries < max
) {
retries++
continue
}
throw er
}
}
}
return method
}