refactor: move worker setup into worker node constructor
[poolifier.git] / src / pools / cluster / dynamic.ts
CommitLineData
c3719753
JB
1import { type Worker } from 'node:cluster'
2import { type PoolOptions, type PoolType, PoolTypes } from '../pool'
bde6b5d7 3import { checkDynamicPoolSize } from '../utils'
c3719753 4import { FixedClusterPool } from './fixed'
f045358d 5
4ade5f1f 6/**
729c563d 7 * A cluster pool with a dynamic number of workers, but a guaranteed minimum number of workers.
4ade5f1f 8 *
729c563d 9 * This cluster pool creates new workers when the others are busy, up to the maximum number of workers.
9cd39dd4 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`.
729c563d 11 *
e102732c
JB
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.
325f50bc
S
14 * @author [Christopher Quadflieg](https://github.com/Shinigami92)
15 * @since 2.0.0
4ade5f1f 16 */
325f50bc 17export class DynamicClusterPool<
deb85c12
JB
18 Data = unknown,
19 Response = unknown
325f50bc 20> extends FixedClusterPool<Data, Response> {
4ade5f1f 21 /**
729c563d
S
22 * Constructs a new poolifier dynamic cluster pool.
23 *
38e795c1
JB
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.
4ade5f1f
S
28 */
29 public constructor (
c97c7edb 30 min: number,
b4213b7f 31 protected readonly max: number,
31b90205 32 filePath: string,
c3719753 33 opts: PoolOptions<Worker> = {}
4ade5f1f 34 ) {
31b90205 35 super(min, filePath, opts)
bde6b5d7 36 checkDynamicPoolSize(this.numberOfWorkers, this.max)
4ade5f1f
S
37 }
38
afc003b2 39 /** @inheritDoc */
8881ae32 40 protected get type (): PoolType {
6b27d407 41 return PoolTypes.dynamic
7c0ba920
JB
42 }
43
afc003b2 44 /** @inheritDoc */
c319c66b 45 protected get busy (): boolean {
0527b6db 46 return this.full && this.internalBusy()
c2ade475 47 }
4ade5f1f 48}