1 import cluster
, { type Worker
} from
'node:cluster'
2 import type { MessageValue
} from
'../../utility-types'
3 import { AbstractPool
} from
'../abstract-pool'
4 import { type PoolOptions
, type PoolType
, PoolTypes
} from
'../pool'
5 import { type WorkerType
, WorkerTypes
} from
'../worker'
8 * Options for a poolifier cluster pool.
10 export type ClusterPoolOptions
= PoolOptions
<Worker
>
13 * A cluster pool with a fixed number of workers.
15 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
16 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
17 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
20 export class FixedClusterPool
<
23 > extends AbstractPool
<Worker
, Data
, Response
> {
25 * Constructs a new poolifier fixed cluster pool.
27 * @param numberOfWorkers - Number of workers for this pool.
28 * @param filePath - Path to an implementation of a `ClusterWorker` file, which can be relative or absolute.
29 * @param opts - Options for this fixed cluster pool.
32 numberOfWorkers
: number,
34 opts
: ClusterPoolOptions
= {},
35 maximumNumberOfWorkers
?: number
37 super(numberOfWorkers
, filePath
, opts
, maximumNumberOfWorkers
)
41 protected setupHook (): void {
42 cluster
.setupPrimary({ ...this.opts
.settings
, exec
: this.filePath
})
46 protected isMain (): boolean {
47 return cluster
.isPrimary
51 protected sendToWorker (
52 workerNodeKey
: number,
53 message
: MessageValue
<Data
>
55 this.workerNodes
[workerNodeKey
].worker
.send({
57 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number
62 protected sendStartupMessageToWorker (workerNodeKey
: number): void {
63 this.sendToWorker(workerNodeKey
, {
69 protected registerWorkerMessageListener
<Message
extends Data
| Response
>(
70 workerNodeKey
: number,
71 listener
: (message
: MessageValue
<Message
>) => void
73 this.workerNodes
[workerNodeKey
].worker
.on('message', listener
)
77 protected registerOnceWorkerMessageListener
<Message
extends Data
| Response
>(
78 workerNodeKey
: number,
79 listener
: (message
: MessageValue
<Message
>) => void
81 this.workerNodes
[workerNodeKey
].worker
.once('message', listener
)
85 protected deregisterWorkerMessageListener
<Message
extends Data
| Response
>(
86 workerNodeKey
: number,
87 listener
: (message
: MessageValue
<Message
>) => void
89 this.workerNodes
[workerNodeKey
].worker
.off('message', listener
)
93 protected shallCreateDynamicWorker (): boolean {
98 protected checkAndEmitDynamicWorkerCreationEvents (): void {}
101 protected get
type (): PoolType
{
102 return PoolTypes
.fixed
106 protected get
worker (): WorkerType
{
107 return WorkerTypes
.cluster
111 protected get
busy (): boolean {
112 return this.internalBusy()