1 import type { Worker
} from
'cluster'
2 import cluster from
'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-internal'
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 * A cluster pool with a fixed number of workers.
24 * It is possible to perform tasks in sync or asynchronous mode as you prefer.
26 * This pool selects the workers in a round robin fashion.
28 * @template DataType of data sent to the worker. This can only be serializable data.
29 * @template ResponseType of response of execution. This can only be serializable data.
30 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
33 export class FixedClusterPool
<
36 > extends AbstractPool
<Worker
, Data
, Response
> {
38 * Constructs a new poolifier fixed cluster pool.
40 * @param numberOfWorkers Number of workers for this pool.
41 * @param filePath Path to an implementation of a `ClusterWorker` file, which can be relative or absolute.
42 * @param [opts={}] Options for this fixed cluster pool.
45 numberOfWorkers
: number,
47 public readonly opts
: ClusterPoolOptions
= {}
49 super(numberOfWorkers
, filePath
, opts
)
53 protected setupHook (): void {
54 cluster
.setupPrimary({
60 protected isMain (): boolean {
61 return cluster
.isPrimary
65 public destroyWorker (worker
: Worker
): void {
66 this.sendToWorker(worker
, { kill
: 1 })
71 protected sendToWorker (worker
: Worker
, message
: MessageValue
<Data
>): void {
76 public registerWorkerMessageListener
<Message
extends Data
| Response
> (
78 listener
: (message
: MessageValue
<Message
>) => void
80 worker
.on('message', listener
)
84 protected createWorker (): Worker
{
85 return cluster
.fork(this.opts
.env
)
89 protected afterWorkerSetup (worker
: Worker
): void {
90 // Listen worker messages.
91 this.registerWorkerMessageListener(worker
, super.workerListener())
95 public get
type (): PoolType
{
100 public get
busy (): boolean {
101 return this.internalGetBusyStatus()