-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorkerPool.js
More file actions
291 lines (245 loc) · 7.66 KB
/
WorkerPool.js
File metadata and controls
291 lines (245 loc) · 7.66 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
const os = require("os");
const path = require("path");
const crypto = require("crypto");
const { Worker } = require("worker_threads");
// WorkerPool keeps CPU-heavy jobs off the main event loop.
class WorkerPool {
constructor(options = {}) {
const cpuCount = os.cpus().length;
// Reasonable defaults for local development and demos.
this.poolSize = options.poolSize || Math.max(1, Math.min(cpuCount - 1, 4));
this.maxQueueSize = options.maxQueueSize || 100;
this.jobTimeoutMs = options.jobTimeoutMs || 30000;
this.workerScriptPath =
options.workerScriptPath ||
path.join(__dirname, "..", "workers", "cpuWorker.js");
this.workers = [];
this.jobQueue = [];
this.jobs = new Map();
this.isShuttingDown = false;
// Pre-spawn workers so the first request does not pay startup cost.
for (let i = 0; i < this.poolSize; i += 1) {
this._spawnWorker();
}
}
_spawnWorker() {
// Each worker runs a separate JS file in parallel.
const worker = new Worker(this.workerScriptPath);
const workerState = {
worker,
isBusy: false,
currentJobId: null,
};
worker.on("message", (message) =>
this._handleWorkerMessage(workerState, message),
);
worker.on("error", (error) => this._handleWorkerError(workerState, error));
worker.on("exit", (code) => this._handleWorkerExit(workerState, code));
this.workers.push(workerState);
}
_handleWorkerMessage(workerState, message) {
const { type, jobId } = message;
const job = this.jobs.get(jobId);
if (!job) {
workerState.isBusy = false;
workerState.currentJobId = null;
this._dispatch();
return;
}
clearTimeout(job.timeoutHandle);
// Resolve or reject the promise based on worker result.
if (type === "job_completed") {
job.status = "completed";
job.finishedAt = new Date().toISOString();
job.output = message.output || {
result: message.result,
durationMs: message.durationMs,
iterations: message.iterations,
threadId: message.threadId,
};
job.resolve(job.output);
} else {
job.status = "failed";
job.finishedAt = new Date().toISOString();
job.error = message.message || "Worker failed to process the job.";
job.reject(new Error(job.error));
}
workerState.isBusy = false;
workerState.currentJobId = null;
this._dispatch();
}
_handleWorkerError(workerState, error) {
const { currentJobId } = workerState;
if (!currentJobId) {
return;
}
const job = this.jobs.get(currentJobId);
if (!job) {
return;
}
clearTimeout(job.timeoutHandle);
job.status = "failed";
job.finishedAt = new Date().toISOString();
job.error = `Worker thread crashed: ${error.message}`;
job.reject(new Error(job.error));
workerState.isBusy = false;
workerState.currentJobId = null;
}
_handleWorkerExit(workerState, code) {
const workerIndex = this.workers.indexOf(workerState);
if (workerIndex >= 0) {
this.workers.splice(workerIndex, 1);
}
if (workerState.currentJobId) {
const job = this.jobs.get(workerState.currentJobId);
if (job && job.status !== "completed" && job.status !== "failed") {
clearTimeout(job.timeoutHandle);
job.status = "failed";
job.finishedAt = new Date().toISOString();
job.error = `Worker exited unexpectedly with code ${code}.`;
job.reject(new Error(job.error));
}
}
if (!this.isShuttingDown) {
this._spawnWorker();
this._dispatch();
}
}
_getIdleWorker() {
return this.workers.find((workerState) => !workerState.isBusy);
}
_dispatch() {
if (this.isShuttingDown) {
return;
}
// Keep assigning queued jobs while idle workers exist.
while (this.jobQueue.length > 0) {
const idleWorker = this._getIdleWorker();
if (!idleWorker) {
return;
}
const nextJobId = this.jobQueue.shift();
const job = this.jobs.get(nextJobId);
if (!job || job.status !== "queued") {
continue;
}
job.status = "running";
job.startedAt = new Date().toISOString();
idleWorker.isBusy = true;
idleWorker.currentJobId = nextJobId;
job.timeoutHandle = setTimeout(() => {
const timeoutMessage = `Worker job timed out after ${this.jobTimeoutMs}ms.`;
job.status = "failed";
job.finishedAt = new Date().toISOString();
job.error = timeoutMessage;
job.reject(new Error(timeoutMessage));
idleWorker.worker.terminate();
}, this.jobTimeoutMs);
// Send job payload to worker thread.
idleWorker.worker.postMessage({
jobId: nextJobId,
type: job.type,
input: job.input,
});
}
}
submitJob(input, options = {}) {
if (this.isShuttingDown) {
throw new Error("Worker pool is shutting down.");
}
if (this.jobQueue.length >= this.maxQueueSize) {
throw new Error("Worker queue is full. Try again later.");
}
// Optional input validation lets each job type enforce its own rules.
const validatedInput = options.validateInput
? options.validateInput(input)
: input;
const jobId = crypto.randomUUID();
let resolveFn;
let rejectFn;
const completionPromise = new Promise((resolve, reject) => {
resolveFn = resolve;
rejectFn = reject;
});
this.jobs.set(jobId, {
jobId,
status: "queued",
createdAt: new Date().toISOString(),
startedAt: null,
finishedAt: null,
type: options.type || "generic",
input: validatedInput,
output: null,
error: null,
timeoutHandle: null,
resolve: resolveFn,
reject: rejectFn,
});
this.jobQueue.push(jobId);
this._dispatch();
return {
jobId,
completionPromise,
};
}
submitCpuJob(iterations) {
// Convenience API used by CPU benchmark/demo routes.
return this.submitJob(
{ iterations },
{
type: "cpu",
validateInput: (input) => {
const normalizedIterations = Number(input.iterations);
if (
!Number.isFinite(normalizedIterations) ||
normalizedIterations <= 0
) {
throw new Error("Iterations must be a positive number.");
}
return { iterations: normalizedIterations };
},
},
);
}
getJob(jobId) {
const job = this.jobs.get(jobId);
if (!job) {
return null;
}
return {
jobId: job.jobId,
status: job.status,
createdAt: job.createdAt,
startedAt: job.startedAt,
finishedAt: job.finishedAt,
input: job.input,
output: job.output,
error: job.error,
};
}
getStats() {
// Snapshot-style metrics useful for dashboards and debugging.
const values = Array.from(this.jobs.values());
return {
poolSize: this.poolSize,
workerCount: this.workers.length,
activeWorkers: this.workers.filter((w) => w.isBusy).length,
queuedJobs: this.jobQueue.length,
maxQueueSize: this.maxQueueSize,
totalJobs: values.length,
completedJobs: values.filter((job) => job.status === "completed").length,
failedJobs: values.filter((job) => job.status === "failed").length,
runningJobs: values.filter((job) => job.status === "running").length,
queuedJobCount: values.filter((job) => job.status === "queued").length,
};
}
async shutdown() {
// Prevent new jobs, then terminate all worker threads.
this.isShuttingDown = true;
for (const workerState of this.workers) {
await workerState.worker.terminate();
}
this.workers = [];
}
}
module.exports = WorkerPool;