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