1 import { AsyncResource
} from
'node:async_hooks'
2 import type { Worker
} from
'node:cluster'
3 import type { MessagePort
} from
'node:worker_threads'
4 import { performance
} from
'node:perf_hooks'
10 } from
'../utility-types'
17 import { KillBehaviors
, type WorkerOptions
} from
'./worker-options'
23 } from
'./task-functions'
25 const DEFAULT_MAX_INACTIVE_TIME
= 60000
26 const DEFAULT_WORKER_OPTIONS
: WorkerOptions
= {
28 * The kill behavior option on this worker or its default value.
30 killBehavior
: KillBehaviors
.SOFT
,
32 * The maximum time to keep this worker active while idle.
33 * The pool automatically checks and terminates this worker when the time expires.
35 maxInactiveTime
: DEFAULT_MAX_INACTIVE_TIME
,
37 * The function to call when the worker is killed.
39 killHandler
: EMPTY_FUNCTION
43 * Base class that implements some shared logic for all poolifier workers.
45 * @typeParam MainWorker - Type of main worker.
46 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
47 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data.
49 export abstract class AbstractWorker
<
50 MainWorker
extends Worker
| MessagePort
,
53 > extends AsyncResource
{
57 protected abstract id
: number
59 * Task function(s) processed by the worker when the pool's `execution` function is invoked.
61 protected taskFunctions
!: Map
<string, TaskFunction
<Data
, Response
>>
63 * Timestamp of the last task processed by this worker.
65 protected lastTaskTimestamp
!: number
67 * Performance statistics computation requirements.
69 protected statistics
!: WorkerStatistics
71 * Handler id of the `activeInterval` worker activity check.
73 protected activeInterval
?: NodeJS
.Timeout
75 * Constructs a new poolifier worker.
77 * @param type - The type of async event.
78 * @param isMain - Whether this is the main worker or not.
79 * @param mainWorker - Reference to main worker.
80 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. The first function is the default function.
81 * @param opts - Options for the worker.
85 protected readonly isMain
: boolean,
86 private readonly mainWorker
: MainWorker
,
87 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>,
88 protected opts
: WorkerOptions
= DEFAULT_WORKER_OPTIONS
91 if (this.isMain
== null) {
92 throw new Error('isMain parameter is mandatory')
94 this.checkTaskFunctions(taskFunctions
)
95 this.checkWorkerOptions(this.opts
)
97 this.getMainWorker().on('message', this.handleReadyMessage
.bind(this))
101 private checkWorkerOptions (opts
: WorkerOptions
): void {
102 if (opts
!= null && !isPlainObject(opts
)) {
103 throw new TypeError('opts worker options parameter is not a plain object')
106 opts
?.killBehavior
!= null &&
107 !Object.values(KillBehaviors
).includes(opts
.killBehavior
)
110 `killBehavior option '${opts.killBehavior}' is not valid`
114 opts
?.maxInactiveTime
!= null &&
115 !Number.isSafeInteger(opts
.maxInactiveTime
)
117 throw new TypeError('maxInactiveTime option is not an integer')
119 if (opts
?.maxInactiveTime
!= null && opts
.maxInactiveTime
< 5) {
121 'maxInactiveTime option is not a positive integer greater or equal than 5'
124 if (opts
?.killHandler
!= null && typeof opts
.killHandler
!== 'function') {
125 throw new TypeError('killHandler option is not a function')
127 if (opts
?.async != null) {
128 throw new Error('async option is deprecated')
130 this.opts
= { ...DEFAULT_WORKER_OPTIONS
, ...opts
}
133 private checkValidTaskFunction (
135 fn
: TaskFunction
<Data
, Response
>
137 if (typeof name
!== 'string') {
139 'A taskFunctions parameter object key is not a string'
142 if (typeof name
=== 'string' && name
.trim().length
=== 0) {
144 'A taskFunctions parameter object key is an empty string'
147 if (typeof fn
!== 'function') {
149 'A taskFunctions parameter object value is not a function'
155 * Checks if the `taskFunctions` parameter is passed to the constructor and valid.
157 * @param taskFunctions - The task function(s) parameter that should be checked.
159 private checkTaskFunctions (
160 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>
162 if (taskFunctions
== null) {
163 throw new Error('taskFunctions parameter is mandatory')
165 this.taskFunctions
= new Map
<string, TaskFunction
<Data
, Response
>>()
166 if (typeof taskFunctions
=== 'function') {
167 const boundFn
= taskFunctions
.bind(this)
168 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
169 this.taskFunctions
.set(
170 typeof taskFunctions
.name
=== 'string' &&
171 taskFunctions
.name
.trim().length
> 0
176 } else if (isPlainObject(taskFunctions
)) {
177 let firstEntry
= true
178 for (const [name
, fn
] of Object.entries(taskFunctions
)) {
179 this.checkValidTaskFunction(name
, fn
)
180 const boundFn
= fn
.bind(this)
182 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
185 this.taskFunctions
.set(name
, boundFn
)
188 throw new Error('taskFunctions parameter object is empty')
192 'taskFunctions parameter is not a function or a plain object'
198 * Checks if the worker has a task function with the given name.
200 * @param name - The name of the task function to check.
201 * @returns Whether the worker has a task function with the given name or not.
202 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
204 public hasTaskFunction (name
: string): boolean {
205 this.checkTaskFunctionName(name
)
206 return this.taskFunctions
.has(name
)
210 * Adds a task function to the worker.
211 * If a task function with the same name already exists, it is replaced.
213 * @param name - The name of the task function to add.
214 * @param fn - The task function to add.
215 * @returns Whether the task function was added or not.
216 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
217 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
218 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `fn` parameter is not a function.
220 public addTaskFunction (
222 fn
: TaskFunction
<Data
, Response
>
224 this.checkTaskFunctionName(name
)
225 if (name
=== DEFAULT_TASK_NAME
) {
227 'Cannot add a task function with the default reserved name'
230 if (typeof fn
!== 'function') {
231 throw new TypeError('fn parameter is not a function')
234 const boundFn
= fn
.bind(this)
236 this.taskFunctions
.get(name
) ===
237 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
239 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
241 this.taskFunctions
.set(name
, boundFn
)
242 this.sendTaskFunctionsListToMainWorker()
250 * Removes a task function from the worker.
252 * @param name - The name of the task function to remove.
253 * @returns Whether the task function existed and was removed or not.
254 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
255 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
256 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the task function used as default task function.
258 public removeTaskFunction (name
: string): boolean {
259 this.checkTaskFunctionName(name
)
260 if (name
=== DEFAULT_TASK_NAME
) {
262 'Cannot remove the task function with the default reserved name'
266 this.taskFunctions
.get(name
) === this.taskFunctions
.get(DEFAULT_TASK_NAME
)
269 'Cannot remove the task function used as the default task function'
272 const deleteStatus
= this.taskFunctions
.delete(name
)
273 this.sendTaskFunctionsListToMainWorker()
278 * Lists the names of the worker's task functions.
280 * @returns The names of the worker's task functions.
282 public listTaskFunctions (): string[] {
283 const names
: string[] = [...this.taskFunctions
.keys()]
284 let defaultTaskFunctionName
: string = DEFAULT_TASK_NAME
285 for (const [name
, fn
] of this.taskFunctions
) {
287 name
!== DEFAULT_TASK_NAME
&&
288 fn
=== this.taskFunctions
.get(DEFAULT_TASK_NAME
)
290 defaultTaskFunctionName
= name
295 names
[names
.indexOf(DEFAULT_TASK_NAME
)],
296 defaultTaskFunctionName
,
298 name
=> name
!== DEFAULT_TASK_NAME
&& name
!== defaultTaskFunctionName
304 * Sets the default task function to use in the worker.
306 * @param name - The name of the task function to use as default task function.
307 * @returns Whether the default task function was set or not.
308 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
309 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
310 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is a non-existing task function.
312 public setDefaultTaskFunction (name
: string): boolean {
313 this.checkTaskFunctionName(name
)
314 if (name
=== DEFAULT_TASK_NAME
) {
316 'Cannot set the default task function reserved name as the default task function'
319 if (!this.taskFunctions
.has(name
)) {
321 'Cannot set the default task function to a non-existing task function'
325 this.taskFunctions
.set(
327 this.taskFunctions
.get(name
) as TaskFunction
<Data
, Response
>
335 private checkTaskFunctionName (name
: string): void {
336 if (typeof name
!== 'string') {
337 throw new TypeError('name parameter is not a string')
339 if (typeof name
=== 'string' && name
.trim().length
=== 0) {
340 throw new TypeError('name parameter is an empty string')
345 * Handles the ready message sent by the main worker.
347 * @param message - The ready message.
349 protected abstract handleReadyMessage (message
: MessageValue
<Data
>): void
352 * Worker message listener.
354 * @param message - The received message.
356 protected messageListener (message
: MessageValue
<Data
>): void {
357 this.checkMessageWorkerId(message
)
358 if (message
.statistics
!= null) {
359 // Statistics message received
360 this.statistics
= message
.statistics
361 } else if (message
.checkActive
!= null) {
362 // Check active message received
363 message
.checkActive
? this.startCheckActive() : this.stopCheckActive()
364 } else if (message
.taskId
!= null && message
.data
!= null) {
365 // Task message received
367 } else if (message
.kill
=== true) {
368 // Kill message received
369 this.handleKillMessage(message
)
374 * Handles a kill message sent by the main worker.
376 * @param message - The kill message.
378 protected handleKillMessage (message
: MessageValue
<Data
>): void {
379 this.stopCheckActive()
380 if (isAsyncFunction(this.opts
.killHandler
)) {
381 (this.opts
.killHandler
?.() as Promise
<void>)
383 this.sendToMainWorker({ kill
: 'success', workerId
: this.id
})
387 this.sendToMainWorker({ kill
: 'failure', workerId
: this.id
})
392 .catch(EMPTY_FUNCTION
)
395 // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
396 this.opts
.killHandler
?.() as void
397 this.sendToMainWorker({ kill
: 'success', workerId
: this.id
})
399 this.sendToMainWorker({ kill
: 'failure', workerId
: this.id
})
407 * Check if the message worker id is set and matches the worker id.
409 * @param message - The message to check.
410 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the message worker id is not set or does not match the worker id.
412 private checkMessageWorkerId (message
: MessageValue
<Data
>): void {
413 if (message
.workerId
== null) {
414 throw new Error('Message worker id is not set')
415 } else if (message
.workerId
!= null && message
.workerId
!== this.id
) {
417 `Message worker id ${message.workerId} does not match the worker id ${this.id}`
423 * Starts the worker check active interval.
425 private startCheckActive (): void {
426 this.lastTaskTimestamp
= performance
.now()
427 this.activeInterval
= setInterval(
428 this.checkActive
.bind(this),
429 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
) / 2
434 * Stops the worker check active interval.
436 private stopCheckActive (): void {
437 if (this.activeInterval
!= null) {
438 clearInterval(this.activeInterval
)
439 delete this.activeInterval
444 * Checks if the worker should be terminated, because its living too long.
446 private checkActive (): void {
448 performance
.now() - this.lastTaskTimestamp
>
449 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
)
451 this.sendToMainWorker({ kill
: this.opts
.killBehavior
, workerId
: this.id
})
456 * Returns the main worker.
458 * @returns Reference to the main worker.
459 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set.
461 protected getMainWorker (): MainWorker
{
462 if (this.mainWorker
== null) {
463 throw new Error('Main worker not set')
465 return this.mainWorker
469 * Sends a message to main worker.
471 * @param message - The response message.
473 protected abstract sendToMainWorker (
474 message
: MessageValue
<Response
, Data
>
478 * Sends the list of task function names to the main worker.
480 protected sendTaskFunctionsListToMainWorker (): void {
481 this.sendToMainWorker({
482 taskFunctions
: this.listTaskFunctions(),
488 * Handles an error and convert it to a string so it can be sent back to the main worker.
490 * @param error - The error raised by the worker.
491 * @returns The error message.
493 protected handleError (error
: Error | string): string {
494 return error
instanceof Error ? error
.message
: error
498 * Runs the given task.
500 * @param task - The task to execute.
501 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found.
503 protected run (task
: Task
<Data
>): void {
504 const { name
, taskId
, data
} = task
505 const fn
= this.taskFunctions
.get(name
?? DEFAULT_TASK_NAME
)
507 this.sendToMainWorker({
509 name
: name
as string,
510 message
: `Task function '${name as string}' not found`,
518 if (isAsyncFunction(fn
)) {
519 this.runInAsyncScope(this.runAsync
.bind(this), this, fn
, task
)
521 this.runInAsyncScope(this.runSync
.bind(this), this, fn
, task
)
526 * Runs the given task function synchronously.
528 * @param fn - Task function that will be executed.
529 * @param task - Input data for the task function.
532 fn
: TaskSyncFunction
<Data
, Response
>,
535 const { name
, taskId
, data
} = task
537 let taskPerformance
= this.beginTaskPerformance(name
)
539 taskPerformance
= this.endTaskPerformance(taskPerformance
)
540 this.sendToMainWorker({
547 this.sendToMainWorker({
549 name
: name
as string,
550 message
: this.handleError(error
as Error | string),
557 this.updateLastTaskTimestamp()
562 * Runs the given task function asynchronously.
564 * @param fn - Task function that will be executed.
565 * @param task - Input data for the task function.
568 fn
: TaskAsyncFunction
<Data
, Response
>,
571 const { name
, taskId
, data
} = task
572 let taskPerformance
= this.beginTaskPerformance(name
)
575 taskPerformance
= this.endTaskPerformance(taskPerformance
)
576 this.sendToMainWorker({
585 this.sendToMainWorker({
587 name
: name
as string,
588 message
: this.handleError(error
as Error | string),
596 this.updateLastTaskTimestamp()
598 .catch(EMPTY_FUNCTION
)
601 private beginTaskPerformance (name
?: string): TaskPerformance
{
602 this.checkStatistics()
604 name
: name
?? DEFAULT_TASK_NAME
,
605 timestamp
: performance
.now(),
606 ...(this.statistics
.elu
&& { elu
: performance
.eventLoopUtilization() })
610 private endTaskPerformance (
611 taskPerformance
: TaskPerformance
613 this.checkStatistics()
616 ...(this.statistics
.runTime
&& {
617 runTime
: performance
.now() - taskPerformance
.timestamp
619 ...(this.statistics
.elu
&& {
620 elu
: performance
.eventLoopUtilization(taskPerformance
.elu
)
625 private checkStatistics (): void {
626 if (this.statistics
== null) {
627 throw new Error('Performance statistics computation requirements not set')
631 private updateLastTaskTimestamp (): void {
632 if (this.activeInterval
!= null) {
633 this.lastTaskTimestamp
= performance
.now()