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.
53 * @typeParam MainWorker - Type of main worker.
54 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
55 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data.
57 export abstract class AbstractWorker
<
58 MainWorker
extends Worker
| MessagePort
,
65 protected abstract id
: number
67 * Task function object(s) processed by the worker when the pool's `execution` function is invoked.
69 protected taskFunctions
!: Map
<string, TaskFunctionObject
<Data
, Response
>>
71 * Timestamp of the last task processed by this worker.
73 protected lastTaskTimestamp
!: number
75 * Performance statistics computation requirements.
77 protected statistics
?: WorkerStatistics
79 * Handler id of the `activeInterval` worker activity check.
81 // eslint-disable-next-line no-undef
82 protected activeInterval
?: NodeJS
.Timeout
85 * Constructs a new poolifier worker.
86 * @param isMain - Whether this is the main worker or not.
87 * @param mainWorker - Reference to main worker.
88 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. The first function is the default function.
89 * @param opts - Options for the worker.
92 protected readonly isMain
: boolean | undefined,
93 private readonly mainWorker
: MainWorker
| undefined | null,
94 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>,
95 protected opts
: WorkerOptions
= DEFAULT_WORKER_OPTIONS
97 if (this.isMain
== null) {
98 throw new Error('isMain parameter is mandatory')
100 this.checkTaskFunctions(taskFunctions
)
101 this.checkWorkerOptions(this.opts
)
103 // Should be once() but Node.js on windows has a bug that prevents it from working
104 this.getMainWorker().on('message', this.handleReadyMessage
.bind(this))
108 private checkWorkerOptions (opts
: WorkerOptions
): void {
109 checkValidWorkerOptions(opts
)
110 this.opts
= { ...DEFAULT_WORKER_OPTIONS
, ...opts
}
114 * Checks if the `taskFunctions` parameter is passed to the constructor and valid.
115 * @param taskFunctions - The task function(s) parameter that should be checked.
117 private checkTaskFunctions (
119 | TaskFunction
<Data
, Response
>
120 | TaskFunctions
<Data
, Response
>
123 if (taskFunctions
== null) {
124 throw new Error('taskFunctions parameter is mandatory')
126 this.taskFunctions
= new Map
<string, TaskFunctionObject
<Data
, Response
>>()
127 if (typeof taskFunctions
=== 'function') {
128 const fnObj
= { taskFunction
: taskFunctions
.bind(this) }
129 this.taskFunctions
.set(DEFAULT_TASK_NAME
, fnObj
)
130 this.taskFunctions
.set(
131 typeof taskFunctions
.name
=== 'string' &&
132 taskFunctions
.name
.trim().length
> 0
137 } else if (isPlainObject(taskFunctions
)) {
138 let firstEntry
= true
139 for (let [name
, fnObj
] of Object.entries(taskFunctions
)) {
140 if (typeof fnObj
=== 'function') {
141 fnObj
= { taskFunction
: fnObj
} satisfies TaskFunctionObject
<
146 checkValidTaskFunctionObjectEntry
<Data
, Response
>(name
, fnObj
)
147 fnObj
.taskFunction
= fnObj
.taskFunction
.bind(this)
149 this.taskFunctions
.set(DEFAULT_TASK_NAME
, fnObj
)
152 this.taskFunctions
.set(name
, fnObj
)
155 throw new Error('taskFunctions parameter object is empty')
159 'taskFunctions parameter is not a function or a plain object'
165 * Checks if the worker has a task function with the given name.
166 * @param name - The name of the task function to check.
167 * @returns Whether the worker has a task function with the given name or not.
169 public hasTaskFunction (name
: string): TaskFunctionOperationResult
{
171 checkTaskFunctionName(name
)
173 return { status: false, error
: error
as Error }
175 return { status: this.taskFunctions
.has(name
) }
179 * Adds a task function to the worker.
180 * If a task function with the same name already exists, it is replaced.
181 * @param name - The name of the task function to add.
182 * @param fn - The task function to add.
183 * @returns Whether the task function was added or not.
185 public addTaskFunction (
187 fn
: TaskFunction
<Data
, Response
> | TaskFunctionObject
<Data
, Response
>
188 ): TaskFunctionOperationResult
{
190 checkTaskFunctionName(name
)
191 if (name
=== DEFAULT_TASK_NAME
) {
193 'Cannot add a task function with the default reserved name'
196 if (typeof fn
=== 'function') {
197 fn
= { taskFunction
: fn
} satisfies TaskFunctionObject
<Data
, Response
>
199 checkValidTaskFunctionObjectEntry
<Data
, Response
>(name
, fn
)
200 fn
.taskFunction
= fn
.taskFunction
.bind(this)
202 this.taskFunctions
.get(name
) ===
203 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
205 this.taskFunctions
.set(DEFAULT_TASK_NAME
, fn
)
207 this.taskFunctions
.set(name
, fn
)
208 this.sendTaskFunctionsPropertiesToMainWorker()
209 return { status: true }
211 return { status: false, error
: error
as Error }
216 * Removes a task function from the worker.
217 * @param name - The name of the task function to remove.
218 * @returns Whether the task function existed and was removed or not.
220 public removeTaskFunction (name
: string): TaskFunctionOperationResult
{
222 checkTaskFunctionName(name
)
223 if (name
=== DEFAULT_TASK_NAME
) {
225 'Cannot remove the task function with the default reserved name'
229 this.taskFunctions
.get(name
) ===
230 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
233 'Cannot remove the task function used as the default task function'
236 const deleteStatus
= this.taskFunctions
.delete(name
)
237 this.sendTaskFunctionsPropertiesToMainWorker()
238 return { status: deleteStatus
}
240 return { status: false, error
: error
as Error }
245 * Lists the properties of the worker's task functions.
246 * @returns The properties of the worker's task functions.
248 public listTaskFunctionsProperties (): TaskFunctionProperties
[] {
249 let defaultTaskFunctionName
= DEFAULT_TASK_NAME
250 for (const [name
, fnObj
] of this.taskFunctions
) {
252 name
!== DEFAULT_TASK_NAME
&&
253 fnObj
=== this.taskFunctions
.get(DEFAULT_TASK_NAME
)
255 defaultTaskFunctionName
= name
259 const taskFunctionsProperties
: TaskFunctionProperties
[] = []
260 for (const [name
, fnObj
] of this.taskFunctions
) {
261 if (name
=== DEFAULT_TASK_NAME
|| name
=== defaultTaskFunctionName
) {
264 taskFunctionsProperties
.push(buildTaskFunctionProperties(name
, fnObj
))
267 buildTaskFunctionProperties(
269 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
271 buildTaskFunctionProperties(
272 defaultTaskFunctionName
,
273 this.taskFunctions
.get(defaultTaskFunctionName
)
275 ...taskFunctionsProperties
,
280 * Sets the default task function to use in the worker.
281 * @param name - The name of the task function to use as default task function.
282 * @returns Whether the default task function was set or not.
284 public setDefaultTaskFunction (name
: string): TaskFunctionOperationResult
{
286 checkTaskFunctionName(name
)
287 if (name
=== DEFAULT_TASK_NAME
) {
289 'Cannot set the default task function reserved name as the default task function'
292 if (!this.taskFunctions
.has(name
)) {
294 'Cannot set the default task function to a non-existing task function'
297 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
298 this.taskFunctions
.set(DEFAULT_TASK_NAME
, this.taskFunctions
.get(name
)!)
299 this.sendTaskFunctionsPropertiesToMainWorker()
300 return { status: true }
302 return { status: false, error
: error
as Error }
307 * Handles the ready message sent by the main worker.
308 * @param message - The ready message.
310 protected abstract handleReadyMessage (message
: MessageValue
<Data
>): void
313 * Worker message listener.
314 * @param message - The received message.
316 protected messageListener (message
: MessageValue
<Data
>): void {
317 this.checkMessageWorkerId(message
)
321 taskFunctionOperation
,
326 if (statistics
!= null) {
327 // Statistics message received
328 this.statistics
= statistics
329 } else if (checkActive
!= null) {
330 // Check active message received
331 checkActive
? this.startCheckActive() : this.stopCheckActive()
332 } else if (taskFunctionOperation
!= null) {
333 // Task function operation message received
334 this.handleTaskFunctionOperationMessage(message
)
335 } else if (taskId
!= null && data
!= null) {
336 // Task message received
338 } else if (kill
=== true) {
339 // Kill message received
340 this.handleKillMessage(message
)
344 protected handleTaskFunctionOperationMessage (
345 message
: MessageValue
<Data
>
347 const { taskFunctionOperation
, taskFunctionProperties
, taskFunction
} =
349 if (taskFunctionProperties
== null) {
351 'Cannot handle task function operation message without task function properties'
354 let response
: TaskFunctionOperationResult
355 switch (taskFunctionOperation
) {
357 response
= this.addTaskFunction(taskFunctionProperties
.name
, {
358 // eslint-disable-next-line no-new-func
359 taskFunction
: new Function(
360 `return ${taskFunction}`
361 )() as TaskFunction
<Data
, Response
>,
362 ...(taskFunctionProperties
.priority
!= null && {
363 priority
: taskFunctionProperties
.priority
,
365 ...(taskFunctionProperties
.strategy
!= null && {
366 strategy
: taskFunctionProperties
.strategy
,
371 response
= this.removeTaskFunction(taskFunctionProperties
.name
)
374 response
= this.setDefaultTaskFunction(taskFunctionProperties
.name
)
377 response
= { status: false, error
: new Error('Unknown task operation') }
380 this.sendToMainWorker({
381 taskFunctionOperation
,
382 taskFunctionOperationStatus
: response
.status,
383 taskFunctionProperties
,
384 ...(!response
.status &&
385 response
.error
!= null && {
387 name
: taskFunctionProperties
.name
,
388 message
: this.handleError(response
.error
as Error | string),
395 * Handles a kill message sent by the main worker.
396 * @param message - The kill message.
398 protected handleKillMessage (message
: MessageValue
<Data
>): void {
399 this.stopCheckActive()
400 if (isAsyncFunction(this.opts
.killHandler
)) {
401 ;(this.opts
.killHandler() as Promise
<void>)
403 this.sendToMainWorker({ kill
: 'success' })
407 this.sendToMainWorker({ kill
: 'failure' })
411 this.opts
.killHandler
?.()
412 this.sendToMainWorker({ kill
: 'success' })
414 this.sendToMainWorker({ kill
: 'failure' })
420 * Check if the message worker id is set and matches the worker id.
421 * @param message - The message to check.
422 * @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.
424 private checkMessageWorkerId (message
: MessageValue
<Data
>): void {
425 if (message
.workerId
== null) {
426 throw new Error('Message worker id is not set')
427 } else if (message
.workerId
!== this.id
) {
429 `Message worker id ${message.workerId} does not match the worker id ${this.id}`
435 * Starts the worker check active interval.
437 private startCheckActive (): void {
438 this.lastTaskTimestamp
= performance
.now()
439 this.activeInterval
= setInterval(
440 this.checkActive
.bind(this),
441 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
) / 2
446 * Stops the worker check active interval.
448 private stopCheckActive (): void {
449 if (this.activeInterval
!= null) {
450 clearInterval(this.activeInterval
)
451 delete this.activeInterval
456 * Checks if the worker should be terminated, because its living too long.
458 private checkActive (): void {
460 performance
.now() - this.lastTaskTimestamp
>
461 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
)
463 this.sendToMainWorker({ kill
: this.opts
.killBehavior
})
468 * Returns the main worker.
469 * @returns Reference to the main worker.
470 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set.
472 protected getMainWorker (): MainWorker
{
473 if (this.mainWorker
== null) {
474 throw new Error('Main worker not set')
476 return this.mainWorker
480 * Sends a message to main worker.
481 * @param message - The response message.
483 protected abstract sendToMainWorker (
484 message
: MessageValue
<Response
, Data
>
488 * Sends task functions properties to the main worker.
490 protected sendTaskFunctionsPropertiesToMainWorker (): void {
491 this.sendToMainWorker({
492 taskFunctionsProperties
: this.listTaskFunctionsProperties(),
497 * Handles an error and convert it to a string so it can be sent back to the main worker.
498 * @param error - The error raised by the worker.
499 * @returns The error message.
501 protected handleError (error
: Error | string): string {
502 return error
instanceof Error ? error
.message
: error
506 * Runs the given task.
507 * @param task - The task to execute.
509 protected readonly run
= (task
: Task
<Data
>): void => {
510 const { name
, taskId
, data
} = task
511 const taskFunctionName
= name
?? DEFAULT_TASK_NAME
512 if (!this.taskFunctions
.has(taskFunctionName
)) {
513 this.sendToMainWorker({
515 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
517 message
: `Task function '${name}' not found`,
524 const fn
= this.taskFunctions
.get(taskFunctionName
)?.taskFunction
525 if (isAsyncFunction(fn
)) {
526 this.runAsync(fn
as TaskAsyncFunction
<Data
, Response
>, task
)
528 this.runSync(fn
as TaskSyncFunction
<Data
, Response
>, task
)
533 * Runs the given task function synchronously.
534 * @param fn - Task function that will be executed.
535 * @param task - Input data for the task function.
537 protected readonly runSync
= (
538 fn
: TaskSyncFunction
<Data
, Response
>,
541 const { name
, taskId
, data
} = task
543 let taskPerformance
= this.beginTaskPerformance(name
)
545 taskPerformance
= this.endTaskPerformance(taskPerformance
)
546 this.sendToMainWorker({
552 this.sendToMainWorker({
554 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
556 message
: this.handleError(error
as Error | string),
562 this.updateLastTaskTimestamp()
567 * Runs the given task function asynchronously.
568 * @param fn - Task function that will be executed.
569 * @param task - Input data for the task function.
571 protected readonly runAsync
= (
572 fn
: TaskAsyncFunction
<Data
, Response
>,
575 const { name
, taskId
, data
} = task
576 let taskPerformance
= this.beginTaskPerformance(name
)
579 taskPerformance
= this.endTaskPerformance(taskPerformance
)
580 this.sendToMainWorker({
587 .catch((error
: unknown
) => {
588 this.sendToMainWorker({
590 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
592 message
: this.handleError(error
as Error | string),
599 this.updateLastTaskTimestamp()
601 .catch(EMPTY_FUNCTION
)
604 private beginTaskPerformance (name
?: string): TaskPerformance
{
605 if (this.statistics
== null) {
606 throw new Error('Performance statistics computation requirements not set')
609 name
: name
?? DEFAULT_TASK_NAME
,
610 timestamp
: performance
.now(),
611 ...(this.statistics
.elu
&& {
612 elu
: performance
.eventLoopUtilization(),
617 private endTaskPerformance (
618 taskPerformance
: TaskPerformance
620 if (this.statistics
== null) {
621 throw new Error('Performance statistics computation requirements not set')
625 ...(this.statistics
.runTime
&& {
626 runTime
: performance
.now() - taskPerformance
.timestamp
,
628 ...(this.statistics
.elu
&& {
629 elu
: performance
.eventLoopUtilization(taskPerformance
.elu
),
634 private updateLastTaskTimestamp (): void {
635 if (this.activeInterval
!= null) {
636 this.lastTaskTimestamp
= performance
.now()