Commit | Line | Data |
---|---|---|
fc3e6586 | 1 | import { AsyncResource } from 'node:async_hooks' |
6677a3d3 | 2 | import type { Worker } from 'node:cluster' |
fc3e6586 | 3 | import type { MessagePort } from 'node:worker_threads' |
d715b7bc JB |
4 | import { performance } from 'node:perf_hooks' |
5 | import type { | |
6 | MessageValue, | |
5c4d16da | 7 | Task, |
d715b7bc JB |
8 | TaskPerformance, |
9 | WorkerStatistics | |
10 | } from '../utility-types' | |
ff128cc9 JB |
11 | import { |
12 | DEFAULT_TASK_NAME, | |
13 | EMPTY_FUNCTION, | |
14 | isAsyncFunction, | |
15 | isPlainObject | |
16 | } from '../utils' | |
241f23c2 JB |
17 | import { |
18 | type KillBehavior, | |
19 | KillBehaviors, | |
20 | type WorkerOptions | |
21 | } from './worker-options' | |
b6b32453 JB |
22 | import type { |
23 | TaskFunctions, | |
24 | WorkerAsyncFunction, | |
25 | WorkerFunction, | |
26 | WorkerSyncFunction | |
27 | } from './worker-functions' | |
4c35177b | 28 | |
978aad6f | 29 | const DEFAULT_MAX_INACTIVE_TIME = 60000 |
1a81f8af | 30 | const DEFAULT_KILL_BEHAVIOR: KillBehavior = KillBehaviors.SOFT |
c97c7edb | 31 | |
729c563d | 32 | /** |
ea7a90d3 | 33 | * Base class that implements some shared logic for all poolifier workers. |
729c563d | 34 | * |
38e795c1 | 35 | * @typeParam MainWorker - Type of main worker. |
e102732c JB |
36 | * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data. |
37 | * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data. | |
729c563d | 38 | */ |
c97c7edb | 39 | export abstract class AbstractWorker< |
6677a3d3 | 40 | MainWorker extends Worker | MessagePort, |
d3c8a1a8 S |
41 | Data = unknown, |
42 | Response = unknown | |
c97c7edb | 43 | > extends AsyncResource { |
f59e1027 | 44 | /** |
83fa0a36 | 45 | * Worker id. |
f59e1027 JB |
46 | */ |
47 | protected abstract id: number | |
a86b6df1 JB |
48 | /** |
49 | * Task function(s) processed by the worker when the pool's `execution` function is invoked. | |
50 | */ | |
51 | protected taskFunctions!: Map<string, WorkerFunction<Data, Response>> | |
729c563d S |
52 | /** |
53 | * Timestamp of the last task processed by this worker. | |
54 | */ | |
a9d9ea34 | 55 | protected lastTaskTimestamp!: number |
b6b32453 | 56 | /** |
8a970421 | 57 | * Performance statistics computation requirements. |
b6b32453 JB |
58 | */ |
59 | protected statistics!: WorkerStatistics | |
729c563d | 60 | /** |
aee46736 | 61 | * Handler id of the `aliveInterval` worker alive check. |
729c563d | 62 | */ |
75d3401a | 63 | protected aliveInterval?: NodeJS.Timeout |
c97c7edb | 64 | /** |
729c563d | 65 | * Constructs a new poolifier worker. |
c97c7edb | 66 | * |
38e795c1 JB |
67 | * @param type - The type of async event. |
68 | * @param isMain - Whether this is the main worker or not. | |
82888165 | 69 | * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. The first function is the default function. |
38e795c1 JB |
70 | * @param mainWorker - Reference to main worker. |
71 | * @param opts - Options for the worker. | |
c97c7edb S |
72 | */ |
73 | public constructor ( | |
74 | type: string, | |
c2ade475 | 75 | protected readonly isMain: boolean, |
a86b6df1 JB |
76 | taskFunctions: |
77 | | WorkerFunction<Data, Response> | |
78 | | TaskFunctions<Data, Response>, | |
448ad581 | 79 | protected readonly mainWorker: MainWorker, |
d99ba5a8 | 80 | protected readonly opts: WorkerOptions = { |
e088a00c | 81 | /** |
aee46736 | 82 | * The kill behavior option on this worker or its default value. |
e088a00c | 83 | */ |
1a81f8af | 84 | killBehavior: DEFAULT_KILL_BEHAVIOR, |
e088a00c JB |
85 | /** |
86 | * The maximum time to keep this worker alive while idle. | |
87 | * The pool automatically checks and terminates this worker when the time expires. | |
88 | */ | |
1a81f8af | 89 | maxInactiveTime: DEFAULT_MAX_INACTIVE_TIME |
4c35177b | 90 | } |
c97c7edb S |
91 | ) { |
92 | super(type) | |
e088a00c | 93 | this.checkWorkerOptions(this.opts) |
a86b6df1 | 94 | this.checkTaskFunctions(taskFunctions) |
1f68cede | 95 | if (!this.isMain) { |
3749facb | 96 | this.mainWorker?.on('message', this.messageListener.bind(this)) |
c97c7edb S |
97 | } |
98 | } | |
99 | ||
41aa7dcd JB |
100 | private checkWorkerOptions (opts: WorkerOptions): void { |
101 | this.opts.killBehavior = opts.killBehavior ?? DEFAULT_KILL_BEHAVIOR | |
102 | this.opts.maxInactiveTime = | |
103 | opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME | |
571227f4 | 104 | delete this.opts.async |
41aa7dcd JB |
105 | } |
106 | ||
107 | /** | |
a86b6df1 | 108 | * Checks if the `taskFunctions` parameter is passed to the constructor. |
41aa7dcd | 109 | * |
82888165 | 110 | * @param taskFunctions - The task function(s) parameter that should be checked. |
41aa7dcd | 111 | */ |
a86b6df1 JB |
112 | private checkTaskFunctions ( |
113 | taskFunctions: | |
114 | | WorkerFunction<Data, Response> | |
115 | | TaskFunctions<Data, Response> | |
116 | ): void { | |
ec8fd331 JB |
117 | if (taskFunctions == null) { |
118 | throw new Error('taskFunctions parameter is mandatory') | |
119 | } | |
a86b6df1 | 120 | this.taskFunctions = new Map<string, WorkerFunction<Data, Response>>() |
0d80593b | 121 | if (typeof taskFunctions === 'function') { |
ff128cc9 | 122 | this.taskFunctions.set(DEFAULT_TASK_NAME, taskFunctions.bind(this)) |
0d80593b | 123 | } else if (isPlainObject(taskFunctions)) { |
82888165 | 124 | let firstEntry = true |
a86b6df1 | 125 | for (const [name, fn] of Object.entries(taskFunctions)) { |
42e2b8a6 JB |
126 | if (typeof name !== 'string') { |
127 | throw new TypeError( | |
128 | 'A taskFunctions parameter object key is not a string' | |
129 | ) | |
130 | } | |
a86b6df1 | 131 | if (typeof fn !== 'function') { |
0d80593b | 132 | throw new TypeError( |
a86b6df1 JB |
133 | 'A taskFunctions parameter object value is not a function' |
134 | ) | |
135 | } | |
136 | this.taskFunctions.set(name, fn.bind(this)) | |
82888165 | 137 | if (firstEntry) { |
ff128cc9 | 138 | this.taskFunctions.set(DEFAULT_TASK_NAME, fn.bind(this)) |
82888165 JB |
139 | firstEntry = false |
140 | } | |
a86b6df1 | 141 | } |
630f0acf JB |
142 | if (firstEntry) { |
143 | throw new Error('taskFunctions parameter object is empty') | |
144 | } | |
a86b6df1 | 145 | } else { |
f34fdabe JB |
146 | throw new TypeError( |
147 | 'taskFunctions parameter is not a function or a plain object' | |
148 | ) | |
41aa7dcd JB |
149 | } |
150 | } | |
151 | ||
968a2e8c JB |
152 | /** |
153 | * Checks if the worker has a task function with the given name. | |
154 | * | |
155 | * @param name - The name of the task function to check. | |
156 | * @returns Whether the worker has a task function with the given name or not. | |
13a332e6 | 157 | * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string. |
968a2e8c JB |
158 | */ |
159 | public hasTaskFunction (name: string): boolean { | |
160 | if (typeof name !== 'string') { | |
161 | throw new TypeError('name parameter is not a string') | |
162 | } | |
163 | return this.taskFunctions.has(name) | |
164 | } | |
165 | ||
166 | /** | |
167 | * Adds a task function to the worker. | |
168 | * If a task function with the same name already exists, it is replaced. | |
169 | * | |
170 | * @param name - The name of the task function to add. | |
171 | * @param fn - The task function to add. | |
172 | * @returns Whether the task function was added or not. | |
13a332e6 JB |
173 | * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string. |
174 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name. | |
175 | * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `fn` parameter is not a function. | |
968a2e8c JB |
176 | */ |
177 | public addTaskFunction ( | |
178 | name: string, | |
179 | fn: WorkerFunction<Data, Response> | |
180 | ): boolean { | |
181 | if (typeof name !== 'string') { | |
182 | throw new TypeError('name parameter is not a string') | |
183 | } | |
184 | if (name === DEFAULT_TASK_NAME) { | |
185 | throw new Error( | |
186 | 'Cannot add a task function with the default reserved name' | |
187 | ) | |
188 | } | |
189 | if (typeof fn !== 'function') { | |
190 | throw new TypeError('fn parameter is not a function') | |
191 | } | |
192 | try { | |
193 | if ( | |
194 | this.taskFunctions.get(name) === | |
195 | this.taskFunctions.get(DEFAULT_TASK_NAME) | |
196 | ) { | |
197 | this.taskFunctions.set(DEFAULT_TASK_NAME, fn.bind(this)) | |
198 | } | |
199 | this.taskFunctions.set(name, fn.bind(this)) | |
200 | return true | |
201 | } catch { | |
202 | return false | |
203 | } | |
204 | } | |
205 | ||
206 | /** | |
207 | * Removes a task function from the worker. | |
208 | * | |
209 | * @param name - The name of the task function to remove. | |
210 | * @returns Whether the task function existed and was removed or not. | |
13a332e6 JB |
211 | * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string. |
212 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name. | |
213 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the task function used as default task function. | |
968a2e8c JB |
214 | */ |
215 | public removeTaskFunction (name: string): boolean { | |
216 | if (typeof name !== 'string') { | |
217 | throw new TypeError('name parameter is not a string') | |
218 | } | |
219 | if (name === DEFAULT_TASK_NAME) { | |
220 | throw new Error( | |
221 | 'Cannot remove the task function with the default reserved name' | |
222 | ) | |
223 | } | |
224 | if ( | |
225 | this.taskFunctions.get(name) === this.taskFunctions.get(DEFAULT_TASK_NAME) | |
226 | ) { | |
227 | throw new Error( | |
228 | 'Cannot remove the task function used as the default task function' | |
229 | ) | |
230 | } | |
231 | return this.taskFunctions.delete(name) | |
232 | } | |
233 | ||
234 | /** | |
235 | * Sets the default task function to use when no task function name is specified. | |
236 | * | |
237 | * @param name - The name of the task function to use as default task function. | |
238 | * @returns Whether the default task function was set or not. | |
13a332e6 JB |
239 | * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string. |
240 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name. | |
241 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is a non-existing task function. | |
968a2e8c JB |
242 | */ |
243 | public setDefaultTaskFunction (name: string): boolean { | |
244 | if (typeof name !== 'string') { | |
245 | throw new TypeError('name parameter is not a string') | |
246 | } | |
247 | if (name === DEFAULT_TASK_NAME) { | |
248 | throw new Error( | |
249 | 'Cannot set the default task function reserved name as the default task function' | |
250 | ) | |
251 | } | |
252 | if (!this.taskFunctions.has(name)) { | |
253 | throw new Error( | |
254 | 'Cannot set the default task function to a non-existing task function' | |
255 | ) | |
256 | } | |
257 | try { | |
258 | this.taskFunctions.set( | |
259 | DEFAULT_TASK_NAME, | |
260 | this.taskFunctions.get(name)?.bind(this) as WorkerFunction< | |
261 | Data, | |
262 | Response | |
263 | > | |
264 | ) | |
265 | return true | |
266 | } catch { | |
267 | return false | |
268 | } | |
269 | } | |
270 | ||
aee46736 JB |
271 | /** |
272 | * Worker message listener. | |
273 | * | |
274 | * @param message - Message received. | |
aee46736 | 275 | */ |
6677a3d3 | 276 | protected messageListener (message: MessageValue<Data, Data>): void { |
826f42ee JB |
277 | if (message.workerId === this.id) { |
278 | if (message.ready != null) { | |
279 | // Startup message received | |
280 | this.workerReady() | |
281 | } else if (message.statistics != null) { | |
282 | // Statistics message received | |
283 | this.statistics = message.statistics | |
284 | } else if (message.checkAlive != null) { | |
285 | // Check alive message received | |
286 | message.checkAlive ? this.startCheckAlive() : this.stopCheckAlive() | |
287 | } else if (message.id != null && message.data != null) { | |
288 | // Task message received | |
5c4d16da | 289 | this.run(message) |
826f42ee JB |
290 | } else if (message.kill === true) { |
291 | // Kill message received | |
292 | this.stopCheckAlive() | |
293 | this.emitDestroy() | |
cf597bc5 | 294 | } |
cf597bc5 JB |
295 | } |
296 | } | |
297 | ||
2431bdb4 JB |
298 | /** |
299 | * Notifies the main worker that this worker is ready to process tasks. | |
300 | */ | |
301 | protected workerReady (): void { | |
302 | !this.isMain && this.sendToMainWorker({ ready: true, workerId: this.id }) | |
303 | } | |
304 | ||
48487131 JB |
305 | /** |
306 | * Starts the worker alive check interval. | |
307 | */ | |
75d3401a JB |
308 | private startCheckAlive (): void { |
309 | this.lastTaskTimestamp = performance.now() | |
310 | this.aliveInterval = setInterval( | |
311 | this.checkAlive.bind(this), | |
312 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2 | |
313 | ) | |
314 | this.checkAlive.bind(this)() | |
315 | } | |
316 | ||
48487131 JB |
317 | /** |
318 | * Stops the worker alive check interval. | |
319 | */ | |
320 | private stopCheckAlive (): void { | |
321 | this.aliveInterval != null && clearInterval(this.aliveInterval) | |
322 | } | |
323 | ||
324 | /** | |
325 | * Checks if the worker should be terminated, because its living too long. | |
326 | */ | |
327 | private checkAlive (): void { | |
328 | if ( | |
329 | performance.now() - this.lastTaskTimestamp > | |
330 | (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) | |
331 | ) { | |
21f710aa | 332 | this.sendToMainWorker({ kill: this.opts.killBehavior, workerId: this.id }) |
48487131 JB |
333 | } |
334 | } | |
335 | ||
729c563d S |
336 | /** |
337 | * Returns the main worker. | |
838898f1 S |
338 | * |
339 | * @returns Reference to the main worker. | |
729c563d | 340 | */ |
838898f1 | 341 | protected getMainWorker (): MainWorker { |
78cea37e | 342 | if (this.mainWorker == null) { |
e102732c | 343 | throw new Error('Main worker not set') |
838898f1 S |
344 | } |
345 | return this.mainWorker | |
346 | } | |
c97c7edb | 347 | |
729c563d | 348 | /** |
8accb8d5 | 349 | * Sends a message to the main worker. |
729c563d | 350 | * |
38e795c1 | 351 | * @param message - The response message. |
729c563d | 352 | */ |
82f36766 JB |
353 | protected abstract sendToMainWorker ( |
354 | message: MessageValue<Response, Data> | |
355 | ): void | |
c97c7edb | 356 | |
729c563d | 357 | /** |
8accb8d5 | 358 | * Handles an error and convert it to a string so it can be sent back to the main worker. |
729c563d | 359 | * |
38e795c1 | 360 | * @param e - The error raised by the worker. |
ab80dc46 | 361 | * @returns The error message. |
729c563d | 362 | */ |
c97c7edb | 363 | protected handleError (e: Error | string): string { |
985d0e79 | 364 | return e instanceof Error ? e.message : e |
c97c7edb S |
365 | } |
366 | ||
5c4d16da JB |
367 | /** |
368 | * Runs the given task. | |
369 | * | |
370 | * @param task - The task to execute. | |
371 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found. | |
372 | */ | |
373 | protected run (task: Task<Data>): void { | |
374 | const fn = this.getTaskFunction(task.name) | |
375 | if (isAsyncFunction(fn)) { | |
376 | this.runInAsyncScope(this.runAsync.bind(this), this, fn, task) | |
377 | } else { | |
378 | this.runInAsyncScope(this.runSync.bind(this), this, fn, task) | |
379 | } | |
380 | } | |
381 | ||
729c563d | 382 | /** |
4dd93fcf | 383 | * Runs the given task function synchronously. |
729c563d | 384 | * |
5c4d16da JB |
385 | * @param fn - Task function that will be executed. |
386 | * @param task - Input data for the task function. | |
729c563d | 387 | */ |
70a4f5ea | 388 | protected runSync ( |
48ef9107 | 389 | fn: WorkerSyncFunction<Data, Response>, |
5c4d16da | 390 | task: Task<Data> |
c97c7edb S |
391 | ): void { |
392 | try { | |
5c4d16da JB |
393 | let taskPerformance = this.beginTaskPerformance(task.name) |
394 | const res = fn(task.data) | |
d715b7bc | 395 | taskPerformance = this.endTaskPerformance(taskPerformance) |
3fafb1b2 JB |
396 | this.sendToMainWorker({ |
397 | data: res, | |
d715b7bc | 398 | taskPerformance, |
f59e1027 | 399 | workerId: this.id, |
5c4d16da | 400 | id: task.id |
3fafb1b2 | 401 | }) |
c97c7edb | 402 | } catch (e) { |
985d0e79 | 403 | const errorMessage = this.handleError(e as Error | string) |
91ee39ed | 404 | this.sendToMainWorker({ |
82f36766 | 405 | taskError: { |
5c4d16da | 406 | name: task.name ?? DEFAULT_TASK_NAME, |
985d0e79 | 407 | message: errorMessage, |
5c4d16da | 408 | data: task.data |
82f36766 | 409 | }, |
21f710aa | 410 | workerId: this.id, |
5c4d16da | 411 | id: task.id |
91ee39ed | 412 | }) |
6e9d10db | 413 | } finally { |
75d3401a JB |
414 | if (!this.isMain && this.aliveInterval != null) { |
415 | this.lastTaskTimestamp = performance.now() | |
416 | } | |
c97c7edb S |
417 | } |
418 | } | |
419 | ||
729c563d | 420 | /** |
4dd93fcf | 421 | * Runs the given task function asynchronously. |
729c563d | 422 | * |
5c4d16da JB |
423 | * @param fn - Task function that will be executed. |
424 | * @param task - Input data for the task function. | |
729c563d | 425 | */ |
c97c7edb | 426 | protected runAsync ( |
48ef9107 | 427 | fn: WorkerAsyncFunction<Data, Response>, |
5c4d16da | 428 | task: Task<Data> |
c97c7edb | 429 | ): void { |
5c4d16da JB |
430 | let taskPerformance = this.beginTaskPerformance(task.name) |
431 | fn(task.data) | |
c97c7edb | 432 | .then(res => { |
d715b7bc | 433 | taskPerformance = this.endTaskPerformance(taskPerformance) |
3fafb1b2 JB |
434 | this.sendToMainWorker({ |
435 | data: res, | |
d715b7bc | 436 | taskPerformance, |
f59e1027 | 437 | workerId: this.id, |
5c4d16da | 438 | id: task.id |
3fafb1b2 | 439 | }) |
c97c7edb S |
440 | return null |
441 | }) | |
442 | .catch(e => { | |
985d0e79 | 443 | const errorMessage = this.handleError(e as Error | string) |
91ee39ed | 444 | this.sendToMainWorker({ |
82f36766 | 445 | taskError: { |
5c4d16da | 446 | name: task.name ?? DEFAULT_TASK_NAME, |
985d0e79 | 447 | message: errorMessage, |
5c4d16da | 448 | data: task.data |
82f36766 | 449 | }, |
21f710aa | 450 | workerId: this.id, |
5c4d16da | 451 | id: task.id |
91ee39ed | 452 | }) |
6e9d10db JB |
453 | }) |
454 | .finally(() => { | |
75d3401a JB |
455 | if (!this.isMain && this.aliveInterval != null) { |
456 | this.lastTaskTimestamp = performance.now() | |
457 | } | |
c97c7edb | 458 | }) |
6e9d10db | 459 | .catch(EMPTY_FUNCTION) |
c97c7edb | 460 | } |
ec8fd331 | 461 | |
82888165 | 462 | /** |
5c4d16da | 463 | * Gets the task function with the given name. |
82888165 | 464 | * |
ff128cc9 | 465 | * @param name - Name of the task function that will be returned. |
5c4d16da JB |
466 | * @returns The task function. |
467 | * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found. | |
82888165 | 468 | */ |
ec8fd331 | 469 | private getTaskFunction (name?: string): WorkerFunction<Data, Response> { |
ff128cc9 | 470 | name = name ?? DEFAULT_TASK_NAME |
ec8fd331 JB |
471 | const fn = this.taskFunctions.get(name) |
472 | if (fn == null) { | |
ace229a1 | 473 | throw new Error(`Task function '${name}' not found`) |
ec8fd331 JB |
474 | } |
475 | return fn | |
476 | } | |
62c15a68 | 477 | |
197b4aa5 | 478 | private beginTaskPerformance (name?: string): TaskPerformance { |
8a970421 | 479 | this.checkStatistics() |
62c15a68 | 480 | return { |
ff128cc9 | 481 | name: name ?? DEFAULT_TASK_NAME, |
1c6fe997 | 482 | timestamp: performance.now(), |
b6b32453 | 483 | ...(this.statistics.elu && { elu: performance.eventLoopUtilization() }) |
62c15a68 JB |
484 | } |
485 | } | |
486 | ||
d9d31201 JB |
487 | private endTaskPerformance ( |
488 | taskPerformance: TaskPerformance | |
489 | ): TaskPerformance { | |
8a970421 | 490 | this.checkStatistics() |
62c15a68 JB |
491 | return { |
492 | ...taskPerformance, | |
b6b32453 JB |
493 | ...(this.statistics.runTime && { |
494 | runTime: performance.now() - taskPerformance.timestamp | |
495 | }), | |
496 | ...(this.statistics.elu && { | |
62c15a68 | 497 | elu: performance.eventLoopUtilization(taskPerformance.elu) |
b6b32453 | 498 | }) |
62c15a68 JB |
499 | } |
500 | } | |
8a970421 JB |
501 | |
502 | private checkStatistics (): void { | |
503 | if (this.statistics == null) { | |
504 | throw new Error('Performance statistics computation requirements not set') | |
505 | } | |
506 | } | |
c97c7edb | 507 | } |