b0a22346690bd36c471b6b45c844af8ffae098ea
[poolifier.git] / src / pools / thread / dynamic.ts
1 import { type Worker } from 'node:worker_threads'
2 import { type PoolOptions, type PoolType, PoolTypes } from '../pool'
3 import { checkDynamicPoolSize } from '../utils'
4 import { FixedThreadPool } from './fixed'
5
6 /**
7 * A thread pool with a dynamic number of threads, but a guaranteed minimum number of threads.
8 *
9 * This thread pool creates new threads when the others are busy, up to the maximum number of threads.
10 * When the maximum number of threads 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 [Alessandro Pio Ardizio](https://github.com/pioardi)
15 * @since 0.0.1
16 */
17 export class DynamicThreadPool<
18 Data = unknown,
19 Response = unknown
20 > extends FixedThreadPool<Data, Response> {
21 /**
22 * Constructs a new poolifier dynamic thread pool.
23 *
24 * @param min - Minimum number of threads which are always active.
25 * @param max - Maximum number of threads that can be created by this pool.
26 * @param filePath - Path to an implementation of a `ThreadWorker` file, which can be relative or absolute.
27 * @param opts - Options for this dynamic thread pool.
28 */
29 public constructor (
30 min: number,
31 max: number,
32 filePath: string,
33 opts: PoolOptions<Worker> = {}
34 ) {
35 super(min, filePath, opts, max)
36 checkDynamicPoolSize(
37 this.minimumNumberOfWorkers,
38 this.maximumNumberOfWorkers as number
39 )
40 }
41
42 /** @inheritDoc */
43 protected get type (): PoolType {
44 return PoolTypes.dynamic
45 }
46
47 /** @inheritDoc */
48 protected get busy (): boolean {
49 return this.full && this.internalBusy()
50 }
51 }