1 import cluster
, { type ClusterSettings
, type Worker
} from
'node:cluster'
2 import type { MessageValue
} from
'../../utility-types'
3 import { AbstractPool
} from
'../abstract-pool'
13 * Options for a poolifier cluster pool.
15 export interface ClusterPoolOptions
extends PoolOptions
<Worker
> {
17 * Key/value pairs to add to worker process environment.
19 * @see https://nodejs.org/api/cluster.html#cluster_cluster_fork_env
21 // eslint-disable-next-line @typescript-eslint/no-explicit-any
26 * @see https://nodejs.org/api/cluster.html#cluster_cluster_settings
28 settings
?: ClusterSettings
32 * A cluster pool with a fixed number of workers.
34 * It is possible to perform tasks in sync or asynchronous mode as you prefer.
36 * This pool selects the workers in a round robin fashion.
38 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
39 * @typeParam Response - Type of execution response. This can only be serializable data.
40 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
43 export class FixedClusterPool
<
46 > extends AbstractPool
<Worker
, Data
, Response
> {
48 * Constructs a new poolifier fixed cluster pool.
50 * @param numberOfWorkers - Number of workers for this pool.
51 * @param filePath - Path to an implementation of a `ClusterWorker` file, which can be relative or absolute.
52 * @param opts - Options for this fixed cluster pool.
55 numberOfWorkers
: number,
57 protected readonly opts
: ClusterPoolOptions
= {}
59 super(numberOfWorkers
, filePath
, opts
)
63 protected setupHook (): void {
64 cluster
.setupPrimary({ ...this.opts
.settings
, exec
: this.filePath
})
68 protected isMain (): boolean {
69 return cluster
.isPrimary
73 protected destroyWorker (worker
: Worker
): void {
74 this.sendToWorker(worker
, { kill
: 1 })
79 protected sendToWorker (worker
: Worker
, message
: MessageValue
<Data
>): void {
84 protected registerWorkerMessageListener
<Message
extends Data
| Response
>(
86 listener
: (message
: MessageValue
<Message
>) => void
88 worker
.on('message', listener
)
92 protected createWorker (): Worker
{
93 return cluster
.fork(this.opts
.env
)
97 protected afterWorkerSetup (worker
: Worker
): void {
98 // Listen to worker messages.
99 this.registerWorkerMessageListener(worker
, super.workerListener())
103 protected get
type (): PoolType
{
104 return PoolTypes
.fixed
108 protected get
worker (): WorkerType
{
109 return WorkerTypes
.cluster
113 protected get
minSize (): number {
114 return this.numberOfWorkers
118 protected get
maxSize (): number {
119 return this.numberOfWorkers
123 protected get
busy (): boolean {
124 return this.internalBusy()