a88197f715bdd2c2a129638d3960dce9d9ac8420
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 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
34 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
35 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
38 export class FixedClusterPool
<
41 > extends AbstractPool
<Worker
, Data
, Response
> {
43 * Constructs a new poolifier fixed cluster pool.
45 * @param numberOfWorkers - Number of workers for this pool.
46 * @param filePath - Path to an implementation of a `ClusterWorker` file, which can be relative or absolute.
47 * @param opts - Options for this fixed cluster pool.
50 numberOfWorkers
: number,
52 protected readonly opts
: ClusterPoolOptions
= {}
54 super(numberOfWorkers
, filePath
, opts
)
58 protected setupHook (): void {
59 cluster
.setupPrimary({ ...this.opts
.settings
, exec
: this.filePath
})
63 protected isMain (): boolean {
64 return cluster
.isPrimary
68 protected destroyWorker (worker
: Worker
): void {
69 this.sendToWorker(worker
, { kill
: 1 })
70 worker
.on('disconnect', () => {
77 protected sendToWorker (worker
: Worker
, message
: MessageValue
<Data
>): void {
82 protected createWorker (): Worker
{
83 return cluster
.fork(this.opts
.env
)
87 protected get
type (): PoolType
{
88 return PoolTypes
.fixed
92 protected get
worker (): WorkerType
{
93 return WorkerTypes
.cluster
97 protected get
minSize (): number {
98 return this.numberOfWorkers
102 protected get
maxSize (): number {
103 return this.numberOfWorkers
107 protected get
busy (): boolean {
108 return this.internalBusy()