1 import cluster
, { type Worker
} from
'node:cluster'
2 import type { MessageValue
} from
'../utility-types'
3 import { AbstractWorker
} from
'./abstract-worker'
4 import type { WorkerOptions
} from
'./worker-options'
5 import type { TaskFunction
, TaskFunctions
} from
'./task-functions'
8 * A cluster worker used by a poolifier `ClusterPool`.
10 * When this worker is inactive for more than the given `maxInactiveTime`,
11 * it will send a termination request to its main worker.
13 * If you use a `DynamicClusterPool` the extra workers that were created will be terminated,
14 * but the minimum number of workers will be guaranteed.
16 * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data.
17 * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data.
18 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
21 export class ClusterWorker
<
24 > extends AbstractWorker
<Worker
, Data
, Response
> {
26 * Constructs a new poolifier cluster worker.
28 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
29 * @param opts - Options for the worker.
32 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>,
33 opts
: WorkerOptions
= {}
36 'worker-cluster-pool:poolifier',
38 cluster
.worker
as Worker
,
45 protected handleReadyMessage (message
: MessageValue
<Data
>): void {
46 if (message
.workerId
=== this.id
&& message
.ready
=== false) {
48 this.getMainWorker().on('message', this.messageListener
.bind(this))
49 this.sendToMainWorker({
51 taskFunctionNames
: this.listTaskFunctionNames()
54 this.sendToMainWorker({
56 taskFunctionNames
: this.listTaskFunctionNames()
63 protected get
id (): number {
64 return this.getMainWorker().id
68 protected sendToMainWorker (message
: MessageValue
<Response
>): void {
69 this.getMainWorker().send({ ...message
, workerId
: this.id
})