-
-
Notifications
You must be signed in to change notification settings - Fork 67
/
WorkerPool.js
251 lines (233 loc) · 6.99 KB
/
WorkerPool.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/* eslint-disable no-console */
import childProcess from 'child_process';
import asyncQueue from 'async/queue';
import asyncMapSeries from 'async/mapSeries';
import readBuffer from './readBuffer';
const workerPath = require.resolve('./worker');
let workerId = 0;
class PoolWorker {
constructor(options, onJobDone) {
this.nextJobId = 0;
this.jobs = Object.create(null);
this.activeJobs = 0;
this.onJobDone = onJobDone;
this.id = workerId;
workerId += 1;
this.worker = childProcess.spawn(process.execPath, [].concat(options.nodeArgs || []).concat(workerPath, options.parallelJobs), {
stdio: ['ignore', 1, 2, 'pipe', 'pipe'],
});
const [, , , readPipe, writePipe] = this.worker.stdio;
this.readPipe = readPipe;
this.writePipe = writePipe;
this.readNextMessage();
}
run(data, callback) {
const jobId = this.nextJobId;
this.nextJobId += 1;
this.jobs[jobId] = { data, callback };
this.activeJobs += 1;
this.writeJson({
type: 'job',
id: jobId,
data,
});
}
writeJson(data) {
const lengthBuffer = new Buffer(4);
const messageBuffer = new Buffer(JSON.stringify(data), 'utf-8');
lengthBuffer.writeInt32BE(messageBuffer.length, 0);
this.writePipe.write(lengthBuffer);
this.writePipe.write(messageBuffer);
}
writeEnd() {
const lengthBuffer = new Buffer(4);
lengthBuffer.writeInt32BE(0, 0);
this.writePipe.write(lengthBuffer);
}
readNextMessage() {
this.state = 'read length';
this.readBuffer(4, (lengthReadError, lengthBuffer) => {
if (lengthReadError) {
console.error(`Failed to communicate with worker (read length) ${lengthReadError}`);
return;
}
this.state = 'length read';
const length = lengthBuffer.readInt32BE(0);
this.state = 'read message';
this.readBuffer(length, (messageError, messageBuffer) => {
if (messageError) {
console.error(`Failed to communicate with worker (read message) ${messageError}`);
return;
}
this.state = 'message read';
const messageString = messageBuffer.toString('utf-8');
const message = JSON.parse(messageString);
this.state = 'process message';
this.onWorkerMessage(message, (err) => {
if (err) {
console.error(`Failed to communicate with worker (process message) ${err}`);
return;
}
this.state = 'soon next';
setImmediate(() => this.readNextMessage());
});
});
});
}
onWorkerMessage(message, finalCallback) {
const { type, id } = message;
switch (type) {
case 'job': {
const { data, error, result } = message;
asyncMapSeries(data, (length, callback) => this.readBuffer(length, callback), (eachErr, buffers) => {
const { callback: jobCallback } = this.jobs[id];
const callback = (err, arg) => {
if (jobCallback) {
delete this.jobs[id];
this.activeJobs -= 1;
this.onJobDone();
if (err) {
jobCallback(err instanceof Error ? err : new Error(err));
} else {
jobCallback(null, arg);
}
}
finalCallback();
};
if (eachErr) {
callback(eachErr);
return;
}
if (error) {
callback(this.fromErrorObj(error));
return;
}
let bufferPosition = 0;
result.result = result.result.map((r) => {
if (r.buffer) {
const buffer = buffers[bufferPosition];
bufferPosition += 1;
if (r.string) {
return buffer.toString('utf-8');
}
return buffer;
}
return r.data;
});
callback(null, result);
});
break;
}
case 'resolve': {
const { context, request, questionId } = message;
const { data } = this.jobs[id];
data.resolve(context, request, (error, result) => {
this.writeJson({
type: 'result',
id: questionId,
error,
result,
});
});
break;
}
case 'emitWarning': {
const { data } = message;
const { data: jobData } = this.jobs[id];
jobData.emitWarning(this.fromErrorObj(data));
finalCallback();
break;
}
case 'emitError': {
const { data } = message;
const { data: jobData } = this.jobs[id];
jobData.emitError(this.fromErrorObj(data));
finalCallback();
break;
}
default: {
console.error(`Unexpected worker message ${type} in WorkerPool.`);
finalCallback();
break;
}
}
}
fromErrorObj(arg) {
let obj;
if (typeof arg === 'string') {
obj = { message: arg };
} else {
obj = arg;
}
const err = new Error(obj.message);
err.message = obj.message;
if (obj.stack) {
err.stack = `${obj.stack}\n\tfrom thread-loader (worker ${this.id})\n${err.stack}`;
}
err.hideStack = obj.hideStack;
err.details = obj.details;
return err;
}
readBuffer(length, callback) {
readBuffer(this.readPipe, length, callback);
}
dispose() {
this.writeEnd();
}
}
export default class WorkerPool {
constructor(options) {
this.options = options || {};
this.numberOfWorkers = options.numberOfWorkers;
this.poolTimeout = options.poolTimeout;
this.workerNodeArgs = options.workerNodeArgs;
this.workerParallelJobs = options.workerParallelJobs;
this.workers = new Set();
this.activeJobs = 0;
this.timeout = null;
this.poolQueue = asyncQueue(this.distributeJob.bind(this), options.poolParallelJobs);
}
run(data, callback) {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
this.activeJobs += 1;
this.poolQueue.push(data, callback);
// this.distributeJob(data, callback);
}
distributeJob(data, callback) {
// use worker with the fewest jobs
let bestWorker;
for (const worker of this.workers) {
if (!bestWorker || worker.activeJobs < bestWorker.activeJobs) {
bestWorker = worker;
}
}
if (bestWorker && (bestWorker.activeJobs === 0 || this.workers.size >= this.numberOfWorkers)) {
bestWorker.run(data, callback);
return;
}
// spin up a new worker
const newWorker = new PoolWorker({
nodeArgs: this.workerNodeArgs,
parallelJobs: this.workerParallelJobs,
}, () => this.onJobDone());
this.workers.add(newWorker);
newWorker.run(data, callback);
}
onJobDone() {
this.activeJobs -= 1;
if (this.activeJobs === 0 && isFinite(this.poolTimeout)) {
this.timeout = setTimeout(() => this.disposeWorkers(), this.poolTimeout);
}
}
disposeWorkers() {
if (this.activeJobs === 0) {
for (const worker of this.workers) {
worker.dispose();
}
this.workers.clear();
}
}
}