1 import type { Worker
} from
'node:cluster'
2 import { performance
} from
'node:perf_hooks'
3 import type { MessagePort
} from
'node:worker_threads'
10 } from
'../utility-types.js'
20 TaskFunctionOperationResult
,
23 } from
'./task-functions.js'
25 checkTaskFunctionName
,
26 checkValidTaskFunctionEntry
,
27 checkValidWorkerOptions
29 import { KillBehaviors
, type WorkerOptions
} from
'./worker-options.js'
31 const DEFAULT_MAX_INACTIVE_TIME
= 60000
32 const DEFAULT_WORKER_OPTIONS
: WorkerOptions
= {
34 * The kill behavior option on this worker or its default value.
36 killBehavior
: KillBehaviors
.SOFT
,
38 * The maximum time to keep this worker active while idle.
39 * The pool automatically checks and terminates this worker when the time expires.
41 maxInactiveTime
: DEFAULT_MAX_INACTIVE_TIME
,
43 * The function to call when the worker is killed.
45 killHandler
: EMPTY_FUNCTION
49 * Base class that implements some shared logic for all poolifier workers.
51 * @typeParam MainWorker - Type of main worker.
52 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
53 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data.
55 export abstract class AbstractWorker
<
56 MainWorker
extends Worker
| MessagePort
,
63 protected abstract id
: number
65 * Task function(s) processed by the worker when the pool's `execution` function is invoked.
67 protected taskFunctions
!: Map
<string, TaskFunction
<Data
, Response
>>
69 * Timestamp of the last task processed by this worker.
71 protected lastTaskTimestamp
!: number
73 * Performance statistics computation requirements.
75 protected statistics
?: WorkerStatistics
77 * Handler id of the `activeInterval` worker activity check.
79 protected activeInterval
?: NodeJS
.Timeout
82 * Constructs a new poolifier worker.
84 * @param isMain - Whether this is the main worker or not.
85 * @param mainWorker - Reference to main worker.
86 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. The first function is the default function.
87 * @param opts - Options for the worker.
90 protected readonly isMain
: boolean | undefined,
91 private readonly mainWorker
: MainWorker
| undefined | null,
92 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>,
93 protected opts
: WorkerOptions
= DEFAULT_WORKER_OPTIONS
95 if (this.isMain
== null) {
96 throw new Error('isMain parameter is mandatory')
98 this.checkTaskFunctions(taskFunctions
)
99 this.checkWorkerOptions(this.opts
)
101 // Should be once() but Node.js on windows has a bug that prevents it from working
102 this.getMainWorker().on('message', this.handleReadyMessage
.bind(this))
106 private checkWorkerOptions (opts
: WorkerOptions
): void {
107 checkValidWorkerOptions(opts
)
108 this.opts
= { ...DEFAULT_WORKER_OPTIONS
, ...opts
}
112 * Checks if the `taskFunctions` parameter is passed to the constructor and valid.
114 * @param taskFunctions - The task function(s) parameter that should be checked.
116 private checkTaskFunctions (
118 | TaskFunction
<Data
, Response
>
119 | TaskFunctions
<Data
, Response
>
122 if (taskFunctions
== null) {
123 throw new Error('taskFunctions parameter is mandatory')
125 this.taskFunctions
= new Map
<string, TaskFunction
<Data
, Response
>>()
126 if (typeof taskFunctions
=== 'function') {
127 const boundFn
= taskFunctions
.bind(this)
128 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
129 this.taskFunctions
.set(
130 typeof taskFunctions
.name
=== 'string' &&
131 taskFunctions
.name
.trim().length
> 0
136 } else if (isPlainObject(taskFunctions
)) {
137 let firstEntry
= true
138 for (const [name
, fn
] of Object.entries(taskFunctions
)) {
139 checkValidTaskFunctionEntry
<Data
, Response
>(name
, fn
)
140 const boundFn
= fn
.bind(this)
142 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
145 this.taskFunctions
.set(name
, boundFn
)
148 throw new Error('taskFunctions parameter object is empty')
152 'taskFunctions parameter is not a function or a plain object'
158 * Checks if the worker has a task function with the given name.
160 * @param name - The name of the task function to check.
161 * @returns Whether the worker has a task function with the given name or not.
163 public hasTaskFunction (name
: string): TaskFunctionOperationResult
{
165 checkTaskFunctionName(name
)
167 return { status: false, error
: error
as Error }
169 return { status: this.taskFunctions
.has(name
) }
173 * Adds a task function to the worker.
174 * If a task function with the same name already exists, it is replaced.
176 * @param name - The name of the task function to add.
177 * @param fn - The task function to add.
178 * @returns Whether the task function was added or not.
180 public addTaskFunction (
182 fn
: TaskFunction
<Data
, Response
>
183 ): TaskFunctionOperationResult
{
185 checkTaskFunctionName(name
)
186 if (name
=== DEFAULT_TASK_NAME
) {
188 'Cannot add a task function with the default reserved name'
191 if (typeof fn
!== 'function') {
192 throw new TypeError('fn parameter is not a function')
194 const boundFn
= fn
.bind(this)
196 this.taskFunctions
.get(name
) ===
197 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
199 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
201 this.taskFunctions
.set(name
, boundFn
)
202 this.sendTaskFunctionNamesToMainWorker()
203 return { status: true }
205 return { status: false, error
: error
as Error }
210 * Removes a task function from the worker.
212 * @param name - The name of the task function to remove.
213 * @returns Whether the task function existed and was removed or not.
215 public removeTaskFunction (name
: string): TaskFunctionOperationResult
{
217 checkTaskFunctionName(name
)
218 if (name
=== DEFAULT_TASK_NAME
) {
220 'Cannot remove the task function with the default reserved name'
224 this.taskFunctions
.get(name
) ===
225 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
228 'Cannot remove the task function used as the default task function'
231 const deleteStatus
= this.taskFunctions
.delete(name
)
232 this.sendTaskFunctionNamesToMainWorker()
233 return { status: deleteStatus
}
235 return { status: false, error
: error
as Error }
240 * Lists the names of the worker's task functions.
242 * @returns The names of the worker's task functions.
244 public listTaskFunctionNames (): string[] {
245 const names
= [...this.taskFunctions
.keys()]
246 let defaultTaskFunctionName
= DEFAULT_TASK_NAME
247 for (const [name
, fn
] of this.taskFunctions
) {
249 name
!== DEFAULT_TASK_NAME
&&
250 fn
=== this.taskFunctions
.get(DEFAULT_TASK_NAME
)
252 defaultTaskFunctionName
= name
257 names
[names
.indexOf(DEFAULT_TASK_NAME
)],
258 defaultTaskFunctionName
,
260 name
=> name
!== DEFAULT_TASK_NAME
&& name
!== defaultTaskFunctionName
266 * Sets the default task function to use in the worker.
268 * @param name - The name of the task function to use as default task function.
269 * @returns Whether the default task function was set or not.
271 public setDefaultTaskFunction (name
: string): TaskFunctionOperationResult
{
273 checkTaskFunctionName(name
)
274 if (name
=== DEFAULT_TASK_NAME
) {
276 'Cannot set the default task function reserved name as the default task function'
279 if (!this.taskFunctions
.has(name
)) {
281 'Cannot set the default task function to a non-existing task function'
284 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
285 this.taskFunctions
.set(DEFAULT_TASK_NAME
, this.taskFunctions
.get(name
)!)
286 this.sendTaskFunctionNamesToMainWorker()
287 return { status: true }
289 return { status: false, error
: error
as Error }
294 * Handles the ready message sent by the main worker.
296 * @param message - The ready message.
298 protected abstract handleReadyMessage (message
: MessageValue
<Data
>): void
301 * Worker message listener.
303 * @param message - The received message.
305 protected messageListener (message
: MessageValue
<Data
>): void {
306 this.checkMessageWorkerId(message
)
307 if (message
.statistics
!= null) {
308 // Statistics message received
309 this.statistics
= message
.statistics
310 } else if (message
.checkActive
!= null) {
311 // Check active message received
312 message
.checkActive
? this.startCheckActive() : this.stopCheckActive()
313 } else if (message
.taskFunctionOperation
!= null) {
314 // Task function operation message received
315 this.handleTaskFunctionOperationMessage(message
)
316 } else if (message
.taskId
!= null && message
.data
!= null) {
317 // Task message received
319 } else if (message
.kill
=== true) {
320 // Kill message received
321 this.handleKillMessage(message
)
325 protected handleTaskFunctionOperationMessage (
326 message
: MessageValue
<Data
>
328 const { taskFunctionOperation
, taskFunctionName
, taskFunction
} = message
329 if (taskFunctionName
== null) {
331 'Cannot handle task function operation message without a task function name'
334 let response
: TaskFunctionOperationResult
335 switch (taskFunctionOperation
) {
337 response
= this.addTaskFunction(
339 // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func
340 new Function(`return ${taskFunction}`)() as TaskFunction
<
347 response
= this.removeTaskFunction(taskFunctionName
)
350 response
= this.setDefaultTaskFunction(taskFunctionName
)
353 response
= { status: false, error
: new Error('Unknown task operation') }
356 this.sendToMainWorker({
357 taskFunctionOperation
,
358 taskFunctionOperationStatus
: response
.status,
360 ...(!response
.status &&
361 response
.error
!= null && {
363 name
: taskFunctionName
,
364 message
: this.handleError(response
.error
as Error | string)
371 * Handles a kill message sent by the main worker.
373 * @param message - The kill message.
375 protected handleKillMessage (_message
: MessageValue
<Data
>): void {
376 this.stopCheckActive()
377 if (isAsyncFunction(this.opts
.killHandler
)) {
378 (this.opts
.killHandler() as Promise
<void>)
380 this.sendToMainWorker({ kill
: 'success' })
384 this.sendToMainWorker({ kill
: 'failure' })
388 // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
389 this.opts
.killHandler
?.() as void
390 this.sendToMainWorker({ kill
: 'success' })
392 this.sendToMainWorker({ kill
: 'failure' })
398 * Check if the message worker id is set and matches the worker id.
400 * @param message - The message to check.
401 * @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.
403 private checkMessageWorkerId (message
: MessageValue
<Data
>): void {
404 if (message
.workerId
== null) {
405 throw new Error('Message worker id is not set')
406 } else if (message
.workerId
!== this.id
) {
408 `Message worker id ${message.workerId} does not match the worker id ${this.id}`
414 * Starts the worker check active interval.
416 private startCheckActive (): void {
417 this.lastTaskTimestamp
= performance
.now()
418 this.activeInterval
= setInterval(
419 this.checkActive
.bind(this),
420 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
) / 2
425 * Stops the worker check active interval.
427 private stopCheckActive (): void {
428 if (this.activeInterval
!= null) {
429 clearInterval(this.activeInterval
)
430 delete this.activeInterval
435 * Checks if the worker should be terminated, because its living too long.
437 private checkActive (): void {
439 performance
.now() - this.lastTaskTimestamp
>
440 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
)
442 this.sendToMainWorker({ kill
: this.opts
.killBehavior
})
447 * Returns the main worker.
449 * @returns Reference to the main worker.
450 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set.
452 protected getMainWorker (): MainWorker
{
453 if (this.mainWorker
== null) {
454 throw new Error('Main worker not set')
456 return this.mainWorker
460 * Sends a message to main worker.
462 * @param message - The response message.
464 protected abstract sendToMainWorker (
465 message
: MessageValue
<Response
, Data
>
469 * Sends task function names to the main worker.
471 protected sendTaskFunctionNamesToMainWorker (): void {
472 this.sendToMainWorker({
473 taskFunctionNames
: this.listTaskFunctionNames()
478 * Handles an error and convert it to a string so it can be sent back to the main worker.
480 * @param error - The error raised by the worker.
481 * @returns The error message.
483 protected handleError (error
: Error | string): string {
484 return error
instanceof Error ? error
.message
: error
488 * Runs the given task.
490 * @param task - The task to execute.
492 protected readonly run
= (task
: Task
<Data
>): void => {
493 const { name
, taskId
, data
} = task
494 const taskFunctionName
= name
?? DEFAULT_TASK_NAME
495 if (!this.taskFunctions
.has(taskFunctionName
)) {
496 this.sendToMainWorker({
498 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
500 message
: `Task function '${name}' not found`,
507 const fn
= this.taskFunctions
.get(taskFunctionName
)
508 if (isAsyncFunction(fn
)) {
509 this.runAsync(fn
as TaskAsyncFunction
<Data
, Response
>, task
)
511 this.runSync(fn
as TaskSyncFunction
<Data
, Response
>, task
)
516 * Runs the given task function synchronously.
518 * @param fn - Task function that will be executed.
519 * @param task - Input data for the task function.
521 protected readonly runSync
= (
522 fn
: TaskSyncFunction
<Data
, Response
>,
525 const { name
, taskId
, data
} = task
527 let taskPerformance
= this.beginTaskPerformance(name
)
529 taskPerformance
= this.endTaskPerformance(taskPerformance
)
530 this.sendToMainWorker({
536 this.sendToMainWorker({
538 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
540 message
: this.handleError(error
as Error | string),
546 this.updateLastTaskTimestamp()
551 * Runs the given task function asynchronously.
553 * @param fn - Task function that will be executed.
554 * @param task - Input data for the task function.
556 protected readonly runAsync
= (
557 fn
: TaskAsyncFunction
<Data
, Response
>,
560 const { name
, taskId
, data
} = task
561 let taskPerformance
= this.beginTaskPerformance(name
)
564 taskPerformance
= this.endTaskPerformance(taskPerformance
)
565 this.sendToMainWorker({
573 this.sendToMainWorker({
575 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
577 message
: this.handleError(error
as Error | string),
584 this.updateLastTaskTimestamp()
586 .catch(EMPTY_FUNCTION
)
589 private beginTaskPerformance (name
?: string): TaskPerformance
{
590 if (this.statistics
== null) {
591 throw new Error('Performance statistics computation requirements not set')
594 name
: name
?? DEFAULT_TASK_NAME
,
595 timestamp
: performance
.now(),
596 ...(this.statistics
.elu
&& {
597 elu
: performance
.eventLoopUtilization()
602 private endTaskPerformance (
603 taskPerformance
: TaskPerformance
605 if (this.statistics
== null) {
606 throw new Error('Performance statistics computation requirements not set')
610 ...(this.statistics
.runTime
&& {
611 runTime
: performance
.now() - taskPerformance
.timestamp
613 ...(this.statistics
.elu
&& {
614 elu
: performance
.eventLoopUtilization(taskPerformance
.elu
)
619 private updateLastTaskTimestamp (): void {
620 if (this.activeInterval
!= null) {
621 this.lastTaskTimestamp
= performance
.now()