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
81 * Constructs a new poolifier worker.
83 * @param isMain - Whether this is the main worker or not.
84 * @param mainWorker - Reference to main worker.
85 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. The first function is the default function.
86 * @param opts - Options for the worker.
89 protected readonly isMain
: boolean,
90 private readonly mainWorker
: MainWorker
,
91 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>,
92 protected opts
: WorkerOptions
= DEFAULT_WORKER_OPTIONS
94 if (this.isMain
== null) {
95 throw new Error('isMain parameter is mandatory')
97 this.checkTaskFunctions(taskFunctions
)
98 this.checkWorkerOptions(this.opts
)
100 // Should be once() but Node.js on windows has a bug that prevents it from working
101 this.getMainWorker().on('message', this.handleReadyMessage
.bind(this))
105 private checkWorkerOptions (opts
: WorkerOptions
): void {
106 checkValidWorkerOptions(opts
)
107 this.opts
= { ...DEFAULT_WORKER_OPTIONS
, ...opts
}
111 * Checks if the `taskFunctions` parameter is passed to the constructor and valid.
113 * @param taskFunctions - The task function(s) parameter that should be checked.
115 private checkTaskFunctions (
116 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>
118 if (taskFunctions
== null) {
119 throw new Error('taskFunctions parameter is mandatory')
121 this.taskFunctions
= new Map
<string, TaskFunction
<Data
, Response
>>()
122 if (typeof taskFunctions
=== 'function') {
123 const boundFn
= taskFunctions
.bind(this)
124 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
125 this.taskFunctions
.set(
126 typeof taskFunctions
.name
=== 'string' &&
127 taskFunctions
.name
.trim().length
> 0
132 } else if (isPlainObject(taskFunctions
)) {
133 let firstEntry
= true
134 for (const [name
, fn
] of Object.entries(taskFunctions
)) {
135 checkValidTaskFunctionEntry
<Data
, Response
>(name
, fn
)
136 const boundFn
= fn
.bind(this)
138 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
141 this.taskFunctions
.set(name
, boundFn
)
144 throw new Error('taskFunctions parameter object is empty')
148 'taskFunctions parameter is not a function or a plain object'
154 * Checks if the worker has a task function with the given name.
156 * @param name - The name of the task function to check.
157 * @returns Whether the worker has a task function with the given name or not.
159 public hasTaskFunction (name
: string): TaskFunctionOperationResult
{
161 checkTaskFunctionName(name
)
163 return { status: false, error
: error
as Error }
165 return { status: this.taskFunctions
.has(name
) }
169 * Adds a task function to the worker.
170 * If a task function with the same name already exists, it is replaced.
172 * @param name - The name of the task function to add.
173 * @param fn - The task function to add.
174 * @returns Whether the task function was added or not.
176 public addTaskFunction (
178 fn
: TaskFunction
<Data
, Response
>
179 ): TaskFunctionOperationResult
{
181 checkTaskFunctionName(name
)
182 if (name
=== DEFAULT_TASK_NAME
) {
184 'Cannot add a task function with the default reserved name'
187 if (typeof fn
!== 'function') {
188 throw new TypeError('fn parameter is not a function')
190 const boundFn
= fn
.bind(this)
192 this.taskFunctions
.get(name
) ===
193 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
195 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
197 this.taskFunctions
.set(name
, boundFn
)
198 this.sendTaskFunctionNamesToMainWorker()
199 return { status: true }
201 return { status: false, error
: error
as Error }
206 * Removes a task function from the worker.
208 * @param name - The name of the task function to remove.
209 * @returns Whether the task function existed and was removed or not.
211 public removeTaskFunction (name
: string): TaskFunctionOperationResult
{
213 checkTaskFunctionName(name
)
214 if (name
=== DEFAULT_TASK_NAME
) {
216 'Cannot remove the task function with the default reserved name'
220 this.taskFunctions
.get(name
) ===
221 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
224 'Cannot remove the task function used as the default task function'
227 const deleteStatus
= this.taskFunctions
.delete(name
)
228 this.sendTaskFunctionNamesToMainWorker()
229 return { status: deleteStatus
}
231 return { status: false, error
: error
as Error }
236 * Lists the names of the worker's task functions.
238 * @returns The names of the worker's task functions.
240 public listTaskFunctionNames (): string[] {
241 const names
: string[] = [...this.taskFunctions
.keys()]
242 let defaultTaskFunctionName
: string = DEFAULT_TASK_NAME
243 for (const [name
, fn
] of this.taskFunctions
) {
245 name
!== DEFAULT_TASK_NAME
&&
246 fn
=== this.taskFunctions
.get(DEFAULT_TASK_NAME
)
248 defaultTaskFunctionName
= name
253 names
[names
.indexOf(DEFAULT_TASK_NAME
)],
254 defaultTaskFunctionName
,
256 name
=> name
!== DEFAULT_TASK_NAME
&& name
!== defaultTaskFunctionName
262 * Sets the default task function to use in the worker.
264 * @param name - The name of the task function to use as default task function.
265 * @returns Whether the default task function was set or not.
267 public setDefaultTaskFunction (name
: string): TaskFunctionOperationResult
{
269 checkTaskFunctionName(name
)
270 if (name
=== DEFAULT_TASK_NAME
) {
272 'Cannot set the default task function reserved name as the default task function'
275 if (!this.taskFunctions
.has(name
)) {
277 'Cannot set the default task function to a non-existing task function'
280 this.taskFunctions
.set(
282 this.taskFunctions
.get(name
) as TaskFunction
<Data
, Response
>
284 this.sendTaskFunctionNamesToMainWorker()
285 return { status: true }
287 return { status: false, error
: error
as Error }
292 * Handles the ready message sent by the main worker.
294 * @param message - The ready message.
296 protected abstract handleReadyMessage (message
: MessageValue
<Data
>): void
299 * Worker message listener.
301 * @param message - The received message.
303 protected messageListener (message
: MessageValue
<Data
>): void {
304 this.checkMessageWorkerId(message
)
305 if (message
.statistics
!= null) {
306 // Statistics message received
307 this.statistics
= message
.statistics
308 } else if (message
.checkActive
!= null) {
309 // Check active message received
310 message
.checkActive
? this.startCheckActive() : this.stopCheckActive()
311 } else if (message
.taskFunctionOperation
!= null) {
312 // Task function operation message received
313 this.handleTaskFunctionOperationMessage(message
)
314 } else if (message
.taskId
!= null && message
.data
!= null) {
315 // Task message received
317 } else if (message
.kill
=== true) {
318 // Kill message received
319 this.handleKillMessage(message
)
323 protected handleTaskFunctionOperationMessage (
324 message
: MessageValue
<Data
>
326 const { taskFunctionOperation
, taskFunctionName
, taskFunction
} = message
327 let response
!: TaskFunctionOperationResult
328 switch (taskFunctionOperation
) {
330 response
= this.addTaskFunction(
331 taskFunctionName
as string,
332 // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func
333 new Function(`return ${taskFunction as string}`)() as TaskFunction
<
340 response
= this.removeTaskFunction(taskFunctionName
as string)
343 response
= this.setDefaultTaskFunction(taskFunctionName
as string)
346 response
= { status: false, error
: new Error('Unknown task operation') }
349 this.sendToMainWorker({
350 taskFunctionOperation
,
351 taskFunctionOperationStatus
: response
.status,
353 ...(!response
.status &&
354 response
?.error
!= null && {
356 name
: taskFunctionName
as string,
357 message
: this.handleError(response
.error
as Error | string)
364 * Handles a kill message sent by the main worker.
366 * @param message - The kill message.
368 protected handleKillMessage (_message
: MessageValue
<Data
>): void {
369 this.stopCheckActive()
370 if (isAsyncFunction(this.opts
.killHandler
)) {
371 (this.opts
.killHandler
?.() as Promise
<void>)
373 this.sendToMainWorker({ kill
: 'success' })
377 this.sendToMainWorker({ kill
: 'failure' })
381 // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
382 this.opts
.killHandler
?.() as void
383 this.sendToMainWorker({ kill
: 'success' })
385 this.sendToMainWorker({ kill
: 'failure' })
391 * Check if the message worker id is set and matches the worker id.
393 * @param message - The message to check.
394 * @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.
396 private checkMessageWorkerId (message
: MessageValue
<Data
>): void {
397 if (message
.workerId
== null) {
398 throw new Error('Message worker id is not set')
399 } else if (message
.workerId
!== this.id
) {
401 `Message worker id ${message.workerId} does not match the worker id ${this.id}`
407 * Starts the worker check active interval.
409 private startCheckActive (): void {
410 this.lastTaskTimestamp
= performance
.now()
411 this.activeInterval
= setInterval(
412 this.checkActive
.bind(this),
413 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
) / 2
418 * Stops the worker check active interval.
420 private stopCheckActive (): void {
421 if (this.activeInterval
!= null) {
422 clearInterval(this.activeInterval
)
423 delete this.activeInterval
428 * Checks if the worker should be terminated, because its living too long.
430 private checkActive (): void {
432 performance
.now() - this.lastTaskTimestamp
>
433 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
)
435 this.sendToMainWorker({ kill
: this.opts
.killBehavior
})
440 * Returns the main worker.
442 * @returns Reference to the main worker.
443 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set.
445 protected getMainWorker (): MainWorker
{
446 if (this.mainWorker
== null) {
447 throw new Error('Main worker not set')
449 return this.mainWorker
453 * Sends a message to main worker.
455 * @param message - The response message.
457 protected abstract sendToMainWorker (
458 message
: MessageValue
<Response
, Data
>
462 * Sends task function names to the main worker.
464 protected sendTaskFunctionNamesToMainWorker (): void {
465 this.sendToMainWorker({
466 taskFunctionNames
: this.listTaskFunctionNames()
471 * Handles an error and convert it to a string so it can be sent back to the main worker.
473 * @param error - The error raised by the worker.
474 * @returns The error message.
476 protected handleError (error
: Error | string): string {
477 return error
instanceof Error ? error
.message
: error
481 * Runs the given task.
483 * @param task - The task to execute.
485 protected readonly run
= (task
: Task
<Data
>): void => {
486 const { name
, taskId
, data
} = task
487 const taskFunctionName
= name
?? DEFAULT_TASK_NAME
488 if (!this.taskFunctions
.has(taskFunctionName
)) {
489 this.sendToMainWorker({
491 name
: name
as string,
492 message
: `Task function '${name as string}' not found`,
499 const fn
= this.taskFunctions
.get(taskFunctionName
)
500 if (isAsyncFunction(fn
)) {
501 this.runAsync(fn
as TaskAsyncFunction
<Data
, Response
>, task
)
503 this.runSync(fn
as TaskSyncFunction
<Data
, Response
>, task
)
508 * Runs the given task function synchronously.
510 * @param fn - Task function that will be executed.
511 * @param task - Input data for the task function.
513 protected readonly runSync
= (
514 fn
: TaskSyncFunction
<Data
, Response
>,
517 const { name
, taskId
, data
} = task
519 let taskPerformance
= this.beginTaskPerformance(name
)
521 taskPerformance
= this.endTaskPerformance(taskPerformance
)
522 this.sendToMainWorker({
528 this.sendToMainWorker({
530 name
: name
as string,
531 message
: this.handleError(error
as Error | string),
537 this.updateLastTaskTimestamp()
542 * Runs the given task function asynchronously.
544 * @param fn - Task function that will be executed.
545 * @param task - Input data for the task function.
547 protected readonly runAsync
= (
548 fn
: TaskAsyncFunction
<Data
, Response
>,
551 const { name
, taskId
, data
} = task
552 let taskPerformance
= this.beginTaskPerformance(name
)
555 taskPerformance
= this.endTaskPerformance(taskPerformance
)
556 this.sendToMainWorker({
564 this.sendToMainWorker({
566 name
: name
as string,
567 message
: this.handleError(error
as Error | string),
574 this.updateLastTaskTimestamp()
576 .catch(EMPTY_FUNCTION
)
579 private beginTaskPerformance (name
?: string): TaskPerformance
{
580 this.checkStatistics()
582 name
: name
?? DEFAULT_TASK_NAME
,
583 timestamp
: performance
.now(),
584 ...(this.statistics
.elu
&& { elu
: performance
.eventLoopUtilization() })
588 private endTaskPerformance (
589 taskPerformance
: TaskPerformance
591 this.checkStatistics()
594 ...(this.statistics
.runTime
&& {
595 runTime
: performance
.now() - taskPerformance
.timestamp
597 ...(this.statistics
.elu
&& {
598 elu
: performance
.eventLoopUtilization(taskPerformance
.elu
)
603 private checkStatistics (): void {
604 if (this.statistics
== null) {
605 throw new Error('Performance statistics computation requirements not set')
609 private updateLastTaskTimestamp (): void {
610 if (this.activeInterval
!= null) {
611 this.lastTaskTimestamp
= performance
.now()