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.js'
16 import { KillBehaviors
, type WorkerOptions
} from
'./worker-options.js'
20 TaskFunctionOperationResult
,
23 } from
'./task-functions.js'
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 | undefined,
90 private readonly mainWorker
: MainWorker
| undefined | null,
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 (
117 | TaskFunction
<Data
, Response
>
118 | TaskFunctions
<Data
, Response
>
121 if (taskFunctions
== null) {
122 throw new Error('taskFunctions parameter is mandatory')
124 this.taskFunctions
= new Map
<string, TaskFunction
<Data
, Response
>>()
125 if (typeof taskFunctions
=== 'function') {
126 const boundFn
= taskFunctions
.bind(this)
127 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
128 this.taskFunctions
.set(
129 typeof taskFunctions
.name
=== 'string' &&
130 taskFunctions
.name
.trim().length
> 0
135 } else if (isPlainObject(taskFunctions
)) {
136 let firstEntry
= true
137 for (const [name
, fn
] of Object.entries(taskFunctions
)) {
138 checkValidTaskFunctionEntry
<Data
, Response
>(name
, fn
)
139 const boundFn
= fn
.bind(this)
141 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
144 this.taskFunctions
.set(name
, boundFn
)
147 throw new Error('taskFunctions parameter object is empty')
151 'taskFunctions parameter is not a function or a plain object'
157 * Checks if the worker has a task function with the given name.
159 * @param name - The name of the task function to check.
160 * @returns Whether the worker has a task function with the given name or not.
162 public hasTaskFunction (name
: string): TaskFunctionOperationResult
{
164 checkTaskFunctionName(name
)
166 return { status: false, error
: error
as Error }
168 return { status: this.taskFunctions
.has(name
) }
172 * Adds a task function to the worker.
173 * If a task function with the same name already exists, it is replaced.
175 * @param name - The name of the task function to add.
176 * @param fn - The task function to add.
177 * @returns Whether the task function was added or not.
179 public addTaskFunction (
181 fn
: TaskFunction
<Data
, Response
>
182 ): TaskFunctionOperationResult
{
184 checkTaskFunctionName(name
)
185 if (name
=== DEFAULT_TASK_NAME
) {
187 'Cannot add a task function with the default reserved name'
190 if (typeof fn
!== 'function') {
191 throw new TypeError('fn parameter is not a function')
193 const boundFn
= fn
.bind(this)
195 this.taskFunctions
.get(name
) ===
196 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
198 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
200 this.taskFunctions
.set(name
, boundFn
)
201 this.sendTaskFunctionNamesToMainWorker()
202 return { status: true }
204 return { status: false, error
: error
as Error }
209 * Removes a task function from the worker.
211 * @param name - The name of the task function to remove.
212 * @returns Whether the task function existed and was removed or not.
214 public removeTaskFunction (name
: string): TaskFunctionOperationResult
{
216 checkTaskFunctionName(name
)
217 if (name
=== DEFAULT_TASK_NAME
) {
219 'Cannot remove the task function with the default reserved name'
223 this.taskFunctions
.get(name
) ===
224 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
227 'Cannot remove the task function used as the default task function'
230 const deleteStatus
= this.taskFunctions
.delete(name
)
231 this.sendTaskFunctionNamesToMainWorker()
232 return { status: deleteStatus
}
234 return { status: false, error
: error
as Error }
239 * Lists the names of the worker's task functions.
241 * @returns The names of the worker's task functions.
243 public listTaskFunctionNames (): string[] {
244 const names
: string[] = [...this.taskFunctions
.keys()]
245 let defaultTaskFunctionName
: string = DEFAULT_TASK_NAME
246 for (const [name
, fn
] of this.taskFunctions
) {
248 name
!== DEFAULT_TASK_NAME
&&
249 fn
=== this.taskFunctions
.get(DEFAULT_TASK_NAME
)
251 defaultTaskFunctionName
= name
256 names
[names
.indexOf(DEFAULT_TASK_NAME
)],
257 defaultTaskFunctionName
,
259 name
=> name
!== DEFAULT_TASK_NAME
&& name
!== defaultTaskFunctionName
265 * Sets the default task function to use in the worker.
267 * @param name - The name of the task function to use as default task function.
268 * @returns Whether the default task function was set or not.
270 public setDefaultTaskFunction (name
: string): TaskFunctionOperationResult
{
272 checkTaskFunctionName(name
)
273 if (name
=== DEFAULT_TASK_NAME
) {
275 'Cannot set the default task function reserved name as the default task function'
278 if (!this.taskFunctions
.has(name
)) {
280 'Cannot set the default task function to a non-existing task function'
283 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
284 this.taskFunctions
.set(DEFAULT_TASK_NAME
, this.taskFunctions
.get(name
)!)
285 this.sendTaskFunctionNamesToMainWorker()
286 return { status: true }
288 return { status: false, error
: error
as Error }
293 * Handles the ready message sent by the main worker.
295 * @param message - The ready message.
297 protected abstract handleReadyMessage (message
: MessageValue
<Data
>): void
300 * Worker message listener.
302 * @param message - The received message.
304 protected messageListener (message
: MessageValue
<Data
>): void {
305 this.checkMessageWorkerId(message
)
306 if (message
.statistics
!= null) {
307 // Statistics message received
308 this.statistics
= message
.statistics
309 } else if (message
.checkActive
!= null) {
310 // Check active message received
311 message
.checkActive
? this.startCheckActive() : this.stopCheckActive()
312 } else if (message
.taskFunctionOperation
!= null) {
313 // Task function operation message received
314 this.handleTaskFunctionOperationMessage(message
)
315 } else if (message
.taskId
!= null && message
.data
!= null) {
316 // Task message received
318 } else if (message
.kill
=== true) {
319 // Kill message received
320 this.handleKillMessage(message
)
324 protected handleTaskFunctionOperationMessage (
325 message
: MessageValue
<Data
>
327 const { taskFunctionOperation
, taskFunctionName
, taskFunction
} = message
328 let response
!: TaskFunctionOperationResult
329 switch (taskFunctionOperation
) {
331 response
= this.addTaskFunction(
332 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
334 // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func, @typescript-eslint/no-non-null-assertion
335 new Function(`return ${taskFunction!}`)() as TaskFunction
<
342 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
343 response
= this.removeTaskFunction(taskFunctionName
!)
346 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
347 response
= this.setDefaultTaskFunction(taskFunctionName
!)
350 response
= { status: false, error
: new Error('Unknown task operation') }
353 this.sendToMainWorker({
354 taskFunctionOperation
,
355 taskFunctionOperationStatus
: response
.status,
357 ...(!response
.status &&
358 response
.error
!= null && {
360 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
361 name
: taskFunctionName
!,
362 message
: this.handleError(response
.error
as Error | string)
369 * Handles a kill message sent by the main worker.
371 * @param message - The kill message.
373 protected handleKillMessage (_message
: MessageValue
<Data
>): void {
374 this.stopCheckActive()
375 if (isAsyncFunction(this.opts
.killHandler
)) {
376 (this.opts
.killHandler() as Promise
<void>)
378 this.sendToMainWorker({ kill
: 'success' })
382 this.sendToMainWorker({ kill
: 'failure' })
386 // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
387 this.opts
.killHandler
?.() as void
388 this.sendToMainWorker({ kill
: 'success' })
390 this.sendToMainWorker({ kill
: 'failure' })
396 * Check if the message worker id is set and matches the worker id.
398 * @param message - The message to check.
399 * @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.
401 private checkMessageWorkerId (message
: MessageValue
<Data
>): void {
402 if (message
.workerId
== null) {
403 throw new Error('Message worker id is not set')
404 } else if (message
.workerId
!== this.id
) {
406 `Message worker id ${message.workerId} does not match the worker id ${this.id}`
412 * Starts the worker check active interval.
414 private startCheckActive (): void {
415 this.lastTaskTimestamp
= performance
.now()
416 this.activeInterval
= setInterval(
417 this.checkActive
.bind(this),
418 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
) / 2
423 * Stops the worker check active interval.
425 private stopCheckActive (): void {
426 if (this.activeInterval
!= null) {
427 clearInterval(this.activeInterval
)
428 delete this.activeInterval
433 * Checks if the worker should be terminated, because its living too long.
435 private checkActive (): void {
437 performance
.now() - this.lastTaskTimestamp
>
438 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
)
440 this.sendToMainWorker({ kill
: this.opts
.killBehavior
})
445 * Returns the main worker.
447 * @returns Reference to the main worker.
448 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the main worker is not set.
450 protected getMainWorker (): MainWorker
{
451 if (this.mainWorker
== null) {
452 throw new Error('Main worker not set')
454 return this.mainWorker
458 * Sends a message to main worker.
460 * @param message - The response message.
462 protected abstract sendToMainWorker (
463 message
: MessageValue
<Response
, Data
>
467 * Sends task function names to the main worker.
469 protected sendTaskFunctionNamesToMainWorker (): void {
470 this.sendToMainWorker({
471 taskFunctionNames
: this.listTaskFunctionNames()
476 * Handles an error and convert it to a string so it can be sent back to the main worker.
478 * @param error - The error raised by the worker.
479 * @returns The error message.
481 protected handleError (error
: Error | string): string {
482 return error
instanceof Error ? error
.message
: error
486 * Runs the given task.
488 * @param task - The task to execute.
490 protected readonly run
= (task
: Task
<Data
>): void => {
491 const { name
, taskId
, data
} = task
492 const taskFunctionName
= name
?? DEFAULT_TASK_NAME
493 if (!this.taskFunctions
.has(taskFunctionName
)) {
494 this.sendToMainWorker({
496 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
498 message
: `Task function '${name}' not found`,
505 const fn
= this.taskFunctions
.get(taskFunctionName
)
506 if (isAsyncFunction(fn
)) {
507 this.runAsync(fn
as TaskAsyncFunction
<Data
, Response
>, task
)
509 this.runSync(fn
as TaskSyncFunction
<Data
, Response
>, task
)
514 * Runs the given task function synchronously.
516 * @param fn - Task function that will be executed.
517 * @param task - Input data for the task function.
519 protected readonly runSync
= (
520 fn
: TaskSyncFunction
<Data
, Response
>,
523 const { name
, taskId
, data
} = task
525 let taskPerformance
= this.beginTaskPerformance(name
)
527 taskPerformance
= this.endTaskPerformance(taskPerformance
)
528 this.sendToMainWorker({
534 this.sendToMainWorker({
536 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
538 message
: this.handleError(error
as Error | string),
544 this.updateLastTaskTimestamp()
549 * Runs the given task function asynchronously.
551 * @param fn - Task function that will be executed.
552 * @param task - Input data for the task function.
554 protected readonly runAsync
= (
555 fn
: TaskAsyncFunction
<Data
, Response
>,
558 const { name
, taskId
, data
} = task
559 let taskPerformance
= this.beginTaskPerformance(name
)
562 taskPerformance
= this.endTaskPerformance(taskPerformance
)
563 this.sendToMainWorker({
571 this.sendToMainWorker({
573 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
575 message
: this.handleError(error
as Error | string),
582 this.updateLastTaskTimestamp()
584 .catch(EMPTY_FUNCTION
)
587 private beginTaskPerformance (name
?: string): TaskPerformance
{
588 if (this.statistics
== null) {
589 throw new Error('Performance statistics computation requirements not set')
592 name
: name
?? DEFAULT_TASK_NAME
,
593 timestamp
: performance
.now(),
594 ...(this.statistics
.elu
&& {
595 elu
: performance
.eventLoopUtilization()
600 private endTaskPerformance (
601 taskPerformance
: TaskPerformance
603 if (this.statistics
== null) {
604 throw new Error('Performance statistics computation requirements not set')
608 ...(this.statistics
.runTime
&& {
609 runTime
: performance
.now() - taskPerformance
.timestamp
611 ...(this.statistics
.elu
&& {
612 elu
: performance
.eventLoopUtilization(taskPerformance
.elu
)
617 private updateLastTaskTimestamp (): void {
618 if (this.activeInterval
!= null) {
619 this.lastTaskTimestamp
= performance
.now()