This repository has been archived by the owner on Aug 31, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 97
/
worker.js
231 lines (192 loc) · 6.78 KB
/
worker.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
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
'use strict';
const EventEmitter = require('events');
const assert = require('assert');
const path = require('path');
const util = require('util');
const errors = require('internal/errors');
const { MessagePort, MessageChannel } = internalBinding('messaging');
const { serializeError, deserializeError } = require('internal/error-serdes');
util.inherits(MessagePort, EventEmitter);
const {
Worker: WorkerImpl,
getEnvMessagePort,
setSerializeWorkerErrorFunction,
threadId,
MESSAGE_FLAG_NONE,
MESSAGE_FLAG_CUSTOM_OFFSET,
MESSAGE_FLAG_COULD_NOT_SERIALIZE_ERR,
MESSAGE_FLAG_OUT_OF_MEMORY,
MESSAGE_FLAG_ERROR_MESSAGE
} = internalBinding('worker');
setSerializeWorkerErrorFunction(serializeError);
const kHandle = Symbol('kHandle');
const kPort = Symbol('kPort');
const kDispose = Symbol('kDispose');
const kOnExit = Symbol('kOnExit');
const kOnMessage = Symbol('kOnMessage');
const kOnCouldNotSerializeErr = Symbol('kOnCouldNotSerializeErr');
const kOnOutOfMemory = Symbol('kOnOutOfMemory');
const kOnErrorMessage = Symbol('kOnErrorMessage');
const debug = util.debuglog('worker');
// Flags >= MESSAGE_FLAG_CUSTOM_OFFSET are reserved for custom commands in the
// sense that they are not handled in the C++ layer.
// MESSAGE_FLAG_NONE is the default flag for normal user messages sent by
// `postMessage`.
const kUpAndRunning = MESSAGE_FLAG_CUSTOM_OFFSET;
const kLoadScript = MESSAGE_FLAG_CUSTOM_OFFSET + 1;
function setupPortReferencing(port, eventEmitter, eventName) {
// TODO(addaleax): Merge with oninit() in lib/extras/messaging.js
// Keep track of whether there are any workerMessage listeners:
// If there are some, ref() the channel so it keeps the event loop alive.
// If there are none or all are removed, unref() the channel so the worker
// can shutdown gracefully.
port.unref();
eventEmitter.on('newListener', (name) => {
if (name === eventName && eventEmitter.listenerCount(eventName) === 0) {
port.ref();
port.start();
}
});
eventEmitter.on('removeListener', (name) => {
if (name === eventName && eventEmitter.listenerCount(eventName) === 0) {
port.stop();
port.unref();
}
});
}
class Worker extends EventEmitter {
constructor(filename, options = {}) {
super();
debug(`[${threadId}] create new worker`, filename, options);
if (typeof filename !== 'string') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'filename',
'string', filename);
}
if (!options.eval) {
if (!path.isAbsolute(filename)) {
throw new errors.TypeError('ERR_WORKER_NEED_ABSOLUTE_PATH', filename);
}
const ext = path.extname(filename);
if (ext !== '.js' && ext !== '.mjs') {
throw new errors.TypeError('ERR_WORKER_UNSUPPORTED_EXTENSION', ext);
}
}
const resourceLimits = {
maxSemiSpaceSize: options.maxSemiSpaceSize | 0,
maxOldSpaceSize: options.maxOldSpaceSize | 0
};
// Set up the C++ handle for the worker, as well as some internal wiring.
this[kHandle] = new WorkerImpl(resourceLimits);
this[kHandle].onexit = (code) => this[kOnExit](code);
this[kPort] = this[kHandle].messagePort;
this[kPort].on('message', (payload) => this.emit('message', payload));
this[kPort].on('flaggedMessage', (flag, payload) => {
this[kOnMessage](flag, payload);
});
this[kPort].start();
debug(`[${threadId}] created Worker with ID ${this.threadId}`);
this[kPort].postMessage([
filename, !!options.eval, options.workerData
], undefined, kLoadScript);
// Actually start the new thread now that everything is in place.
this[kHandle].startThread();
}
[kOnExit](code) {
debug(`[${threadId}] hears end event for Worker ${this.threadId}`);
this[kDispose]();
this.emit('exit', code);
this.removeAllListeners();
}
[kOnCouldNotSerializeErr]() {
this.emit('error', new errors.Error('ERR_WORKER_UNSERIALIZABLE_ERROR'));
}
[kOnOutOfMemory](serialized) {
this.emit('error', new errors.Error('ERR_WORKER_OUT_OF_MEMORY'));
}
[kOnErrorMessage](serialized) {
// This is what is called for uncaught exceptions.
const error = deserializeError(serialized);
this.emit('error', error);
}
[kOnMessage](flag, payload) {
switch (flag) {
case MESSAGE_FLAG_NONE:
// This is a userland message.
return this.emit('message', payload);
case kUpAndRunning:
return this.emit('online');
case MESSAGE_FLAG_COULD_NOT_SERIALIZE_ERR:
return this[kOnCouldNotSerializeErr](payload);
case MESSAGE_FLAG_OUT_OF_MEMORY:
return this[kOnOutOfMemory](payload);
case MESSAGE_FLAG_ERROR_MESSAGE:
return this[kOnErrorMessage](payload);
}
assert.fail(`Unknown worker message flag ${flag}`);
}
[kDispose]() {
this[kHandle].onexit = null;
this[kHandle] = null;
this[kPort] = null;
}
postMessage(payload, transferList = undefined) {
if (this[kHandle] === null) return;
this[kPort].postMessage(payload, transferList);
}
terminate(callback) {
if (this[kHandle] === null) return;
debug(`[${threadId}] terminates Worker with ID ${this.threadId}`);
if (typeof callback !== 'undefined')
this.once('exit', (exitCode) => callback(null, exitCode));
this[kHandle].stopThread();
}
ref() {
if (this[kPort] === null) return;
this[kPort].ref();
}
unref() {
if (this[kPort] === null) return;
this[kPort].unref();
}
get threadId() {
if (this[kHandle] === null) return -1;
return this[kHandle].threadId;
}
}
function setupChild(evalScript) {
// Called during bootstrap to set up worker script execution.
debug(`[${threadId}] is setting up worker child environment`);
const port = getEnvMessagePort();
const publicWorker = require('worker');
assert.strictEqual(typeof publicWorker.on, 'function');
publicWorker.postMessage = (payload, transferList) => {
port.postMessage(payload, transferList);
};
port.on('message', (payload) => publicWorker.emit('workerMessage', payload));
port.on('flaggedMessage', (flag, payload) => {
if (flag === kLoadScript) {
const [ filename, doEval, workerData ] = payload;
debug(`[${threadId}] starts worker script ${filename} ` +
`(eval = ${!!doEval}) at cwd = ${process.cwd()}`);
publicWorker.workerData = workerData;
setupPortReferencing(port, publicWorker, 'workerMessage');
port.postMessage(null, undefined, kUpAndRunning);
if (doEval) {
evalScript('[worker eval]', filename);
} else {
process.argv[1] = filename; // script filename
require('module').runMain();
}
return;
}
assert.fail(`Unknown worker message flag ${flag}`);
});
port.start();
}
module.exports = {
MessagePort,
MessageChannel,
threadId,
Worker,
setupChild
};