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 env
?: Record
<string, unknown
>
25 * @see https://nodejs.org/api/cluster.html#cluster_cluster_settings
27 settings
?: ClusterSettings
31 * A cluster pool with a fixed number of workers.
33 * It is possible to perform tasks in sync or asynchronous mode as you prefer.
35 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
36 * @typeParam Response - Type of execution response. This can only be serializable data.
37 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
40 export class FixedClusterPool
<
43 > extends AbstractPool
<Worker
, Data
, Response
> {
45 * Constructs a new poolifier fixed cluster pool.
47 * @param numberOfWorkers - Number of workers for this pool.
48 * @param filePath - Path to an implementation of a `ClusterWorker` file, which can be relative or absolute.
49 * @param opts - Options for this fixed cluster pool.
52 numberOfWorkers
: number,
54 protected readonly opts
: ClusterPoolOptions
= {}
56 super(numberOfWorkers
, filePath
, opts
)
60 protected setupHook (): void {
61 cluster
.setupPrimary({ ...this.opts
.settings
, exec
: this.filePath
})
65 protected isMain (): boolean {
66 return cluster
.isPrimary
70 protected destroyWorker (worker
: Worker
): void {
71 this.sendToWorker(worker
, { kill
: 1 })
76 protected sendToWorker (worker
: Worker
, message
: MessageValue
<Data
>): void {
81 protected registerWorkerMessageListener
<Message
extends Data
| Response
>(
83 listener
: (message
: MessageValue
<Message
>) => void
85 worker
.on('message', listener
)
89 protected createWorker (): Worker
{
90 return cluster
.fork(this.opts
.env
)
94 protected afterWorkerSetup (worker
: Worker
): void {
95 // Listen to worker messages.
96 this.registerWorkerMessageListener(worker
, super.workerListener())
100 protected get
type (): PoolType
{
101 return PoolTypes
.fixed
105 protected get
worker (): WorkerType
{
106 return WorkerTypes
.cluster
110 protected get
minSize (): number {
111 return this.numberOfWorkers
115 protected get
maxSize (): number {
116 return this.numberOfWorkers
120 protected get
busy (): boolean {
121 return this.internalBusy()