-
Notifications
You must be signed in to change notification settings - Fork 669
Expand file tree
/
Copy pathchild.ts
More file actions
264 lines (228 loc) · 6.98 KB
/
Copy pathchild.ts
File metadata and controls
264 lines (228 loc) · 6.98 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import { ChildProcess, fork } from 'child_process';
import { AddressInfo, createServer } from 'net';
import { Worker } from 'worker_threads';
import { ChildCommand, ParentCommand } from '../enums';
import { SandboxedOptions } from '../interfaces';
import { EventEmitter } from 'events';
/**
* @see https://nodejs.org/api/process.html#process_exit_codes
*/
const exitCodesErrors: { [index: number]: string } = {
1: 'Uncaught Fatal Exception',
2: 'Unused',
3: 'Internal JavaScript Parse Error',
4: 'Internal JavaScript Evaluation Failure',
5: 'Fatal Error',
6: 'Non-function Internal Exception Handler',
7: 'Internal Exception Handler Run-Time Failure',
8: 'Unused',
9: 'Invalid Argument',
10: 'Internal JavaScript Run-Time Failure',
12: 'Invalid Debug Argument',
13: 'Unfinished Top-Level Await',
};
/**
* Child class
*
* This class is used to create a child process or worker thread, and allows using
* isolated processes or threads for processing jobs.
*
*/
export class Child extends EventEmitter {
childProcess: ChildProcess;
worker: Worker;
private _exitCode: number = null;
private _signalCode: number = null;
private _killed = false;
constructor(
private mainFile: string,
public processFile: string,
private opts: SandboxedOptions = {
useWorkerThreads: false,
},
) {
super();
}
get pid() {
if (this.childProcess) {
return this.childProcess.pid;
} else if (this.worker) {
// Worker threads pids can become negative when they are terminated
// so we need to use the absolute value to index the retained object
return Math.abs(this.worker.threadId);
} else {
throw new Error('No child process or worker thread');
}
}
get exitCode() {
return this._exitCode;
}
get signalCode() {
return this._signalCode;
}
get killed() {
if (this.childProcess) {
return this.childProcess.killed;
}
return this._killed;
}
async init(): Promise<void> {
const execArgv = await convertExecArgv(process.execArgv);
let parent: ChildProcess | Worker;
if (this.opts.useWorkerThreads) {
this.worker = parent = new Worker(this.mainFile, {
execArgv,
stdin: true,
stdout: true,
stderr: true,
...(this.opts.workerThreadsOptions
? this.opts.workerThreadsOptions
: {}),
});
} else {
this.childProcess = parent = fork(this.mainFile, [], {
execArgv,
stdio: 'pipe',
...(this.opts.workerForkOptions ? this.opts.workerForkOptions : {}),
});
}
parent.on('exit', (exitCode: number, signalCode?: number) => {
this._exitCode = exitCode;
// Coerce to null if undefined for backwards compatibility
signalCode = typeof signalCode === 'undefined' ? null : signalCode;
this._signalCode = signalCode;
this._killed = true;
this.emit('exit', exitCode, signalCode);
// Clean all listeners, we do not expect any more events after "exit"
parent.removeAllListeners();
this.removeAllListeners();
});
parent.on('error', (...args) => this.emit('error', ...args));
parent.on('message', (...args) => this.emit('message', ...args));
parent.on('close', (...args) => this.emit('close', ...args));
parent.stdout.pipe(process.stdout);
parent.stderr.pipe(process.stderr);
await this.initChild();
}
async send(msg: any) {
return new Promise<void>((resolve, reject) => {
if (this.childProcess) {
this.childProcess.send(msg, (err: Error | null) => {
if (err) {
reject(err);
} else {
resolve();
}
});
} else if (this.worker) {
resolve(this.worker.postMessage(msg));
} else {
resolve();
}
});
}
private killProcess(signal: 'SIGTERM' | 'SIGKILL' = 'SIGKILL') {
if (this.childProcess) {
this.childProcess.kill(signal);
} else if (this.worker) {
this.worker.terminate();
}
}
async kill(
signal: 'SIGTERM' | 'SIGKILL' = 'SIGKILL',
timeoutMs?: number,
): Promise<void> {
if (this.hasProcessExited()) {
return;
}
const parent = this.childProcess || this.worker;
const onExit = new Promise<void>(resolve => {
parent.once('exit', () => resolve());
/**
* Re-check after attaching the listener to close the race window where the process exits (and
* removeAllListeners is called) between the guard above and the listener registration.
*/
if (this.hasProcessExited()) {
resolve();
}
});
this.killProcess(signal);
if (timeoutMs !== undefined && (timeoutMs === 0 || isFinite(timeoutMs))) {
const escalate = new Promise<void>(resolve =>
setTimeout(() => {
if (!this.hasProcessExited()) {
this.killProcess('SIGKILL');
}
resolve();
}, timeoutMs),
);
await Promise.race([onExit, escalate]);
} else {
await onExit;
}
}
private async initChild() {
const onComplete = new Promise<void>((resolve, reject) => {
const onMessageHandler = (msg: any) => {
if (!Object.values(ParentCommand).includes(msg.cmd)) {
return;
}
if (msg.cmd === ParentCommand.InitCompleted) {
resolve();
} else if (msg.cmd === ParentCommand.InitFailed) {
const err = new Error();
err.stack = msg.err.stack;
err.message = msg.err.message;
reject(err);
}
this.off('message', onMessageHandler);
this.off('close', onCloseHandler);
};
const onCloseHandler = (code: number, signal: number) => {
if (code > 128) {
code -= 128;
}
const msg = exitCodesErrors[code] || `Unknown exit code ${code}`;
reject(
new Error(`Error initializing child: ${msg} and signal ${signal}`),
);
this.off('message', onMessageHandler);
this.off('close', onCloseHandler);
};
this.on('message', onMessageHandler);
this.on('close', onCloseHandler);
});
await this.send({
cmd: ChildCommand.Init,
value: this.processFile,
});
await onComplete;
}
hasProcessExited(): boolean {
return !!(this.exitCode !== null || this.signalCode);
}
}
const getFreePort = async () => {
return new Promise(resolve => {
const server = createServer();
server.listen(0, () => {
const { port } = server.address() as AddressInfo;
server.close(() => resolve(port));
});
});
};
const convertExecArgv = async (execArgv: string[]): Promise<string[]> => {
const standard: string[] = [];
const convertedArgs: string[] = [];
for (let i = 0; i < execArgv.length; i++) {
const arg = execArgv[i];
if (arg.indexOf('--inspect') === -1) {
standard.push(arg);
} else {
const argName = arg.split('=')[0];
const port = await getFreePort();
convertedArgs.push(`${argName}=${port}`);
}
}
return standard.concat(convertedArgs);
};