-
-
Notifications
You must be signed in to change notification settings - Fork 629
Expand file tree
/
Copy pathstartupErrorHandler.ts
More file actions
65 lines (60 loc) · 1.99 KB
/
Copy pathstartupErrorHandler.ts
File metadata and controls
65 lines (60 loc) · 1.99 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import cluster from 'cluster';
import log from '../shared/log.js';
import { WORKER_STARTUP_FAILURE, type WorkerStartupFailureMessage } from '../shared/workerMessages.js';
export type StartupListenErrorHandlerOptions = {
err: Error;
host: string;
port: number;
isWorker?: boolean;
send?: NodeJS.Process['send'];
exit?: NodeJS.Process['exit'];
};
export function handleStartupListenError({
err,
host,
port,
isWorker = cluster.isWorker,
send,
exit,
}: StartupListenErrorHandlerOptions) {
const sendFn = send ?? process.send?.bind(process);
const exitFn = exit ?? ((code?: number) => process.exit(code));
log.error({ err, host, port }, 'Node renderer failed to start');
if (isWorker) {
if (!sendFn) {
log.error('Cluster worker has no IPC channel; cannot notify master of startup failure');
exitFn(1);
return;
}
const startupFailure: WorkerStartupFailureMessage = {
type: WORKER_STARTUP_FAILURE,
stage: 'listen',
code: (err as NodeJS.ErrnoException).code,
errno: (err as NodeJS.ErrnoException).errno,
syscall: (err as NodeJS.ErrnoException).syscall,
host,
port,
message: err.message,
};
try {
let exited = false;
const doExit = (sendErr?: Error | null) => {
if (exited) return;
exited = true;
if (sendErr) log.error({ err: sendErr }, 'Failed to send startup failure message to master');
exitFn(1);
};
sendFn(startupFailure, undefined, undefined, doExit);
// Safety net: if the IPC channel is half-broken the callback may never
// fire, leaving this worker alive indefinitely. Force exit after a timeout.
const IPC_SEND_TIMEOUT_MS = 2000;
const timer = setTimeout(() => doExit(), IPC_SEND_TIMEOUT_MS);
if (typeof timer.unref === 'function') timer.unref();
} catch (sendErr) {
log.error({ err: sendErr as Error }, 'Failed to send startup failure message to master');
exitFn(1);
}
} else {
exitFn(1);
}
}