1 import type { Worker
} from
'node:cluster'
2 import { performance
} from
'node:perf_hooks'
3 import type { MessagePort
} from
'node:worker_threads'
8 TaskFunctionProperties
,
11 } from
'../utility-types.js'
13 buildTaskFunctionProperties
,
23 TaskFunctionOperationResult
,
26 } from
'./task-functions.js'
28 checkTaskFunctionName
,
29 checkValidTaskFunctionObjectEntry
,
30 checkValidWorkerOptions
32 import { KillBehaviors
, type WorkerOptions
} from
'./worker-options.js'
34 const DEFAULT_MAX_INACTIVE_TIME
= 60000
35 const DEFAULT_WORKER_OPTIONS
: WorkerOptions
= {
37 * The kill behavior option on this worker or its default value.
39 killBehavior
: KillBehaviors
.SOFT
,
41 * The maximum time to keep this worker active while idle.
42 * The pool automatically checks and terminates this worker when the time expires.
44 maxInactiveTime
: DEFAULT_MAX_INACTIVE_TIME
,
46 * The function to call when the worker is killed.
48 killHandler
: EMPTY_FUNCTION
52 * Base class that implements some shared logic for all poolifier workers.
54 * @typeParam MainWorker - Type of main worker.
55 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
56 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data.
58 export abstract class AbstractWorker
<
59 MainWorker
extends Worker
| MessagePort
,
66 protected abstract id
: number
68 * Task function object(s) processed by the worker when the pool's `execution` function is invoked.
70 protected taskFunctions
!: Map
<string, TaskFunctionObject
<Data
, Response
>>
72 * Timestamp of the last task processed by this worker.
74 protected lastTaskTimestamp
!: number
76 * Performance statistics computation requirements.
78 protected statistics
?: WorkerStatistics
80 * Handler id of the `activeInterval` worker activity check.
82 protected activeInterval
?: NodeJS
.Timeout
85 * Constructs a new poolifier worker.
87 * @param isMain - Whether this is the main worker or not.
88 * @param mainWorker - Reference to main worker.
89 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. The first function is the default function.
90 * @param opts - Options for the worker.
93 protected readonly isMain
: boolean | undefined,
94 private readonly mainWorker
: MainWorker
| undefined | null,
95 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>,
96 protected opts
: WorkerOptions
= DEFAULT_WORKER_OPTIONS
98 if (this.isMain
== null) {
99 throw new Error('isMain parameter is mandatory')
101 this.checkTaskFunctions(taskFunctions
)
102 this.checkWorkerOptions(this.opts
)
104 // Should be once() but Node.js on windows has a bug that prevents it from working
105 this.getMainWorker().on('message', this.handleReadyMessage
.bind(this))
109 private checkWorkerOptions (opts
: WorkerOptions
): void {
110 checkValidWorkerOptions(opts
)
111 this.opts
= { ...DEFAULT_WORKER_OPTIONS
, ...opts
}
115 * Checks if the `taskFunctions` parameter is passed to the constructor and valid.
117 * @param taskFunctions - The task function(s) parameter that should be checked.
119 private checkTaskFunctions (
121 | TaskFunction
<Data
, Response
>
122 | TaskFunctions
<Data
, Response
>
125 if (taskFunctions
== null) {
126 throw new Error('taskFunctions parameter is mandatory')
128 this.taskFunctions
= new Map
<string, TaskFunctionObject
<Data
, Response
>>()
129 if (typeof taskFunctions
=== 'function') {
130 const fnObj
= { taskFunction
: taskFunctions
.bind(this) }
131 this.taskFunctions
.set(DEFAULT_TASK_NAME
, fnObj
)
132 this.taskFunctions
.set(
133 typeof taskFunctions
.name
=== 'string' &&
134 taskFunctions
.name
.trim().length
> 0
139 } else if (isPlainObject(taskFunctions
)) {
140 let firstEntry
= true
141 for (let [name
, fnObj
] of Object.entries(taskFunctions
)) {
142 if (typeof fnObj
=== 'function') {
143 fnObj
= { taskFunction
: fnObj
} satisfies TaskFunctionObject
<
148 checkValidTaskFunctionObjectEntry
<Data
, Response
>(name
, fnObj
)
149 fnObj
.taskFunction
= fnObj
.taskFunction
.bind(this)
151 this.taskFunctions
.set(DEFAULT_TASK_NAME
, fnObj
)
154 this.taskFunctions
.set(name
, fnObj
)
157 throw new Error('taskFunctions parameter object is empty')
161 'taskFunctions parameter is not a function or a plain object'
167 * Checks if the worker has a task function with the given name.
169 * @param name - The name of the task function to check.
170 * @returns Whether the worker has a task function with the given name or not.
172 public hasTaskFunction (name
: string): TaskFunctionOperationResult
{
174 checkTaskFunctionName(name
)
176 return { status: false, error
: error
as Error }
178 return { status: this.taskFunctions
.has(name
) }
182 * Adds a task function to the worker.
183 * If a task function with the same name already exists, it is replaced.
185 * @param name - The name of the task function to add.
186 * @param fn - The task function to add.
187 * @returns Whether the task function was added or not.
189 public addTaskFunction (
191 fn
: TaskFunction
<Data
, Response
> | TaskFunctionObject
<Data
, Response
>
192 ): TaskFunctionOperationResult
{
194 checkTaskFunctionName(name
)
195 if (name
=== DEFAULT_TASK_NAME
) {
197 'Cannot add a task function with the default reserved name'
200 if (typeof fn
=== 'function') {
201 fn
= { taskFunction
: fn
} satisfies TaskFunctionObject
<Data
, Response
>
203 checkValidTaskFunctionObjectEntry
<Data
, Response
>(name
, fn
)
204 fn
.taskFunction
= fn
.taskFunction
.bind(this)
206 this.taskFunctions
.get(name
) ===
207 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
209 this.taskFunctions
.set(DEFAULT_TASK_NAME
, fn
)
211 this.taskFunctions
.set(name
, fn
)
212 this.sendTaskFunctionsPropertiesToMainWorker()
213 return { status: true }
215 return { status: false, error
: error
as Error }
220 * Removes a task function from the worker.
222 * @param name - The name of the task function to remove.
223 * @returns Whether the task function existed and was removed or not.
225 public removeTaskFunction (name
: string): TaskFunctionOperationResult
{
227 checkTaskFunctionName(name
)
228 if (name
=== DEFAULT_TASK_NAME
) {
230 'Cannot remove the task function with the default reserved name'
234 this.taskFunctions
.get(name
) ===
235 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
238 'Cannot remove the task function used as the default task function'
241 const deleteStatus
= this.taskFunctions
.delete(name
)
242 this.sendTaskFunctionsPropertiesToMainWorker()
243 return { status: deleteStatus
}
245 return { status: false, error
: error
as Error }
250 * Lists the properties of the worker's task functions.
252 * @returns The properties of the worker's task functions.
254 public listTaskFunctionsProperties (): TaskFunctionProperties
[] {
255 let defaultTaskFunctionName
= DEFAULT_TASK_NAME
256 for (const [name
, fnObj
] of this.taskFunctions
) {
258 name
!== DEFAULT_TASK_NAME
&&
259 fnObj
=== this.taskFunctions
.get(DEFAULT_TASK_NAME
)
261 defaultTaskFunctionName
= name
265 const taskFunctionsProperties
: TaskFunctionProperties
[] = []
266 for (const [name
, fnObj
] of this.taskFunctions
) {
267 if (name
=== DEFAULT_TASK_NAME
|| name
=== defaultTaskFunctionName
) {
270 taskFunctionsProperties
.push(buildTaskFunctionProperties(name
, fnObj
))
273 buildTaskFunctionProperties(
275 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
277 buildTaskFunctionProperties(
278 defaultTaskFunctionName
,
279 this.taskFunctions
.get(defaultTaskFunctionName
)
281 ...taskFunctionsProperties
286 * Sets the default task function to use in the worker.
288 * @param name - The name of the task function to use as default task function.
289 * @returns Whether the default task function was set or not.
291 public setDefaultTaskFunction (name
: string): TaskFunctionOperationResult
{
293 checkTaskFunctionName(name
)
294 if (name
=== DEFAULT_TASK_NAME
) {
296 'Cannot set the default task function reserved name as the default task function'
299 if (!this.taskFunctions
.has(name
)) {
301 'Cannot set the default task function to a non-existing task function'
304 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
305 this.taskFunctions
.set(DEFAULT_TASK_NAME
, this.taskFunctions
.get(name
)!)
306 this.sendTaskFunctionsPropertiesToMainWorker()
307 return { status: true }
309 return { status: false, error
: error
as Error }
314 * Handles the ready message sent by the main worker.
316 * @param message - The ready message.
318 protected abstract handleReadyMessage (message
: MessageValue
<Data
>): void
321 * Worker message listener.
323 * @param message - The received message.
325 protected messageListener (message
: MessageValue
<Data
>): void {
326 this.checkMessageWorkerId(message
)
330 taskFunctionOperation
,
335 if (statistics
!= null) {
336 // Statistics message received
337 this.statistics
= statistics
338 } else if (checkActive
!= null) {
339 // Check active message received
340 checkActive
? this.startCheckActive() : this.stopCheckActive()
341 } else if (taskFunctionOperation
!= null) {
342 // Task function operation message received
343 this.handleTaskFunctionOperationMessage(message
)
344 } else if (taskId
!= null && data
!= null) {
345 // Task message received
347 } else if (kill
=== true) {
348 // Kill message received
349 this.handleKillMessage(message
)
353 protected handleTaskFunctionOperationMessage (
354 message
: MessageValue
<Data
>
356 const { taskFunctionOperation
, taskFunctionProperties
, taskFunction
} =
358 if (taskFunctionProperties
== null) {
360 'Cannot handle task function operation message without task function properties'
363 let response
: TaskFunctionOperationResult
364 switch (taskFunctionOperation
) {
366 response
= this.addTaskFunction(taskFunctionProperties
.name
, {
367 // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func
368 taskFunction
: new Function(
369 `return ${taskFunction}`
370 )() as TaskFunction
<Data
, Response
>,
371 ...(taskFunctionProperties
.priority
!= null && {
372 priority
: taskFunctionProperties
.priority
374 ...(taskFunctionProperties
.strategy
!= null && {
375 strategy
: taskFunctionProperties
.strategy
380 response
= this.removeTaskFunction(taskFunctionProperties
.name
)
383 response
= this.setDefaultTaskFunction(taskFunctionProperties
.name
)
386 response
= { status: false, error
: new Error('Unknown task operation') }
389 this.sendToMainWorker({
390 taskFunctionOperation
,
391 taskFunctionOperationStatus
: response
.status,
392 taskFunctionProperties
,
393 ...(!response
.status &&
394 response
.error
!= null && {
396 name
: taskFunctionProperties
.name
,
397 message
: this.handleError(response
.error
as Error | string)
404 * Handles a kill message sent by the main worker.
406 * @param message - The kill message.
408 protected handleKillMessage (_message
: MessageValue
<Data
>): void {
409 this.stopCheckActive()
410 if (isAsyncFunction(this.opts
.killHandler
)) {
411 (this.opts
.killHandler() as Promise
<void>)
413 this.sendToMainWorker({ kill
: 'success' })
417 this.sendToMainWorker({ kill
: 'failure' })
421 // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
422 this.opts
.killHandler
?.() as void
423 this.sendToMainWorker({ kill
: 'success' })
425 this.sendToMainWorker({ kill
: 'failure' })
431 * Check if the message worker id is set and matches the worker id.
433 * @param message - The message to check.
434 * @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.
436 private checkMessageWorkerId (message
: MessageValue
<Data
>): void {
437 if (message
.workerId
== null) {
438 throw new Error('Message worker id is not set')
439 } else if (message
.workerId
!== this.id
) {
441 `Message worker id ${message.workerId} does not match the worker id ${this.id}`
447 * Starts the worker check active interval.
449 private startCheckActive (): void {
450 this.lastTaskTimestamp
= performance
.now()
451 this.activeInterval
= setInterval(
452 this.checkActive
.bind(this),
453 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
) / 2
458 * Stops the worker check active interval.
460 private stopCheckActive (): void {
461 if (this.activeInterval
!= null) {
462 clearInterval(this.activeInterval
)
463 delete this.activeInterval
468 * Checks if the worker should be terminated, because its living too long.
470 private checkActive (): void {
472 performance
.now() - this.lastTaskTimestamp
>
473 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
)
475 this.sendToMainWorker({ kill
: this.opts
.killBehavior
})
480 * Returns the main worker.
482 * @returns Reference to the main worker.
483 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set.
485 protected getMainWorker (): MainWorker
{
486 if (this.mainWorker
== null) {
487 throw new Error('Main worker not set')
489 return this.mainWorker
493 * Sends a message to main worker.
495 * @param message - The response message.
497 protected abstract sendToMainWorker (
498 message
: MessageValue
<Response
, Data
>
502 * Sends task functions properties to the main worker.
504 protected sendTaskFunctionsPropertiesToMainWorker (): void {
505 this.sendToMainWorker({
506 taskFunctionsProperties
: this.listTaskFunctionsProperties()
511 * Handles an error and convert it to a string so it can be sent back to the main worker.
513 * @param error - The error raised by the worker.
514 * @returns The error message.
516 protected handleError (error
: Error | string): string {
517 return error
instanceof Error ? error
.message
: error
521 * Runs the given task.
523 * @param task - The task to execute.
525 protected readonly run
= (task
: Task
<Data
>): void => {
526 const { name
, taskId
, data
} = task
527 const taskFunctionName
= name
?? DEFAULT_TASK_NAME
528 if (!this.taskFunctions
.has(taskFunctionName
)) {
529 this.sendToMainWorker({
531 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
533 message
: `Task function '${name}' not found`,
540 const fn
= this.taskFunctions
.get(taskFunctionName
)?.taskFunction
541 if (isAsyncFunction(fn
)) {
542 this.runAsync(fn
as TaskAsyncFunction
<Data
, Response
>, task
)
544 this.runSync(fn
as TaskSyncFunction
<Data
, Response
>, task
)
549 * Runs the given task function synchronously.
551 * @param fn - Task function that will be executed.
552 * @param task - Input data for the task function.
554 protected readonly runSync
= (
555 fn
: TaskSyncFunction
<Data
, Response
>,
558 const { name
, taskId
, data
} = task
560 let taskPerformance
= this.beginTaskPerformance(name
)
562 taskPerformance
= this.endTaskPerformance(taskPerformance
)
563 this.sendToMainWorker({
569 this.sendToMainWorker({
571 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
573 message
: this.handleError(error
as Error | string),
579 this.updateLastTaskTimestamp()
584 * Runs the given task function asynchronously.
586 * @param fn - Task function that will be executed.
587 * @param task - Input data for the task function.
589 protected readonly runAsync
= (
590 fn
: TaskAsyncFunction
<Data
, Response
>,
593 const { name
, taskId
, data
} = task
594 let taskPerformance
= this.beginTaskPerformance(name
)
597 taskPerformance
= this.endTaskPerformance(taskPerformance
)
598 this.sendToMainWorker({
605 .catch((error
: unknown
) => {
606 this.sendToMainWorker({
608 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
610 message
: this.handleError(error
as Error | string),
617 this.updateLastTaskTimestamp()
619 .catch(EMPTY_FUNCTION
)
622 private beginTaskPerformance (name
?: string): TaskPerformance
{
623 if (this.statistics
== null) {
624 throw new Error('Performance statistics computation requirements not set')
627 name
: name
?? DEFAULT_TASK_NAME
,
628 timestamp
: performance
.now(),
629 ...(this.statistics
.elu
&& {
630 elu
: performance
.eventLoopUtilization()
635 private endTaskPerformance (
636 taskPerformance
: TaskPerformance
638 if (this.statistics
== null) {
639 throw new Error('Performance statistics computation requirements not set')
643 ...(this.statistics
.runTime
&& {
644 runTime
: performance
.now() - taskPerformance
.timestamp
646 ...(this.statistics
.elu
&& {
647 elu
: performance
.eventLoopUtilization(taskPerformance
.elu
)
652 private updateLastTaskTimestamp (): void {
653 if (this.activeInterval
!= null) {
654 this.lastTaskTimestamp
= performance
.now()