1 import { AsyncResource
} from
'node:async_hooks'
2 import type { Worker
} from
'node:cluster'
3 import type { MessagePort
} from
'node:worker_threads'
4 import { performance
} from
'node:perf_hooks'
10 } from
'../utility-types'
17 import { KillBehaviors
, type WorkerOptions
} from
'./worker-options'
23 } from
'./task-functions'
25 const DEFAULT_MAX_INACTIVE_TIME
= 60000
26 const DEFAULT_WORKER_OPTIONS
: WorkerOptions
= {
28 * The kill behavior option on this worker or its default value.
30 killBehavior
: KillBehaviors
.SOFT
,
32 * The maximum time to keep this worker active while idle.
33 * The pool automatically checks and terminates this worker when the time expires.
35 maxInactiveTime
: DEFAULT_MAX_INACTIVE_TIME
,
37 * The function to call when the worker is killed.
39 killHandler
: EMPTY_FUNCTION
43 * Base class that implements some shared logic for all poolifier workers.
45 * @typeParam MainWorker - Type of main worker.
46 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
47 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data.
49 export abstract class AbstractWorker
<
50 MainWorker
extends Worker
| MessagePort
,
53 > extends AsyncResource
{
57 protected abstract id
: number
59 * Task function(s) processed by the worker when the pool's `execution` function is invoked.
61 protected taskFunctions
!: Map
<string, TaskFunction
<Data
, Response
>>
63 * Timestamp of the last task processed by this worker.
65 protected lastTaskTimestamp
!: number
67 * Performance statistics computation requirements.
69 protected statistics
!: WorkerStatistics
71 * Handler id of the `activeInterval` worker activity check.
73 protected activeInterval
?: NodeJS
.Timeout
75 * Constructs a new poolifier worker.
77 * @param type - The type of async event.
78 * @param isMain - Whether this is the main worker or not.
79 * @param mainWorker - Reference to main worker.
80 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. The first function is the default function.
81 * @param opts - Options for the worker.
85 protected readonly isMain
: boolean,
86 private readonly mainWorker
: MainWorker
,
87 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>,
88 protected opts
: WorkerOptions
= DEFAULT_WORKER_OPTIONS
91 if (this.isMain
== null) {
92 throw new Error('isMain parameter is mandatory')
94 this.checkTaskFunctions(taskFunctions
)
95 this.checkWorkerOptions(this.opts
)
97 this.getMainWorker().on('message', this.handleReadyMessage
.bind(this))
101 private checkWorkerOptions (opts
: WorkerOptions
): void {
102 this.opts
= { ...DEFAULT_WORKER_OPTIONS
, ...opts
}
103 delete this.opts
.async
107 * Checks if the `taskFunctions` parameter is passed to the constructor.
109 * @param taskFunctions - The task function(s) parameter that should be checked.
111 private checkTaskFunctions (
112 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>
114 if (taskFunctions
== null) {
115 throw new Error('taskFunctions parameter is mandatory')
117 this.taskFunctions
= new Map
<string, TaskFunction
<Data
, Response
>>()
118 if (typeof taskFunctions
=== 'function') {
119 const boundFn
= taskFunctions
.bind(this)
120 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
121 this.taskFunctions
.set(
122 typeof taskFunctions
.name
=== 'string' &&
123 taskFunctions
.name
.trim().length
> 0
128 } else if (isPlainObject(taskFunctions
)) {
129 let firstEntry
= true
130 for (const [name
, fn
] of Object.entries(taskFunctions
)) {
131 if (typeof name
!== 'string') {
133 'A taskFunctions parameter object key is not a string'
136 if (typeof name
=== 'string' && name
.trim().length
=== 0) {
138 'A taskFunctions parameter object key is an empty string'
141 if (typeof fn
!== 'function') {
143 'A taskFunctions parameter object value is not a function'
146 const boundFn
= fn
.bind(this)
148 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
151 this.taskFunctions
.set(name
, boundFn
)
154 throw new Error('taskFunctions parameter object is empty')
158 'taskFunctions parameter is not a function or a plain object'
164 * 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.
168 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
170 public hasTaskFunction (name
: string): boolean {
171 this.checkTaskFunctionName(name
)
172 return this.taskFunctions
.has(name
)
176 * Adds a task function to the worker.
177 * If a task function with the same name already exists, it is replaced.
179 * @param name - The name of the task function to add.
180 * @param fn - The task function to add.
181 * @returns Whether the task function was added or not.
182 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
183 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
184 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `fn` parameter is not a function.
186 public addTaskFunction (
188 fn
: TaskFunction
<Data
, Response
>
190 this.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 throw new TypeError('fn parameter is not a function')
200 const boundFn
= fn
.bind(this)
202 this.taskFunctions
.get(name
) ===
203 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
205 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
207 this.taskFunctions
.set(name
, boundFn
)
208 this.sendTaskFunctionsListToMainWorker()
216 * Removes a task function from the worker.
218 * @param name - The name of the task function to remove.
219 * @returns Whether the task function existed and was removed or not.
220 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
221 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
222 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the task function used as default task function.
224 public removeTaskFunction (name
: string): boolean {
225 this.checkTaskFunctionName(name
)
226 if (name
=== DEFAULT_TASK_NAME
) {
228 'Cannot remove the task function with the default reserved name'
232 this.taskFunctions
.get(name
) === this.taskFunctions
.get(DEFAULT_TASK_NAME
)
235 'Cannot remove the task function used as the default task function'
238 const deleteStatus
= this.taskFunctions
.delete(name
)
239 this.sendTaskFunctionsListToMainWorker()
244 * Lists the names of the worker's task functions.
246 * @returns The names of the worker's task functions.
248 public listTaskFunctions (): string[] {
249 const names
: string[] = [...this.taskFunctions
.keys()]
250 let defaultTaskFunctionName
: string = DEFAULT_TASK_NAME
251 for (const [name
, fn
] of this.taskFunctions
) {
253 name
!== DEFAULT_TASK_NAME
&&
254 fn
=== this.taskFunctions
.get(DEFAULT_TASK_NAME
)
256 defaultTaskFunctionName
= name
261 names
[names
.indexOf(DEFAULT_TASK_NAME
)],
262 defaultTaskFunctionName
,
264 (name
) => name
!== DEFAULT_TASK_NAME
&& name
!== defaultTaskFunctionName
270 * Sets the default task function to use in the worker.
272 * @param name - The name of the task function to use as default task function.
273 * @returns Whether the default task function was set or not.
274 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
275 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
276 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is a non-existing task function.
278 public setDefaultTaskFunction (name
: string): boolean {
279 this.checkTaskFunctionName(name
)
280 if (name
=== DEFAULT_TASK_NAME
) {
282 'Cannot set the default task function reserved name as the default task function'
285 if (!this.taskFunctions
.has(name
)) {
287 'Cannot set the default task function to a non-existing task function'
291 this.taskFunctions
.set(
293 this.taskFunctions
.get(name
) as TaskFunction
<Data
, Response
>
301 private checkTaskFunctionName (name
: string): void {
302 if (typeof name
!== 'string') {
303 throw new TypeError('name parameter is not a string')
305 if (typeof name
=== 'string' && name
.trim().length
=== 0) {
306 throw new TypeError('name parameter is an empty string')
311 * Handles the ready message sent by the main worker.
313 * @param message - The ready message.
315 protected abstract handleReadyMessage (message
: MessageValue
<Data
>): void
318 * Worker message listener.
320 * @param message - The received message.
322 protected messageListener (message
: MessageValue
<Data
>): void {
323 this.checkMessageWorkerId(message
)
324 if (message
.statistics
!= null) {
325 // Statistics message received
326 this.statistics
= message
.statistics
327 } else if (message
.checkActive
!= null) {
328 // Check active message received
329 message
.checkActive
? this.startCheckActive() : this.stopCheckActive()
330 } else if (message
.taskId
!= null && message
.data
!= null) {
331 // Task message received
333 } else if (message
.kill
=== true) {
334 // Kill message received
335 this.handleKillMessage(message
)
340 * Handles a kill message sent by the main worker.
342 * @param message - The kill message.
344 protected handleKillMessage (message
: MessageValue
<Data
>): void {
345 this.stopCheckActive()
346 if (isAsyncFunction(this.opts
.killHandler
)) {
347 (this.opts
.killHandler
?.() as Promise
<void>)
349 this.sendToMainWorker({ kill
: 'success', workerId
: this.id
})
353 this.sendToMainWorker({ kill
: 'failure', workerId
: this.id
})
358 .catch(EMPTY_FUNCTION
)
361 // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
362 this.opts
.killHandler
?.() as void
363 this.sendToMainWorker({ kill
: 'success', workerId
: this.id
})
365 this.sendToMainWorker({ kill
: 'failure', workerId
: this.id
})
373 * Check if the message worker id is set and matches the worker id.
375 * @param message - The message to check.
376 * @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.
378 private checkMessageWorkerId (message
: MessageValue
<Data
>): void {
379 if (message
.workerId
== null) {
380 throw new Error('Message worker id is not set')
381 } else if (message
.workerId
!= null && message
.workerId
!== this.id
) {
383 `Message worker id ${message.workerId} does not match the worker id ${this.id}`
389 * Starts the worker check active interval.
391 private startCheckActive (): void {
392 this.lastTaskTimestamp
= performance
.now()
393 this.activeInterval
= setInterval(
394 this.checkActive
.bind(this),
395 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
) / 2
400 * Stops the worker check active interval.
402 private stopCheckActive (): void {
403 if (this.activeInterval
!= null) {
404 clearInterval(this.activeInterval
)
405 delete this.activeInterval
410 * Checks if the worker should be terminated, because its living too long.
412 private checkActive (): void {
414 performance
.now() - this.lastTaskTimestamp
>
415 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
)
417 this.sendToMainWorker({ kill
: this.opts
.killBehavior
, workerId
: this.id
})
422 * Returns the main worker.
424 * @returns Reference to the main worker.
426 protected getMainWorker (): MainWorker
{
427 if (this.mainWorker
== null) {
428 throw new Error('Main worker not set')
430 return this.mainWorker
434 * Sends a message to main worker.
436 * @param message - The response message.
438 protected abstract sendToMainWorker (
439 message
: MessageValue
<Response
, Data
>
443 * Sends the list of task function names to the main worker.
445 protected sendTaskFunctionsListToMainWorker (): void {
446 this.sendToMainWorker({
447 taskFunctions
: this.listTaskFunctions(),
453 * Handles an error and convert it to a string so it can be sent back to the main worker.
455 * @param e - The error raised by the worker.
456 * @returns The error message.
458 protected handleError (e
: Error | string): string {
459 return e
instanceof Error ? e
.message
: e
463 * Runs the given task.
465 * @param task - The task to execute.
466 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found.
468 protected run (task
: Task
<Data
>): void {
469 const { name
, taskId
, data
} = task
470 const fn
= this.taskFunctions
.get(name
?? DEFAULT_TASK_NAME
)
472 this.sendToMainWorker({
474 name
: name
as string,
475 message
: `Task function '${name as string}' not found`,
483 if (isAsyncFunction(fn
)) {
484 this.runInAsyncScope(this.runAsync
.bind(this), this, fn
, task
)
486 this.runInAsyncScope(this.runSync
.bind(this), this, fn
, task
)
491 * Runs the given task function synchronously.
493 * @param fn - Task function that will be executed.
494 * @param task - Input data for the task function.
497 fn
: TaskSyncFunction
<Data
, Response
>,
500 const { name
, taskId
, data
} = task
502 let taskPerformance
= this.beginTaskPerformance(name
)
504 taskPerformance
= this.endTaskPerformance(taskPerformance
)
505 this.sendToMainWorker({
512 const errorMessage
= this.handleError(e
as Error | string)
513 this.sendToMainWorker({
515 name
: name
as string,
516 message
: errorMessage
,
523 this.updateLastTaskTimestamp()
528 * Runs the given task function asynchronously.
530 * @param fn - Task function that will be executed.
531 * @param task - Input data for the task function.
534 fn
: TaskAsyncFunction
<Data
, Response
>,
537 const { name
, taskId
, data
} = task
538 let taskPerformance
= this.beginTaskPerformance(name
)
541 taskPerformance
= this.endTaskPerformance(taskPerformance
)
542 this.sendToMainWorker({
551 const errorMessage
= this.handleError(e
as Error | string)
552 this.sendToMainWorker({
554 name
: name
as string,
555 message
: errorMessage
,
563 this.updateLastTaskTimestamp()
565 .catch(EMPTY_FUNCTION
)
568 private beginTaskPerformance (name
?: string): TaskPerformance
{
569 this.checkStatistics()
571 name
: name
?? DEFAULT_TASK_NAME
,
572 timestamp
: performance
.now(),
573 ...(this.statistics
.elu
&& { elu
: performance
.eventLoopUtilization() })
577 private endTaskPerformance (
578 taskPerformance
: TaskPerformance
580 this.checkStatistics()
583 ...(this.statistics
.runTime
&& {
584 runTime
: performance
.now() - taskPerformance
.timestamp
586 ...(this.statistics
.elu
&& {
587 elu
: performance
.eventLoopUtilization(taskPerformance
.elu
)
592 private checkStatistics (): void {
593 if (this.statistics
== null) {
594 throw new Error('Performance statistics computation requirements not set')
598 private updateLastTaskTimestamp (): void {
599 if (this.activeInterval
!= null) {
600 this.lastTaskTimestamp
= performance
.now()