1 import { fork
, isMaster
, setupMaster
, Worker
} from
'cluster'
2 import type { MessageValue
} from
'../../utility-types'
3 import type { PoolOptions
} from
'../abstract-pool'
4 import { AbstractPool
} from
'../abstract-pool'
5 import { PoolType
} from
'../pool-internal'
8 * Options for a poolifier cluster pool.
10 export interface ClusterPoolOptions
extends PoolOptions
<Worker
> {
12 * Key/value pairs to add to worker process environment.
14 * @see https://nodejs.org/api/cluster.html#cluster_cluster_fork_env
16 // eslint-disable-next-line @typescript-eslint/no-explicit-any
21 * A cluster pool with a fixed number of workers.
23 * It is possible to perform tasks in sync or asynchronous mode as you prefer.
25 * This pool selects the workers in a round robin fashion.
27 * @template Data Type of data sent to the worker. This can only be serializable data.
28 * @template Response Type 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. Default: `{}`
45 numberOfWorkers
: number,
47 public readonly opts
: ClusterPoolOptions
= {}
49 super(numberOfWorkers
, filePath
, opts
)
52 protected setupHook (): void {
58 protected isMain (): boolean {
63 public destroyWorker (worker
: Worker
): void {
64 this.sendToWorker(worker
, { kill
: 1 })
68 protected sendToWorker (worker
: Worker
, message
: MessageValue
<Data
>): void {
73 public registerWorkerMessageListener
<Message
extends Data
| Response
> (
75 listener
: (message
: MessageValue
<Message
>) => void
77 worker
.on('message', listener
)
80 protected createWorker (): Worker
{
81 return fork(this.opts
.env
)
84 protected afterWorkerSetup (worker
: Worker
): void {
85 // Listen worker messages.
86 this.registerWorkerMessageListener(worker
, super.workerListener())
90 public get
type (): PoolType
{
95 public get
busy (): boolean {
96 return this.internalGetBusyStatus()