a88197f715bdd2c2a129638d3960dce9d9ac8420
[poolifier.git] / src / pools / cluster / fixed.ts
1 import cluster, { type ClusterSettings, type Worker } from 'node:cluster'
2 import type { MessageValue } from '../../utility-types'
3 import { AbstractPool } from '../abstract-pool'
4 import {
5 type PoolOptions,
6 type PoolType,
7 PoolTypes,
8 type WorkerType,
9 WorkerTypes
10 } from '../pool'
11
12 /**
13 * Options for a poolifier cluster pool.
14 */
15 export interface ClusterPoolOptions extends PoolOptions<Worker> {
16 /**
17 * Key/value pairs to add to worker process environment.
18 *
19 * @see https://nodejs.org/api/cluster.html#cluster_cluster_fork_env
20 */
21 env?: Record<string, unknown>
22 /**
23 * Cluster settings.
24 *
25 * @see https://nodejs.org/api/cluster.html#cluster_cluster_settings
26 */
27 settings?: ClusterSettings
28 }
29
30 /**
31 * A cluster pool with a fixed number of workers.
32 *
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)
36 * @since 2.0.0
37 */
38 export class FixedClusterPool<
39 Data = unknown,
40 Response = unknown
41 > extends AbstractPool<Worker, Data, Response> {
42 /**
43 * Constructs a new poolifier fixed cluster pool.
44 *
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.
48 */
49 public constructor (
50 numberOfWorkers: number,
51 filePath: string,
52 protected readonly opts: ClusterPoolOptions = {}
53 ) {
54 super(numberOfWorkers, filePath, opts)
55 }
56
57 /** @inheritDoc */
58 protected setupHook (): void {
59 cluster.setupPrimary({ ...this.opts.settings, exec: this.filePath })
60 }
61
62 /** @inheritDoc */
63 protected isMain (): boolean {
64 return cluster.isPrimary
65 }
66
67 /** @inheritDoc */
68 protected destroyWorker (worker: Worker): void {
69 this.sendToWorker(worker, { kill: 1 })
70 worker.on('disconnect', () => {
71 worker.kill()
72 })
73 worker.disconnect()
74 }
75
76 /** @inheritDoc */
77 protected sendToWorker (worker: Worker, message: MessageValue<Data>): void {
78 worker.send(message)
79 }
80
81 /** @inheritDoc */
82 protected createWorker (): Worker {
83 return cluster.fork(this.opts.env)
84 }
85
86 /** @inheritDoc */
87 protected get type (): PoolType {
88 return PoolTypes.fixed
89 }
90
91 /** @inheritDoc */
92 protected get worker (): WorkerType {
93 return WorkerTypes.cluster
94 }
95
96 /** @inheritDoc */
97 protected get minSize (): number {
98 return this.numberOfWorkers
99 }
100
101 /** @inheritDoc */
102 protected get maxSize (): number {
103 return this.numberOfWorkers
104 }
105
106 /** @inheritDoc */
107 protected get busy (): boolean {
108 return this.internalBusy()
109 }
110 }