1 import type { ClusterSettings
, Worker
} from
'node:cluster'
2 import cluster from
'node:cluster'
3 import type { MessageValue
} from
'../../utility-types'
4 import { AbstractPool
} from
'../abstract-pool'
14 * Options for a poolifier cluster pool.
16 export interface ClusterPoolOptions
extends PoolOptions
<Worker
> {
18 * Key/value pairs to add to worker process environment.
20 * @see https://nodejs.org/api/cluster.html#cluster_cluster_fork_env
22 // eslint-disable-next-line @typescript-eslint/no-explicit-any
27 * @see https://nodejs.org/api/cluster.html#cluster_cluster_settings
29 settings
?: ClusterSettings
33 * A cluster pool with a fixed number of workers.
35 * It is possible to perform tasks in sync or asynchronous mode as you prefer.
37 * This pool selects the workers in a round robin fashion.
39 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
40 * @typeParam Response - Type of execution response. This can only be serializable data.
41 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
44 export class FixedClusterPool
<
47 > extends AbstractPool
<Worker
, Data
, Response
> {
49 * Constructs a new poolifier fixed cluster pool.
51 * @param numberOfWorkers - Number of workers for this pool.
52 * @param filePath - Path to an implementation of a `ClusterWorker` file, which can be relative or absolute.
53 * @param opts - Options for this fixed cluster pool.
56 numberOfWorkers
: number,
58 public readonly opts
: ClusterPoolOptions
= {}
60 super(numberOfWorkers
, filePath
, opts
)
64 protected setupHook (): void {
65 cluster
.setupPrimary({ ...this.opts
.settings
, exec
: this.filePath
})
69 protected isMain (): boolean {
70 return cluster
.isPrimary
74 protected destroyWorker (worker
: Worker
): void {
75 this.sendToWorker(worker
, { kill
: 1 })
80 protected sendToWorker (worker
: Worker
, message
: MessageValue
<Data
>): void {
85 protected registerWorkerMessageListener
<Message
extends Data
| Response
>(
87 listener
: (message
: MessageValue
<Message
>) => void
89 worker
.on('message', listener
)
93 protected createWorker (): Worker
{
94 return cluster
.fork(this.opts
.env
)
98 protected afterWorkerSetup (worker
: Worker
): void {
99 // Listen to worker messages.
100 this.registerWorkerMessageListener(worker
, super.workerListener())
104 public get
type (): PoolType
{
105 return PoolTypes
.fixed
109 protected get
worker (): WorkerType
{
110 return WorkerTypes
.cluster
114 protected get
minSize (): number {
115 return this.numberOfWorkers
119 protected get
maxSize (): number {
120 return this.numberOfWorkers
124 protected get
full (): boolean {
125 return this.workerNodes
.length
>= this.numberOfWorkers
129 protected get
busy (): boolean {
130 return this.internalBusy()