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'
5 import type { PoolOptions
} from
'../pool'
6 import { PoolType
} from
'../pool'
9 * Options for a poolifier cluster pool.
11 export interface ClusterPoolOptions
extends PoolOptions
<Worker
> {
13 * Key/value pairs to add to worker process environment.
15 * @see https://nodejs.org/api/cluster.html#cluster_cluster_fork_env
17 // eslint-disable-next-line @typescript-eslint/no-explicit-any
22 * @see https://nodejs.org/api/cluster.html#cluster_cluster_settings
24 settings
?: ClusterSettings
28 * A cluster pool with a fixed number of workers.
30 * It is possible to perform tasks in sync or asynchronous mode as you prefer.
32 * This pool selects the workers in a round robin fashion.
34 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
35 * @typeParam Response - Type of response of execution. This can only be serializable data.
36 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
39 export class FixedClusterPool
<
42 > extends AbstractPool
<Worker
, Data
, Response
> {
44 * Constructs a new poolifier fixed cluster pool.
46 * @param numberOfWorkers - Number of workers for this pool.
47 * @param filePath - Path to an implementation of a `ClusterWorker` file, which can be relative or absolute.
48 * @param opts - Options for this fixed cluster pool.
51 numberOfWorkers
: number,
53 public readonly opts
: ClusterPoolOptions
= {}
55 super(numberOfWorkers
, filePath
, opts
)
59 protected setupHook (): void {
60 cluster
.setupPrimary({ ...this.opts
.settings
, exec
: this.filePath
})
64 protected isMain (): boolean {
65 return cluster
.isPrimary
69 protected destroyWorker (worker
: Worker
): void {
70 this.sendToWorker(worker
, { kill
: 1 })
75 protected sendToWorker (worker
: Worker
, message
: MessageValue
<Data
>): void {
80 protected registerWorkerMessageListener
<Message
extends Data
| Response
>(
82 listener
: (message
: MessageValue
<Message
>) => void
84 worker
.on('message', listener
)
88 protected createWorker (): Worker
{
89 return cluster
.fork(this.opts
.env
)
93 protected afterWorkerSetup (worker
: Worker
): void {
94 // Listen to worker messages.
95 this.registerWorkerMessageListener(worker
, super.workerListener())
99 public get
type (): PoolType
{
100 return PoolType
.FIXED
104 protected get
full (): boolean {
105 return this.workerNodes
.length
=== this.numberOfWorkers
109 protected get
busy (): boolean {
110 return this.internalBusy()