1 import cluster
, { type Worker
} from
'node:cluster'
3 import type { MessageValue
} from
'../../utility-types.js'
4 import { AbstractPool
} from
'../abstract-pool.js'
5 import { type PoolOptions
, type PoolType
, PoolTypes
} from
'../pool.js'
6 import { type WorkerType
, WorkerTypes
} from
'../worker.js'
9 * Options for a poolifier cluster pool.
11 export type ClusterPoolOptions
= PoolOptions
<Worker
>
14 * A cluster pool with a fixed number of workers.
16 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
17 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
18 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
21 export class FixedClusterPool
<
24 > extends AbstractPool
<Worker
, Data
, Response
> {
26 * Constructs a new poolifier fixed cluster pool.
28 * @param numberOfWorkers - Number of workers for this pool.
29 * @param filePath - Path to an implementation of a `ClusterWorker` file, which can be relative or absolute.
30 * @param opts - Options for this fixed cluster pool.
33 numberOfWorkers
: number,
35 opts
: ClusterPoolOptions
= {},
36 maximumNumberOfWorkers
?: number
38 super(numberOfWorkers
, filePath
, opts
, maximumNumberOfWorkers
)
42 protected setupHook (): void {
43 cluster
.setupPrimary({ ...this.opts
.settings
, exec
: this.filePath
})
47 protected isMain (): boolean {
48 return cluster
.isPrimary
52 protected sendToWorker (
53 workerNodeKey
: number,
54 message
: MessageValue
<Data
>
56 this.workerNodes
[workerNodeKey
]?.worker
.send({
58 workerId
: this.getWorkerInfo(workerNodeKey
)?.id
59 } satisfies MessageValue
<Data
>)
63 protected sendStartupMessageToWorker (workerNodeKey
: number): void {
64 this.sendToWorker(workerNodeKey
, {
70 protected registerWorkerMessageListener
<Message
extends Data
| Response
>(
71 workerNodeKey
: number,
72 listener
: (message
: MessageValue
<Message
>) => void
74 this.workerNodes
[workerNodeKey
].worker
.on('message', listener
)
78 protected registerOnceWorkerMessageListener
<Message
extends Data
| Response
>(
79 workerNodeKey
: number,
80 listener
: (message
: MessageValue
<Message
>) => void
82 this.workerNodes
[workerNodeKey
].worker
.once('message', listener
)
86 protected deregisterWorkerMessageListener
<Message
extends Data
| Response
>(
87 workerNodeKey
: number,
88 listener
: (message
: MessageValue
<Message
>) => void
90 this.workerNodes
[workerNodeKey
].worker
.off('message', listener
)
94 protected shallCreateDynamicWorker (): boolean {
99 protected checkAndEmitDynamicWorkerCreationEvents (): void {
104 protected get
type (): PoolType
{
105 return PoolTypes
.fixed
109 protected get
worker (): WorkerType
{
110 return WorkerTypes
.cluster
114 protected get
busy (): boolean {
115 return this.internalBusy()