-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
master.js
195 lines (181 loc) · 4.65 KB
/
master.js
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
/**
* Master of child processes. Handles communication between the
* processor and the main process.
*
*/
'use strict';
let status;
let processor;
let currentJobPromise;
const { promisify } = require('util');
// same as process.send but waits until the send is complete
// the async version is used below because otherwise
// the termination handler may exit before the parent
// process has recived the messages it requires
const processSendAsync = promisify(process.send.bind(process));
// https://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify
if (!('toJSON' in Error.prototype)) {
Object.defineProperty(Error.prototype, 'toJSON', {
value: function() {
const alt = {};
Object.getOwnPropertyNames(this).forEach(function(key) {
alt[key] = this[key];
}, this);
return alt;
},
configurable: true,
writable: true
});
}
async function waitForCurrentJobAndExit() {
status = 'TERMINATING';
try {
await currentJobPromise;
} finally {
// it's an exit handler
// eslint-disable-next-line no-process-exit
process.exit(process.exitCode || 0);
}
}
process.on('SIGTERM', waitForCurrentJobAndExit);
process.on('SIGINT', waitForCurrentJobAndExit);
process.on('message', msg => {
switch (msg.cmd) {
case 'init':
processor = require(msg.value);
if (processor.default) {
// support es2015 module.
processor = processor.default;
}
if (processor.length > 1) {
processor = promisify(processor);
} else {
const origProcessor = processor;
processor = function() {
try {
return Promise.resolve(origProcessor.apply(null, arguments));
} catch (err) {
return Promise.reject(err);
}
};
}
status = 'IDLE';
process.send({
cmd: 'init-complete'
});
break;
case 'start':
if (status !== 'IDLE') {
return process.send({
cmd: 'error',
err: new Error('cannot start a not idling child process')
});
}
status = 'STARTED';
currentJobPromise = (async () => {
try {
const result = (await processor(wrapJob(msg.job))) || {};
await processSendAsync({
cmd: 'completed',
value: result
});
} catch (err) {
if (!err.message) {
// eslint-disable-next-line no-ex-assign
err = new Error(err);
}
await processSendAsync({
cmd: 'failed',
value: err
});
} finally {
status = 'IDLE';
currentJobPromise = null;
}
})();
break;
case 'stop':
break;
}
});
process.on('uncaughtException', err => {
if (!err.message) {
err = new Error(err);
}
process.send({
cmd: 'failed',
value: err
});
// An uncaughException leaves this process in a potentially undetermined state so
// we must exit
process.exit(-1);
});
/**
* Enhance the given job argument with some functions
* that can be called from the sandboxed job processor.
*
* Note, the `job` argument is a JSON deserialized message
* from the main node process to this forked child process,
* the functions on the original job object are not in tact.
* The wrapped job adds back some of those original functions.
*/
function wrapJob(job) {
/*
* Emulate the real job `progress` function.
* If no argument is given, it behaves as a sync getter.
* If an argument is given, it behaves as an async setter.
*/
let progressValue = job.progress;
job.progress = function(progress) {
if (progress) {
// Locally store reference to new progress value
// so that we can return it from this process synchronously.
progressValue = progress;
// Send message to update job progress.
return processSendAsync({
cmd: 'progress',
value: progress
});
} else {
// Return the last known progress value.
return progressValue;
}
};
/**
* Update job info
*/
job.update = function(data) {
process.send({
cmd: 'update',
value: data
});
};
/*
* Emulate the real job `log` function.
*/
job.log = function(row) {
return processSendAsync({
cmd: 'log',
value: row
});
};
/*
* Emulate the real job `update` function.
*/
job.update = function(data) {
process.send({
cmd: 'update',
value: data
});
job.data = data;
};
/*
* Emulate the real job `discard` function.
*/
job.discard = function() {
process.send({
cmd: 'discard'
});
};
return job;
}