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'
21 } from
'./worker-options'
27 } from
'./task-functions'
29 const DEFAULT_MAX_INACTIVE_TIME
= 60000
30 const DEFAULT_KILL_BEHAVIOR
: KillBehavior
= KillBehaviors
.SOFT
33 * Base class that implements some shared logic for all poolifier workers.
35 * @typeParam MainWorker - Type of main worker.
36 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
37 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data.
39 export abstract class AbstractWorker
<
40 MainWorker
extends Worker
| MessagePort
,
43 > extends AsyncResource
{
47 protected abstract id
: number
49 * Task function(s) processed by the worker when the pool's `execution` function is invoked.
51 protected taskFunctions
!: Map
<string, TaskFunction
<Data
, Response
>>
53 * Timestamp of the last task processed by this worker.
55 protected lastTaskTimestamp
!: number
57 * Performance statistics computation requirements.
59 protected statistics
!: WorkerStatistics
61 * Handler id of the `activeInterval` worker activity check.
63 protected activeInterval
?: NodeJS
.Timeout
65 * Constructs a new poolifier worker.
67 * @param type - The type of async event.
68 * @param isMain - Whether this is the main worker or not.
69 * @param mainWorker - Reference to main worker.
70 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. The first function is the default function.
71 * @param opts - Options for the worker.
75 protected readonly isMain
: boolean,
76 private readonly mainWorker
: MainWorker
,
77 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>,
78 protected readonly opts
: WorkerOptions
= {
80 * The kill behavior option on this worker or its default value.
82 killBehavior
: DEFAULT_KILL_BEHAVIOR
,
84 * The maximum time to keep this worker active while idle.
85 * The pool automatically checks and terminates this worker when the time expires.
87 maxInactiveTime
: DEFAULT_MAX_INACTIVE_TIME
,
89 * The function to call when the worker is killed.
91 killHandler
: EMPTY_FUNCTION
95 this.checkWorkerOptions(this.opts
)
96 this.checkTaskFunctions(taskFunctions
)
98 this.getMainWorker()?.on('message', this.handleReadyMessage
.bind(this))
102 private checkWorkerOptions (opts
: WorkerOptions
): void {
103 this.opts
.killBehavior
= opts
.killBehavior
?? DEFAULT_KILL_BEHAVIOR
104 this.opts
.maxInactiveTime
=
105 opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
106 this.opts
.killHandler
= opts
.killHandler
?? EMPTY_FUNCTION
107 delete this.opts
.async
111 * Checks if the `taskFunctions` parameter is passed to the constructor.
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 if (typeof name
!== 'string') {
137 'A taskFunctions parameter object key is not a string'
140 if (typeof name
=== 'string' && name
.trim().length
=== 0) {
142 'A taskFunctions parameter object key an empty string'
145 if (typeof fn
!== 'function') {
147 'A taskFunctions parameter object value is not a function'
150 const boundFn
= fn
.bind(this)
152 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
155 this.taskFunctions
.set(name
, boundFn
)
158 throw new Error('taskFunctions parameter object is empty')
162 'taskFunctions parameter is not a function or a plain object'
168 * Checks if the worker has a task function with the given name.
170 * @param name - The name of the task function to check.
171 * @returns Whether the worker has a task function with the given name or not.
172 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
174 public hasTaskFunction (name
: string): boolean {
175 if (typeof name
!== 'string') {
176 throw new TypeError('name parameter is not a string')
178 if (typeof name
=== 'string' && name
.trim().length
=== 0) {
179 throw new TypeError('name parameter is an empty string')
181 return this.taskFunctions
.has(name
)
185 * Adds a task function to the worker.
186 * If a task function with the same name already exists, it is replaced.
188 * @param name - The name of the task function to add.
189 * @param fn - The task function to add.
190 * @returns Whether the task function was added or not.
191 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
192 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
193 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `fn` parameter is not a function.
195 public addTaskFunction (
197 fn
: TaskFunction
<Data
, Response
>
199 if (typeof name
!== 'string') {
200 throw new TypeError('name parameter is not a string')
202 if (typeof name
=== 'string' && name
.trim().length
=== 0) {
203 throw new TypeError('name parameter is an empty string')
205 if (name
=== DEFAULT_TASK_NAME
) {
207 'Cannot add a task function with the default reserved name'
210 if (typeof fn
!== 'function') {
211 throw new TypeError('fn parameter is not a function')
214 const boundFn
= fn
.bind(this)
216 this.taskFunctions
.get(name
) ===
217 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
219 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
221 this.taskFunctions
.set(name
, boundFn
)
222 this.sendTaskFunctionsListToMainWorker()
230 * Removes a task function from the worker.
232 * @param name - The name of the task function to remove.
233 * @returns Whether the task function existed and was removed or not.
234 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
235 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
236 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the task function used as default task function.
238 public removeTaskFunction (name
: string): boolean {
239 if (typeof name
!== 'string') {
240 throw new TypeError('name parameter is not a string')
242 if (typeof name
=== 'string' && name
.trim().length
=== 0) {
243 throw new TypeError('name parameter is an empty string')
245 if (name
=== DEFAULT_TASK_NAME
) {
247 'Cannot remove the task function with the default reserved name'
251 this.taskFunctions
.get(name
) === this.taskFunctions
.get(DEFAULT_TASK_NAME
)
254 'Cannot remove the task function used as the default task function'
257 const deleteStatus
= this.taskFunctions
.delete(name
)
258 this.sendTaskFunctionsListToMainWorker()
263 * Lists the names of the worker's task functions.
265 * @returns The names of the worker's task functions.
267 public listTaskFunctions (): string[] {
268 return [...this.taskFunctions
.keys()]
272 * Sets the default task function to use in the worker.
274 * @param name - The name of the task function to use as default task function.
275 * @returns Whether the default task function was set or not.
276 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string or an empty string.
277 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
278 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is a non-existing task function.
280 public setDefaultTaskFunction (name
: string): boolean {
281 if (typeof name
!== 'string') {
282 throw new TypeError('name parameter is not a string')
284 if (typeof name
=== 'string' && name
.trim().length
=== 0) {
285 throw new TypeError('name parameter is an empty string')
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'
298 this.taskFunctions
.set(
300 this.taskFunctions
.get(name
) as TaskFunction
<Data
, Response
>
309 * Handles the ready message sent by the main worker.
311 * @param message - The ready message.
313 protected abstract handleReadyMessage (message
: MessageValue
<Data
>): void
316 * Worker message listener.
318 * @param message - The received message.
320 protected messageListener (message
: MessageValue
<Data
>): void {
322 throw new Error('Cannot handle message to worker in main worker')
324 this.checkMessageWorkerId(message
)
325 if (message
.statistics
!= null) {
326 // Statistics message received
327 this.statistics
= message
.statistics
328 } else if (message
.checkActive
!= null) {
329 // Check active message received
330 message
.checkActive
? this.startCheckActive() : this.stopCheckActive()
331 } else if (message
.taskId
!= null && message
.data
!= null) {
332 // Task message received
334 } else if (message
.kill
=== true) {
335 // Kill message received
336 this.handleKillMessage(message
)
341 * Handles a kill message sent by the main worker.
343 * @param message - The kill message.
345 protected handleKillMessage (message
: MessageValue
<Data
>): void {
346 this.stopCheckActive()
347 if (isAsyncFunction(this.opts
.killHandler
)) {
348 (this.opts
.killHandler
?.() as Promise
<void>)
350 this.sendToMainWorker({ kill
: 'success', workerId
: this.id
})
354 this.sendToMainWorker({ kill
: 'failure', workerId
: this.id
})
359 .catch(EMPTY_FUNCTION
)
362 // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
363 this.opts
.killHandler
?.() as void
364 this.sendToMainWorker({ kill
: 'success', workerId
: this.id
})
366 this.sendToMainWorker({ kill
: 'failure', workerId
: this.id
})
374 * Check if the message worker id is set and matches the worker id.
376 * @param message - The message to check.
377 * @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.
379 private checkMessageWorkerId (message
: MessageValue
<Data
>): void {
380 if (message
.workerId
== null) {
381 throw new Error('Message worker id is not set')
382 } else if (message
.workerId
!= null && message
.workerId
!== this.id
) {
384 `Message worker id ${message.workerId} does not match the worker id ${this.id}`
390 * Starts the worker check active interval.
392 private startCheckActive (): void {
393 this.lastTaskTimestamp
= performance
.now()
394 this.activeInterval
= setInterval(
395 this.checkActive
.bind(this),
396 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
) / 2
401 * Stops the worker check active interval.
403 private stopCheckActive (): void {
404 if (this.activeInterval
!= null) {
405 clearInterval(this.activeInterval
)
406 delete this.activeInterval
411 * Checks if the worker should be terminated, because its living too long.
413 private checkActive (): void {
415 performance
.now() - this.lastTaskTimestamp
>
416 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
)
418 this.sendToMainWorker({ kill
: this.opts
.killBehavior
, workerId
: this.id
})
423 * Returns the main worker.
425 * @returns Reference to the main worker.
427 protected getMainWorker (): MainWorker
{
428 if (this.mainWorker
== null) {
429 throw new Error('Main worker not set')
431 return this.mainWorker
435 * Sends a message to main worker.
437 * @param message - The response message.
439 protected abstract sendToMainWorker (
440 message
: MessageValue
<Response
, Data
>
444 * Sends the list of task function names to the main worker.
446 protected sendTaskFunctionsListToMainWorker (): void {
447 this.sendToMainWorker({
448 taskFunctions
: this.listTaskFunctions(),
454 * Handles an error and convert it to a string so it can be sent back to the main worker.
456 * @param e - The error raised by the worker.
457 * @returns The error message.
459 protected handleError (e
: Error | string): string {
460 return e
instanceof Error ? e
.message
: e
464 * Runs the given task.
466 * @param task - The task to execute.
467 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found.
469 protected run (task
: Task
<Data
>): void {
470 const fn
= this.getTaskFunction(task
.name
)
471 if (isAsyncFunction(fn
)) {
472 this.runInAsyncScope(this.runAsync
.bind(this), this, fn
, task
)
474 this.runInAsyncScope(this.runSync
.bind(this), this, fn
, task
)
479 * Runs the given task function synchronously.
481 * @param fn - Task function that will be executed.
482 * @param task - Input data for the task function.
485 fn
: TaskSyncFunction
<Data
, Response
>,
488 const { name
, taskId
, data
} = task
490 let taskPerformance
= this.beginTaskPerformance(name
)
492 taskPerformance
= this.endTaskPerformance(taskPerformance
)
493 this.sendToMainWorker({
500 const errorMessage
= this.handleError(e
as Error | string)
501 this.sendToMainWorker({
503 name
: name
?? DEFAULT_TASK_NAME
,
504 message
: errorMessage
,
511 this.updateLastTaskTimestamp()
516 * Runs the given task function asynchronously.
518 * @param fn - Task function that will be executed.
519 * @param task - Input data for the task function.
522 fn
: TaskAsyncFunction
<Data
, Response
>,
525 const { name
, taskId
, data
} = task
526 let taskPerformance
= this.beginTaskPerformance(name
)
529 taskPerformance
= this.endTaskPerformance(taskPerformance
)
530 this.sendToMainWorker({
539 const errorMessage
= this.handleError(e
as Error | string)
540 this.sendToMainWorker({
542 name
: name
?? DEFAULT_TASK_NAME
,
543 message
: errorMessage
,
551 this.updateLastTaskTimestamp()
553 .catch(EMPTY_FUNCTION
)
557 * Gets the task function with the given name.
559 * @param name - Name of the task function that will be returned.
560 * @returns The task function.
561 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found.
563 private getTaskFunction (name
?: string): TaskFunction
<Data
, Response
> {
564 name
= name
?? DEFAULT_TASK_NAME
565 const fn
= this.taskFunctions
.get(name
)
567 throw new Error(`Task function '${name}' not found`)
572 private beginTaskPerformance (name
?: string): TaskPerformance
{
573 this.checkStatistics()
575 name
: name
?? DEFAULT_TASK_NAME
,
576 timestamp
: performance
.now(),
577 ...(this.statistics
.elu
&& { elu
: performance
.eventLoopUtilization() })
581 private endTaskPerformance (
582 taskPerformance
: TaskPerformance
584 this.checkStatistics()
587 ...(this.statistics
.runTime
&& {
588 runTime
: performance
.now() - taskPerformance
.timestamp
590 ...(this.statistics
.elu
&& {
591 elu
: performance
.eventLoopUtilization(taskPerformance
.elu
)
596 private checkStatistics (): void {
597 if (this.statistics
== null) {
598 throw new Error('Performance statistics computation requirements not set')
602 private updateLastTaskTimestamp (): void {
603 if (this.activeInterval
!= null) {
604 this.lastTaskTimestamp
= performance
.now()