1 import type { Worker
} from
'node:cluster'
2 import type { MessagePort
} from
'node:worker_threads'
3 import { performance
} from
'node:perf_hooks'
9 } from
'../utility-types'
16 import { KillBehaviors
, type WorkerOptions
} from
'./worker-options'
20 TaskFunctionOperationResult
,
23 } from
'./task-functions'
25 checkTaskFunctionName
,
26 checkValidTaskFunctionEntry
,
27 checkValidWorkerOptions
30 const DEFAULT_MAX_INACTIVE_TIME
= 60000
31 const DEFAULT_WORKER_OPTIONS
: WorkerOptions
= {
33 * The kill behavior option on this worker or its default value.
35 killBehavior
: KillBehaviors
.SOFT
,
37 * The maximum time to keep this worker active while idle.
38 * The pool automatically checks and terminates this worker when the time expires.
40 maxInactiveTime
: DEFAULT_MAX_INACTIVE_TIME
,
42 * The function to call when the worker is killed.
44 killHandler
: EMPTY_FUNCTION
48 * Base class that implements some shared logic for all poolifier workers.
50 * @typeParam MainWorker - Type of main worker.
51 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
52 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data.
54 export abstract class AbstractWorker
<
55 MainWorker
extends Worker
| MessagePort
,
62 protected abstract id
: number
64 * Task function(s) processed by the worker when the pool's `execution` function is invoked.
66 protected taskFunctions
!: Map
<string, TaskFunction
<Data
, Response
>>
68 * Timestamp of the last task processed by this worker.
70 protected lastTaskTimestamp
!: number
72 * Performance statistics computation requirements.
74 protected statistics
!: WorkerStatistics
76 * Handler id of the `activeInterval` worker activity check.
78 protected activeInterval
?: NodeJS
.Timeout
80 * Constructs a new poolifier worker.
82 * @param isMain - Whether this is the main worker or not.
83 * @param mainWorker - Reference to main worker.
84 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. The first function is the default function.
85 * @param opts - Options for the worker.
88 protected readonly isMain
: boolean,
89 private readonly mainWorker
: MainWorker
,
90 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>,
91 protected opts
: WorkerOptions
= DEFAULT_WORKER_OPTIONS
93 if (this.isMain
== null) {
94 throw new Error('isMain parameter is mandatory')
96 this.checkTaskFunctions(taskFunctions
)
97 this.checkWorkerOptions(this.opts
)
99 // Should be once() but Node.js on windows has a bug that prevents it from working
100 this.getMainWorker().on('message', this.handleReadyMessage
.bind(this))
104 private checkWorkerOptions (opts
: WorkerOptions
): void {
105 checkValidWorkerOptions(opts
)
106 this.opts
= { ...DEFAULT_WORKER_OPTIONS
, ...opts
}
110 * Checks if the `taskFunctions` parameter is passed to the constructor and valid.
112 * @param taskFunctions - The task function(s) parameter that should be checked.
114 private checkTaskFunctions (
115 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>
117 if (taskFunctions
== null) {
118 throw new Error('taskFunctions parameter is mandatory')
120 this.taskFunctions
= new Map
<string, TaskFunction
<Data
, Response
>>()
121 if (typeof taskFunctions
=== 'function') {
122 const boundFn
= taskFunctions
.bind(this)
123 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
124 this.taskFunctions
.set(
125 typeof taskFunctions
.name
=== 'string' &&
126 taskFunctions
.name
.trim().length
> 0
131 } else if (isPlainObject(taskFunctions
)) {
132 let firstEntry
= true
133 for (const [name
, fn
] of Object.entries(taskFunctions
)) {
134 checkValidTaskFunctionEntry
<Data
, Response
>(name
, fn
)
135 const boundFn
= fn
.bind(this)
137 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
140 this.taskFunctions
.set(name
, boundFn
)
143 throw new Error('taskFunctions parameter object is empty')
147 'taskFunctions parameter is not a function or a plain object'
153 * Checks if the worker has a task function with the given name.
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.
158 public hasTaskFunction (name
: string): TaskFunctionOperationResult
{
160 checkTaskFunctionName(name
)
162 return { status: false, error
: error
as Error }
164 return { status: this.taskFunctions
.has(name
) }
168 * Adds a task function to the worker.
169 * If a task function with the same name already exists, it is replaced.
171 * @param name - The name of the task function to add.
172 * @param fn - The task function to add.
173 * @returns Whether the task function was added or not.
175 public addTaskFunction (
177 fn
: TaskFunction
<Data
, Response
>
178 ): TaskFunctionOperationResult
{
180 checkTaskFunctionName(name
)
181 if (name
=== DEFAULT_TASK_NAME
) {
183 'Cannot add a task function with the default reserved name'
186 if (typeof fn
!== 'function') {
187 throw new TypeError('fn parameter is not a function')
189 const boundFn
= fn
.bind(this)
191 this.taskFunctions
.get(name
) ===
192 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
194 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
196 this.taskFunctions
.set(name
, boundFn
)
197 this.sendTaskFunctionNamesToMainWorker()
198 return { status: true }
200 return { status: false, error
: error
as Error }
205 * Removes a task function from the worker.
207 * @param name - The name of the task function to remove.
208 * @returns Whether the task function existed and was removed or not.
210 public removeTaskFunction (name
: string): TaskFunctionOperationResult
{
212 checkTaskFunctionName(name
)
213 if (name
=== DEFAULT_TASK_NAME
) {
215 'Cannot remove the task function with the default reserved name'
219 this.taskFunctions
.get(name
) ===
220 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
223 'Cannot remove the task function used as the default task function'
226 const deleteStatus
= this.taskFunctions
.delete(name
)
227 this.sendTaskFunctionNamesToMainWorker()
228 return { status: deleteStatus
}
230 return { status: false, error
: error
as Error }
235 * Lists the names of the worker's task functions.
237 * @returns The names of the worker's task functions.
239 public listTaskFunctionNames (): string[] {
240 const names
: string[] = [...this.taskFunctions
.keys()]
241 let defaultTaskFunctionName
: string = DEFAULT_TASK_NAME
242 for (const [name
, fn
] of this.taskFunctions
) {
244 name
!== DEFAULT_TASK_NAME
&&
245 fn
=== this.taskFunctions
.get(DEFAULT_TASK_NAME
)
247 defaultTaskFunctionName
= name
252 names
[names
.indexOf(DEFAULT_TASK_NAME
)],
253 defaultTaskFunctionName
,
255 name
=> name
!== DEFAULT_TASK_NAME
&& name
!== defaultTaskFunctionName
261 * Sets the default task function to use in the worker.
263 * @param name - The name of the task function to use as default task function.
264 * @returns Whether the default task function was set or not.
266 public setDefaultTaskFunction (name
: string): TaskFunctionOperationResult
{
268 checkTaskFunctionName(name
)
269 if (name
=== DEFAULT_TASK_NAME
) {
271 'Cannot set the default task function reserved name as the default task function'
274 if (!this.taskFunctions
.has(name
)) {
276 'Cannot set the default task function to a non-existing task function'
279 this.taskFunctions
.set(
281 this.taskFunctions
.get(name
) as TaskFunction
<Data
, Response
>
283 this.sendTaskFunctionNamesToMainWorker()
284 return { status: true }
286 return { status: false, error
: error
as Error }
291 * Handles the ready message sent by the main worker.
293 * @param message - The ready message.
295 protected abstract handleReadyMessage (message
: MessageValue
<Data
>): void
298 * Worker message listener.
300 * @param message - The received message.
302 protected messageListener (message
: MessageValue
<Data
>): void {
303 this.checkMessageWorkerId(message
)
304 if (message
.statistics
!= null) {
305 // Statistics message received
306 this.statistics
= message
.statistics
307 } else if (message
.checkActive
!= null) {
308 // Check active message received
309 message
.checkActive
? this.startCheckActive() : this.stopCheckActive()
310 } else if (message
.taskFunctionOperation
!= null) {
311 // Task function operation message received
312 this.handleTaskFunctionOperationMessage(message
)
313 } else if (message
.taskId
!= null && message
.data
!= null) {
314 // Task message received
316 } else if (message
.kill
=== true) {
317 // Kill message received
318 this.handleKillMessage(message
)
322 protected handleTaskFunctionOperationMessage (
323 message
: MessageValue
<Data
>
325 const { taskFunctionOperation
, taskFunctionName
, taskFunction
} = message
326 let response
!: TaskFunctionOperationResult
327 switch (taskFunctionOperation
) {
329 response
= this.addTaskFunction(
330 taskFunctionName
as string,
331 // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func
332 new Function(`return ${taskFunction as string}`)() as TaskFunction
<
339 response
= this.removeTaskFunction(taskFunctionName
as string)
342 response
= this.setDefaultTaskFunction(taskFunctionName
as string)
345 response
= { status: false, error
: new Error('Unknown task operation') }
348 this.sendToMainWorker({
349 taskFunctionOperation
,
350 taskFunctionOperationStatus
: response
.status,
352 ...(!response
.status &&
353 response
?.error
!= null && {
355 name
: taskFunctionName
as string,
356 message
: this.handleError(response
.error
as Error | string)
363 * Handles a kill message sent by the main worker.
365 * @param message - The kill message.
367 protected handleKillMessage (_message
: MessageValue
<Data
>): void {
368 this.stopCheckActive()
369 if (isAsyncFunction(this.opts
.killHandler
)) {
370 (this.opts
.killHandler
?.() as Promise
<void>)
372 this.sendToMainWorker({ kill
: 'success' })
376 this.sendToMainWorker({ kill
: 'failure' })
380 // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
381 this.opts
.killHandler
?.() as void
382 this.sendToMainWorker({ kill
: 'success' })
384 this.sendToMainWorker({ kill
: 'failure' })
390 * Check if the message worker id is set and matches the worker id.
392 * @param message - The message to check.
393 * @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.
395 private checkMessageWorkerId (message
: MessageValue
<Data
>): void {
396 if (message
.workerId
== null) {
397 throw new Error('Message worker id is not set')
398 } else if (message
.workerId
!== this.id
) {
400 `Message worker id ${message.workerId} does not match the worker id ${this.id}`
406 * Starts the worker check active interval.
408 private startCheckActive (): void {
409 this.lastTaskTimestamp
= performance
.now()
410 this.activeInterval
= setInterval(
411 this.checkActive
.bind(this),
412 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
) / 2
417 * Stops the worker check active interval.
419 private stopCheckActive (): void {
420 if (this.activeInterval
!= null) {
421 clearInterval(this.activeInterval
)
422 delete this.activeInterval
427 * Checks if the worker should be terminated, because its living too long.
429 private checkActive (): void {
431 performance
.now() - this.lastTaskTimestamp
>
432 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
)
434 this.sendToMainWorker({ kill
: this.opts
.killBehavior
})
439 * Returns the main worker.
441 * @returns Reference to the main worker.
442 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set.
444 protected getMainWorker (): MainWorker
{
445 if (this.mainWorker
== null) {
446 throw new Error('Main worker not set')
448 return this.mainWorker
452 * Sends a message to main worker.
454 * @param message - The response message.
456 protected abstract sendToMainWorker (
457 message
: MessageValue
<Response
, Data
>
461 * Sends task function names to the main worker.
463 protected sendTaskFunctionNamesToMainWorker (): void {
464 this.sendToMainWorker({
465 taskFunctionNames
: this.listTaskFunctionNames()
470 * Handles an error and convert it to a string so it can be sent back to the main worker.
472 * @param error - The error raised by the worker.
473 * @returns The error message.
475 protected handleError (error
: Error | string): string {
476 return error
instanceof Error ? error
.message
: error
480 * Runs the given task.
482 * @param task - The task to execute.
484 protected readonly run
= (task
: Task
<Data
>): void => {
485 const { name
, taskId
, data
} = task
486 const taskFunctionName
= name
?? DEFAULT_TASK_NAME
487 if (!this.taskFunctions
.has(taskFunctionName
)) {
488 this.sendToMainWorker({
490 name
: name
as string,
491 message
: `Task function '${name as string}' not found`,
498 const fn
= this.taskFunctions
.get(taskFunctionName
)
499 if (isAsyncFunction(fn
)) {
500 this.runAsync(fn
as TaskAsyncFunction
<Data
, Response
>, task
)
502 this.runSync(fn
as TaskSyncFunction
<Data
, Response
>, task
)
507 * Runs the given task function synchronously.
509 * @param fn - Task function that will be executed.
510 * @param task - Input data for the task function.
512 protected readonly runSync
= (
513 fn
: TaskSyncFunction
<Data
, Response
>,
516 const { name
, taskId
, data
} = task
518 let taskPerformance
= this.beginTaskPerformance(name
)
520 taskPerformance
= this.endTaskPerformance(taskPerformance
)
521 this.sendToMainWorker({
527 this.sendToMainWorker({
529 name
: name
as string,
530 message
: this.handleError(error
as Error | string),
536 this.updateLastTaskTimestamp()
541 * Runs the given task function asynchronously.
543 * @param fn - Task function that will be executed.
544 * @param task - Input data for the task function.
546 protected readonly runAsync
= (
547 fn
: TaskAsyncFunction
<Data
, Response
>,
550 const { name
, taskId
, data
} = task
551 let taskPerformance
= this.beginTaskPerformance(name
)
554 taskPerformance
= this.endTaskPerformance(taskPerformance
)
555 this.sendToMainWorker({
563 this.sendToMainWorker({
565 name
: name
as string,
566 message
: this.handleError(error
as Error | string),
573 this.updateLastTaskTimestamp()
575 .catch(EMPTY_FUNCTION
)
578 private beginTaskPerformance (name
?: string): TaskPerformance
{
579 this.checkStatistics()
581 name
: name
?? DEFAULT_TASK_NAME
,
582 timestamp
: performance
.now(),
583 ...(this.statistics
.elu
&& { elu
: performance
.eventLoopUtilization() })
587 private endTaskPerformance (
588 taskPerformance
: TaskPerformance
590 this.checkStatistics()
593 ...(this.statistics
.runTime
&& {
594 runTime
: performance
.now() - taskPerformance
.timestamp
596 ...(this.statistics
.elu
&& {
597 elu
: performance
.eventLoopUtilization(taskPerformance
.elu
)
602 private checkStatistics (): void {
603 if (this.statistics
== null) {
604 throw new Error('Performance statistics computation requirements not set')
608 private updateLastTaskTimestamp (): void {
609 if (this.activeInterval
!= null) {
610 this.lastTaskTimestamp
= performance
.now()