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 * This pool selects the workers in a round robin fashion.
37 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
38 * @typeParam Response - Type of execution response. This can only be serializable data.
39 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
42 export class FixedClusterPool
<
45 > extends AbstractPool
<Worker
, Data
, Response
> {
47 * Constructs a new poolifier fixed cluster pool.
49 * @param numberOfWorkers - Number of workers for this pool.
50 * @param filePath - Path to an implementation of a `ClusterWorker` file, which can be relative or absolute.
51 * @param opts - Options for this fixed cluster pool.
54 numberOfWorkers
: number,
56 protected readonly opts
: ClusterPoolOptions
= {}
58 super(numberOfWorkers
, filePath
, opts
)
62 protected setupHook (): void {
63 cluster
.setupPrimary({ ...this.opts
.settings
, exec
: this.filePath
})
67 protected isMain (): boolean {
68 return cluster
.isPrimary
72 protected destroyWorker (worker
: Worker
): void {
73 this.sendToWorker(worker
, { kill
: 1 })
78 protected sendToWorker (worker
: Worker
, message
: MessageValue
<Data
>): void {
83 protected registerWorkerMessageListener
<Message
extends Data
| Response
>(
85 listener
: (message
: MessageValue
<Message
>) => void
87 worker
.on('message', listener
)
91 protected createWorker (): Worker
{
92 return cluster
.fork(this.opts
.env
)
96 protected afterWorkerSetup (worker
: Worker
): void {
97 // Listen to worker messages.
98 this.registerWorkerMessageListener(worker
, super.workerListener())
102 protected get
type (): PoolType
{
103 return PoolTypes
.fixed
107 protected get
worker (): WorkerType
{
108 return WorkerTypes
.cluster
112 protected get
minSize (): number {
113 return this.numberOfWorkers
117 protected get
maxSize (): number {
118 return this.numberOfWorkers
122 protected get
busy (): boolean {
123 return this.internalBusy()