1 import cluster
, { type Worker
} from
'node:cluster'
3 import type { MessageValue
} from
'../utility-types.js'
4 import { AbstractWorker
} from
'./abstract-worker.js'
5 import type { TaskFunction
, TaskFunctions
} from
'./task-functions.js'
6 import type { WorkerOptions
} from
'./worker-options.js'
9 * A cluster worker used by a poolifier `ClusterPool`.
11 * When this worker is inactive for more than the given `maxInactiveTime`,
12 * it will send a termination request to its main worker.
14 * If you use a `DynamicClusterPool` the extra workers that were created will be terminated,
15 * but the minimum number of workers will be guaranteed.
17 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
18 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data.
19 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
22 export class ClusterWorker
<
25 > extends AbstractWorker
<Worker
, Data
, Response
> {
27 * Constructs a new poolifier cluster worker.
29 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
30 * @param opts - Options for the worker.
33 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>,
34 opts
: WorkerOptions
= {}
36 super(cluster
.isPrimary
, cluster
.worker
, taskFunctions
, opts
)
40 protected handleReadyMessage (message
: MessageValue
<Data
>): void {
41 if (message
.workerId
=== this.id
&& message
.ready
=== false) {
43 this.getMainWorker().on('message', this.messageListener
.bind(this))
44 this.sendToMainWorker({
46 taskFunctionsProperties
: this.listTaskFunctionsProperties()
49 this.sendToMainWorker({
51 taskFunctionsProperties
: this.listTaskFunctionsProperties()
58 protected get
id (): number {
59 return this.getMainWorker().id
63 protected readonly sendToMainWorker
= (
64 message
: MessageValue
<Response
>
66 this.getMainWorker().send({
69 } satisfies MessageValue
<Response
>)