refactor: move worker setup into worker node constructor
[poolifier.git] / src / pools / cluster / dynamic.ts
1 import { type Worker } from 'node:cluster'
2 import { type PoolOptions, type PoolType, PoolTypes } from '../pool'
3 import { checkDynamicPoolSize } from '../utils'
4 import { FixedClusterPool } from './fixed'
5
6 /**
7 * A cluster pool with a dynamic number of workers, but a guaranteed minimum number of workers.
8 *
9 * This cluster pool creates new workers when the others are busy, up to the maximum number of workers.
10 * When the maximum number of workers is reached and workers are busy, an event is emitted. If you want to listen to this event, use the pool's `emitter`.
11 *
12 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
13 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
14 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
15 * @since 2.0.0
16 */
17 export class DynamicClusterPool<
18 Data = unknown,
19 Response = unknown
20 > extends FixedClusterPool<Data, Response> {
21 /**
22 * Constructs a new poolifier dynamic cluster pool.
23 *
24 * @param min - Minimum number of workers which are always active.
25 * @param max - Maximum number of workers that can be created by this pool.
26 * @param filePath - Path to an implementation of a `ClusterWorker` file, which can be relative or absolute.
27 * @param opts - Options for this dynamic cluster pool.
28 */
29 public constructor (
30 min: number,
31 protected readonly max: number,
32 filePath: string,
33 opts: PoolOptions<Worker> = {}
34 ) {
35 super(min, filePath, opts)
36 checkDynamicPoolSize(this.numberOfWorkers, this.max)
37 }
38
39 /** @inheritDoc */
40 protected get type (): PoolType {
41 return PoolTypes.dynamic
42 }
43
44 /** @inheritDoc */
45 protected get busy (): boolean {
46 return this.full && this.internalBusy()
47 }
48 }