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
'./worker-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, WorkerFunction
<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
,
78 | WorkerFunction
<Data
, Response
>
79 | TaskFunctions
<Data
, Response
>,
80 protected readonly opts
: WorkerOptions
= {
82 * The kill behavior option on this worker or its default value.
84 killBehavior
: DEFAULT_KILL_BEHAVIOR
,
86 * The maximum time to keep this worker active while idle.
87 * The pool automatically checks and terminates this worker when the time expires.
89 maxInactiveTime
: DEFAULT_MAX_INACTIVE_TIME
93 this.checkWorkerOptions(this.opts
)
94 this.checkTaskFunctions(taskFunctions
)
96 this.getMainWorker()?.on('message', this.handleReadyMessage
.bind(this))
100 private checkWorkerOptions (opts
: WorkerOptions
): void {
101 this.opts
.killBehavior
= opts
.killBehavior
?? DEFAULT_KILL_BEHAVIOR
102 this.opts
.maxInactiveTime
=
103 opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
104 delete this.opts
.async
108 * Checks if the `taskFunctions` parameter is passed to the constructor.
110 * @param taskFunctions - The task function(s) parameter that should be checked.
112 private checkTaskFunctions (
114 | WorkerFunction
<Data
, Response
>
115 | TaskFunctions
<Data
, Response
>
117 if (taskFunctions
== null) {
118 throw new Error('taskFunctions parameter is mandatory')
120 this.taskFunctions
= new Map
<string, WorkerFunction
<Data
, Response
>>()
121 if (typeof taskFunctions
=== 'function') {
122 const boundFn
= taskFunctions
.bind(this)
123 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
124 this.taskFunctions
.set(
125 typeof taskFunctions
.name
=== 'string' &&
126 taskFunctions
.name
.trim().length
> 0
131 } else if (isPlainObject(taskFunctions
)) {
132 let firstEntry
= true
133 for (const [name
, fn
] of Object.entries(taskFunctions
)) {
134 if (typeof name
!== 'string') {
136 'A taskFunctions parameter object key is not a string'
139 if (typeof fn
!== 'function') {
141 'A taskFunctions parameter object value is not a function'
144 const boundFn
= fn
.bind(this)
146 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
149 this.taskFunctions
.set(name
, boundFn
)
152 throw new Error('taskFunctions parameter object is empty')
156 'taskFunctions parameter is not a function or a plain object'
162 * Checks if the worker has a task function with the given name.
164 * @param name - The name of the task function to check.
165 * @returns Whether the worker has a task function with the given name or not.
166 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string.
168 public hasTaskFunction (name
: string): boolean {
169 if (typeof name
!== 'string') {
170 throw new TypeError('name parameter is not a string')
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.
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
: WorkerFunction
<Data
, Response
>
190 if (typeof name
!== 'string') {
191 throw new TypeError('name parameter is not a string')
193 if (name
=== DEFAULT_TASK_NAME
) {
195 'Cannot add a task function with the default reserved name'
198 if (typeof fn
!== 'function') {
199 throw new TypeError('fn parameter is not a function')
202 const boundFn
= fn
.bind(this)
204 this.taskFunctions
.get(name
) ===
205 this.taskFunctions
.get(DEFAULT_TASK_NAME
)
207 this.taskFunctions
.set(DEFAULT_TASK_NAME
, boundFn
)
209 this.taskFunctions
.set(name
, boundFn
)
217 * Removes a task function from the worker.
219 * @param name - The name of the task function to remove.
220 * @returns Whether the task function existed and was removed or not.
221 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string.
222 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
223 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the task function used as default task function.
225 public removeTaskFunction (name
: string): boolean {
226 if (typeof name
!== 'string') {
227 throw new TypeError('name parameter is not a string')
229 if (name
=== DEFAULT_TASK_NAME
) {
231 'Cannot remove the task function with the default reserved name'
235 this.taskFunctions
.get(name
) === this.taskFunctions
.get(DEFAULT_TASK_NAME
)
238 'Cannot remove the task function used as the default task function'
241 return this.taskFunctions
.delete(name
)
245 * Lists the names of the worker's task functions.
247 * @returns The names of the worker's task functions.
249 public listTaskFunctions (): string[] {
250 return Array.from(this.taskFunctions
.keys())
254 * Sets the default task function to use in the worker.
256 * @param name - The name of the task function to use as default task function.
257 * @returns Whether the default task function was set or not.
258 * @throws {@link https://nodejs.org/api/errors.html#class-typeerror} If the `name` parameter is not a string.
259 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is the default task function reserved name.
260 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the `name` parameter is a non-existing task function.
262 public setDefaultTaskFunction (name
: string): boolean {
263 if (typeof name
!== 'string') {
264 throw new TypeError('name parameter is not a string')
266 if (name
=== DEFAULT_TASK_NAME
) {
268 'Cannot set the default task function reserved name as the default task function'
271 if (!this.taskFunctions
.has(name
)) {
273 'Cannot set the default task function to a non-existing task function'
277 this.taskFunctions
.set(
279 this.taskFunctions
.get(name
) as WorkerFunction
<Data
, Response
>
288 * Handles the ready message sent by the main worker.
290 * @param message - The ready message.
292 protected abstract handleReadyMessage (message
: MessageValue
<Data
>): void
295 * Worker message listener.
297 * @param message - The received message.
299 protected messageListener (message
: MessageValue
<Data
>): void {
300 if (message
.workerId
=== this.id
) {
301 if (message
.statistics
!= null) {
302 // Statistics message received
303 this.statistics
= message
.statistics
304 } else if (message
.checkActive
!= null) {
305 // Check active message received
306 !this.isMain
&& message
.checkActive
307 ? this.startCheckActive()
308 : this.stopCheckActive()
309 } else if (message
.id
!= null && message
.data
!= null) {
310 // Task message received
312 } else if (message
.kill
=== true) {
313 // Kill message received
314 this.handleKillMessage(message
)
320 * Handles a kill message sent by the main worker.
322 * @param message - The kill message.
324 protected handleKillMessage (message
: MessageValue
<Data
>): void {
325 !this.isMain
&& this.stopCheckActive()
330 * Starts the worker check active interval.
332 private startCheckActive (): void {
333 this.lastTaskTimestamp
= performance
.now()
334 this.activeInterval
= setInterval(
335 this.checkActive
.bind(this),
336 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
) / 2
338 this.activeInterval
.unref()
342 * Stops the worker check active interval.
344 private stopCheckActive (): void {
345 if (this.activeInterval
!= null) {
346 clearInterval(this.activeInterval
)
347 delete this.activeInterval
352 * Checks if the worker should be terminated, because its living too long.
354 private checkActive (): void {
356 performance
.now() - this.lastTaskTimestamp
>
357 (this.opts
.maxInactiveTime
?? DEFAULT_MAX_INACTIVE_TIME
)
359 this.sendToMainWorker({ kill
: this.opts
.killBehavior
, workerId
: this.id
})
364 * Returns the main worker.
366 * @returns Reference to the main worker.
368 protected getMainWorker (): MainWorker
{
369 if (this.mainWorker
== null) {
370 throw new Error('Main worker not set')
372 return this.mainWorker
376 * Sends a message to main worker.
378 * @param message - The response message.
380 protected abstract sendToMainWorker (
381 message
: MessageValue
<Response
, Data
>
385 * Handles an error and convert it to a string so it can be sent back to the main worker.
387 * @param e - The error raised by the worker.
388 * @returns The error message.
390 protected handleError (e
: Error | string): string {
391 return e
instanceof Error ? e
.message
: e
395 * Runs the given task.
397 * @param task - The task to execute.
398 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found.
400 protected run (task
: Task
<Data
>): void {
402 throw new Error('Cannot run a task in the main worker')
404 const fn
= this.getTaskFunction(task
.name
)
405 if (isAsyncFunction(fn
)) {
406 this.runInAsyncScope(this.runAsync
.bind(this), this, fn
, task
)
408 this.runInAsyncScope(this.runSync
.bind(this), this, fn
, task
)
413 * Runs the given task function synchronously.
415 * @param fn - Task function that will be executed.
416 * @param task - Input data for the task function.
419 fn
: WorkerSyncFunction
<Data
, Response
>,
423 let taskPerformance
= this.beginTaskPerformance(task
.name
)
424 const res
= fn(task
.data
)
425 taskPerformance
= this.endTaskPerformance(taskPerformance
)
426 this.sendToMainWorker({
433 const errorMessage
= this.handleError(e
as Error | string)
434 this.sendToMainWorker({
436 name
: task
.name
?? DEFAULT_TASK_NAME
,
437 message
: errorMessage
,
444 this.updateLastTaskTimestamp()
449 * Runs the given task function asynchronously.
451 * @param fn - Task function that will be executed.
452 * @param task - Input data for the task function.
455 fn
: WorkerAsyncFunction
<Data
, Response
>,
458 let taskPerformance
= this.beginTaskPerformance(task
.name
)
461 taskPerformance
= this.endTaskPerformance(taskPerformance
)
462 this.sendToMainWorker({
471 const errorMessage
= this.handleError(e
as Error | string)
472 this.sendToMainWorker({
474 name
: task
.name
?? DEFAULT_TASK_NAME
,
475 message
: errorMessage
,
483 this.updateLastTaskTimestamp()
485 .catch(EMPTY_FUNCTION
)
489 * Gets the task function with the given name.
491 * @param name - Name of the task function that will be returned.
492 * @returns The task function.
493 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the task function is not found.
495 private getTaskFunction (name
?: string): WorkerFunction
<Data
, Response
> {
496 name
= name
?? DEFAULT_TASK_NAME
497 const fn
= this.taskFunctions
.get(name
)
499 throw new Error(`Task function '${name}' not found`)
504 private beginTaskPerformance (name
?: string): TaskPerformance
{
505 this.checkStatistics()
507 name
: name
?? DEFAULT_TASK_NAME
,
508 timestamp
: performance
.now(),
509 ...(this.statistics
.elu
&& { elu
: performance
.eventLoopUtilization() })
513 private endTaskPerformance (
514 taskPerformance
: TaskPerformance
516 this.checkStatistics()
519 ...(this.statistics
.runTime
&& {
520 runTime
: performance
.now() - taskPerformance
.timestamp
522 ...(this.statistics
.elu
&& {
523 elu
: performance
.eventLoopUtilization(taskPerformance
.elu
)
528 private checkStatistics (): void {
529 if (this.statistics
== null) {
530 throw new Error('Performance statistics computation requirements not set')
534 private updateLastTaskTimestamp (): void {
535 if (!this.isMain
&& this.activeInterval
!= null) {
536 this.lastTaskTimestamp
= performance
.now()