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