e01e54e5f64e1b48b9d328e7d08c71ff100cee6e
1 import cluster
, { type Worker
} from
'node:cluster'
3 import type { MessageValue
} from
'../utility-types.js'
4 import type { TaskFunction
, TaskFunctions
} from
'./task-functions.js'
5 import type { WorkerOptions
} from
'./worker-options.js'
7 import { AbstractWorker
} from
'./abstract-worker.js'
10 * A cluster worker used by a poolifier `ClusterPool`.
12 * When this worker is inactive for more than the given `maxInactiveTime`,
13 * it will send a termination request to its main worker.
15 * If you use a `DynamicClusterPool` the extra workers that were created will be terminated,
16 * 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 protected readonly sendToMainWorker
= (
28 message
: MessageValue
<Response
>
30 this.getMainWorker().send({
33 } satisfies MessageValue
<Response
>)
37 * Constructs a new poolifier cluster worker.
38 * @param taskFunctions - Task function(s) processed by the worker when the pool's `execute` method is invoked.
39 * @param opts - Options for the worker.
42 taskFunctions
: TaskFunction
<Data
, Response
> | TaskFunctions
<Data
, Response
>,
43 opts
: WorkerOptions
= {}
45 super(cluster
.isPrimary
, cluster
.worker
, taskFunctions
, opts
)
49 protected handleReadyMessage (message
: MessageValue
<Data
>): void {
50 if (message
.workerId
=== this.id
&& message
.ready
=== false) {
52 this.getMainWorker().on('message', this.messageListener
.bind(this))
53 this.sendToMainWorker({
55 taskFunctionsProperties
: this.listTaskFunctionsProperties(),
58 this.sendToMainWorker({
60 taskFunctionsProperties
: this.listTaskFunctionsProperties(),
67 protected get
id (): number {
68 return this.getMainWorker().id