|
1
|
type ProcessOptions = { |
|
2
|
process: Function |
|
3
|
ignoreERESOLVE?: boolean |
|
4
|
} |
|
5
|
|
|
6
|
export default class ProcessManager { |
|
7
|
intervals: NodeJS.Timeout[] = [] |
|
8
|
static MAX_RETRIES = 3 |
|
9
|
|
|
10
|
constructor() { |
|
11
|
this.onTerminated(() => { |
|
12
|
this.intervals.forEach((interval) => { |
|
13
|
clearInterval(interval) |
|
14
|
}) |
|
15
|
}) |
|
16
|
} |
|
17
|
|
|
18
|
onTerminated(fn: () => Promise<void> | void) { |
|
19
|
process.on("SIGTERM", async () => fn()) |
|
20
|
process.on("SIGINT", async () => fn()) |
|
21
|
} |
|
22
|
|
|
23
|
addInterval(interval: NodeJS.Timeout) { |
|
24
|
this.intervals.push(interval) |
|
25
|
} |
|
26
|
|
|
27
|
// when running commands with npx or npm sometimes they |
|
28
|
// terminate with EAGAIN error unexpectedly |
|
29
|
// this utility function allows retrying the process if |
|
30
|
// EAGAIN occurs, or otherwise throw the error that occurs |
|
31
|
async runProcess({ process, ignoreERESOLVE }: ProcessOptions) { |
|
32
|
let processError = false |
|
33
|
let retries = 0 |
|
34
|
do { |
|
35
|
++retries |
|
36
|
try { |
|
37
|
return await process() |
|
38
|
} catch (error) { |
|
39
|
if ( |
|
40
|
typeof error === "object" && |
|
41
|
error !== null && |
|
42
|
"code" in error && |
|
43
|
error?.code === "EAGAIN" |
|
44
|
) { |
|
45
|
processError = true |
|
46
|
} else if ( |
|
47
|
ignoreERESOLVE && |
|
48
|
typeof error === "object" && |
|
49
|
error !== null && |
|
50
|
"code" in error && |
|
51
|
error?.code === "ERESOLVE" |
|
52
|
) { |
|
53
|
// ignore error |
|
54
|
} else { |
|
55
|
throw error |
|
56
|
} |
|
57
|
} |
|
58
|
} while (processError && retries <= ProcessManager.MAX_RETRIES) |
|
59
|
} |
|
60
|
} |