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 delete this.opts
.async
107 this.opts
.killHandler
= opts
.killHandler
?? EMPTY_FUNCTION
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 fn
!== 'function') {
142 'A taskFunctions parameter object value is not a function'
145 const boundFn
= fn
.bind(this)
147 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
150 this.taskFunctions
.set(name
, boundFn
)
153 throw new Error('taskFunctions parameter object is empty')
157 'taskFunctions parameter is not a function or a plain object'
163 * Checks if the worker has a task function with the given name.
165 * @param name - The name of the task function to check.
166 * @returns Whether the worker has a task function with the given name or not.
167 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string.
169 public hasTaskFunction (name
: string): boolean {
170 if (typeof name
!== 'string') {
171 throw new TypeError('name parameter is not a string')
173 return this.taskFunctions
.has(name
)
177 * Adds a task function to the worker.
178 * If a task function with the same name already exists, it is replaced.
180 * @param name - The name of the task function to add.
181 * @param fn - The task function to add.
182 * @returns Whether the task function was added or not.
183 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string.
184 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
185 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `fn` parameter is not a function.
187 public addTaskFunction (
189 fn
: TaskFunction
<Data
, Response
>
191 if (typeof name
!== 'string') {
192 throw new TypeError('name parameter is not a string')
194 if (name
=== DEFAULT_TASK_NAME
) {
196 'Cannot add a task function with the default reserved name'
199 if (typeof fn
!== 'function') {
200 throw new TypeError('fn parameter is not a function')
203 const boundFn
= fn
.bind(this)
205 this.taskFunctions
.get(name
) ===
206 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
208 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
210 this.taskFunctions
.set(name
, boundFn
)
218 * Removes a task function from the worker.
220 * @param name - The name of the task function to remove.
221 * @returns Whether the task function existed and was removed or not.
222 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string.
223 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
224 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the task function used as default task function.
226 public removeTaskFunction (name
: string): boolean {
227 if (typeof name
!== 'string') {
228 throw new TypeError('name parameter is not a string')
230 if (name
=== DEFAULT_TASK_NAME
) {
232 'Cannot remove the task function with the default reserved name'
236 this.taskFunctions
.get(name
) === this.taskFunctions
.get(DEFAULT_TASK_NAME
)
239 'Cannot remove the task function used as the default task function'
242 return this.taskFunctions
.delete(name
)
246 * Lists the names of the worker's task functions.
248 * @returns The names of the worker's task functions.
250 public listTaskFunctions (): string[] {
251 return [...this.taskFunctions
.keys()]
255 * Sets the default task function to use in the worker.
257 * @param name - The name of the task function to use as default task function.
258 * @returns Whether the default task function was set or not.
259 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string.
260 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
261 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is a non-existing task function.
263 public setDefaultTaskFunction (name
: string): boolean {
264 if (typeof name
!== 'string') {
265 throw new TypeError('name parameter is not a string')
267 if (name
=== DEFAULT_TASK_NAME
) {
269 'Cannot set the default task function reserved name as the default task function'
272 if (!this.taskFunctions
.has(name
)) {
274 'Cannot set the default task function to a non-existing task function'
278 this.taskFunctions
.set(
280 this.taskFunctions
.get(name
) as TaskFunction
<Data
, Response
>
289 * Handles the ready message sent by the main worker.
291 * @param message - The ready message.
293 protected abstract handleReadyMessage (message
: MessageValue
<Data
>): void
296 * Worker message listener.
298 * @param message - The received message.
300 protected messageListener (message
: MessageValue
<Data
>): void {
302 throw new Error('Cannot handle message to worker in main worker')
303 } else if (message
.workerId
!= null && message
.workerId
!== this.id
) {
304 throw new Error('Message worker id does not match the worker id')
305 } else if (message
.workerId
=== this.id
) {
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
.taskId
!= null && message
.data
!= null) {
313 // Task message received
315 } else if (message
.kill
=== true) {
316 // Kill message received
317 this.handleKillMessage(message
)
323 * Handles a kill message sent by the main worker.
325 * @param message - The kill message.
327 protected handleKillMessage (message
: MessageValue
<Data
>): void {
328 this.stopCheckActive()
329 if (isAsyncFunction(this.opts
.killHandler
)) {
330 (this.opts
.killHandler
?.() as Promise
<void>)
331 .then(() => this.emitDestroy())
332 .catch(EMPTY_FUNCTION
)
334 // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
335 this.opts
.killHandler
?.() as void
341 * Starts the worker check active interval.
343 private startCheckActive (): void {
344 this.lastTaskTimestamp
= performance
.now()
345 this.activeInterval
= setInterval(
346 this.checkActive
.bind(this),
347 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
) / 2
352 * Stops the worker check active interval.
354 private stopCheckActive (): void {
355 if (this.activeInterval
!= null) {
356 clearInterval(this.activeInterval
)
357 delete this.activeInterval
362 * Checks if the worker should be terminated, because its living too long.
364 private checkActive (): void {
366 performance
.now() - this.lastTaskTimestamp
>
367 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
)
369 this.sendToMainWorker({ kill
: this.opts
.killBehavior
, workerId
: this.id
})
374 * Returns the main worker.
376 * @returns Reference to the main worker.
378 protected getMainWorker (): MainWorker
{
379 if (this.mainWorker
== null) {
380 throw new Error('Main worker not set')
382 return this.mainWorker
386 * Sends a message to main worker.
388 * @param message - The response message.
390 protected abstract sendToMainWorker (
391 message
: MessageValue
<Response
, Data
>
395 * Handles an error and convert it to a string so it can be sent back to the main worker.
397 * @param e - The error raised by the worker.
398 * @returns The error message.
400 protected handleError (e
: Error | string): string {
401 return e
instanceof Error ? e
.message
: e
405 * Runs the given task.
407 * @param task - The task to execute.
408 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found.
410 protected run (task
: Task
<Data
>): void {
411 const fn
= this.getTaskFunction(task
.name
)
412 if (isAsyncFunction(fn
)) {
413 this.runInAsyncScope(this.runAsync
.bind(this), this, fn
, task
)
415 this.runInAsyncScope(this.runSync
.bind(this), this, fn
, task
)
420 * Runs the given task function synchronously.
422 * @param fn - Task function that will be executed.
423 * @param task - Input data for the task function.
426 fn
: TaskSyncFunction
<Data
, Response
>,
430 let taskPerformance
= this.beginTaskPerformance(task
.name
)
431 const res
= fn(task
.data
)
432 taskPerformance
= this.endTaskPerformance(taskPerformance
)
433 this.sendToMainWorker({
440 const errorMessage
= this.handleError(e
as Error | string)
441 this.sendToMainWorker({
443 name
: task
.name
?? DEFAULT_TASK_NAME
,
444 message
: errorMessage
,
451 this.updateLastTaskTimestamp()
456 * Runs the given task function asynchronously.
458 * @param fn - Task function that will be executed.
459 * @param task - Input data for the task function.
462 fn
: TaskAsyncFunction
<Data
, Response
>,
465 let taskPerformance
= this.beginTaskPerformance(task
.name
)
468 taskPerformance
= this.endTaskPerformance(taskPerformance
)
469 this.sendToMainWorker({
478 const errorMessage
= this.handleError(e
as Error | string)
479 this.sendToMainWorker({
481 name
: task
.name
?? DEFAULT_TASK_NAME
,
482 message
: errorMessage
,
490 this.updateLastTaskTimestamp()
492 .catch(EMPTY_FUNCTION
)
496 * Gets the task function with the given name.
498 * @param name - Name of the task function that will be returned.
499 * @returns The task function.
500 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found.
502 private getTaskFunction (name
?: string): TaskFunction
<Data
, Response
> {
503 name
= name
?? DEFAULT_TASK_NAME
504 const fn
= this.taskFunctions
.get(name
)
506 throw new Error(`Task function '${name}' not found`)
511 private beginTaskPerformance (name
?: string): TaskPerformance
{
512 this.checkStatistics()
514 name
: name
?? DEFAULT_TASK_NAME
,
515 timestamp
: performance
.now(),
516 ...(this.statistics
.elu
&& { elu
: performance
.eventLoopUtilization() })
520 private endTaskPerformance (
521 taskPerformance
: TaskPerformance
523 this.checkStatistics()
526 ...(this.statistics
.runTime
&& {
527 runTime
: performance
.now() - taskPerformance
.timestamp
529 ...(this.statistics
.elu
&& {
530 elu
: performance
.eventLoopUtilization(taskPerformance
.elu
)
535 private checkStatistics (): void {
536 if (this.statistics
== null) {
537 throw new Error('Performance statistics computation requirements not set')
541 private updateLastTaskTimestamp (): void {
542 if (this.activeInterval
!= null) {
543 this.lastTaskTimestamp
= performance
.now()