fix: properly handle dynamic pool with zero minimum size
[poolifier.git] / src / pools / thread / dynamic.ts
CommitLineData
d35e5717
JB
1import { PoolEvents, type PoolType, PoolTypes } from '../pool.js'
2import { checkDynamicPoolSize } from '../utils.js'
3import { FixedThreadPool, type ThreadPoolOptions } from './fixed.js'
f045358d 4
4ade5f1f 5/**
729c563d 6 * A thread pool with a dynamic number of threads, but a guaranteed minimum number of threads.
4ade5f1f 7 *
729c563d 8 * This thread pool creates new threads when the others are busy, up to the maximum number of threads.
9cd39dd4 9 * 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`.
729c563d 10 *
e102732c
JB
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.
4ade5f1f
S
13 * @author [Alessandro Pio Ardizio](https://github.com/pioardi)
14 * @since 0.0.1
15 */
60fbd6d6 16export class DynamicThreadPool<
deb85c12
JB
17 Data = unknown,
18 Response = unknown
4ade5f1f 19> extends FixedThreadPool<Data, Response> {
4ade5f1f 20 /**
729c563d
S
21 * Constructs a new poolifier dynamic thread pool.
22 *
38e795c1
JB
23 * @param min - Minimum number of threads which are always active.
24 * @param max - Maximum number of threads that can be created by this pool.
25 * @param filePath - Path to an implementation of a `ThreadWorker` file, which can be relative or absolute.
26 * @param opts - Options for this dynamic thread pool.
4ade5f1f
S
27 */
28 public constructor (
c97c7edb 29 min: number,
26ce26ca 30 max: number,
31b90205 31 filePath: string,
2889bd70 32 opts: ThreadPoolOptions = {}
4ade5f1f 33 ) {
26ce26ca
JB
34 super(min, filePath, opts, max)
35 checkDynamicPoolSize(
36 this.minimumNumberOfWorkers,
67f3f2d6
JB
37 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
38 this.maximumNumberOfWorkers!
26ce26ca 39 )
4ade5f1f
S
40 }
41
9d9fb7b6
JB
42 /** @inheritDoc */
43 protected shallCreateDynamicWorker (): boolean {
e44639e9
JB
44 return (
45 (!this.full && this.internalBusy()) ||
46 (this.minimumNumberOfWorkers === 0 && this.workerNodes.length === 0)
47 )
9d9fb7b6
JB
48 }
49
d0878034
JB
50 /** @inheritDoc */
51 protected checkAndEmitDynamicWorkerCreationEvents (): void {
52 if (this.full) {
53 this.emitter?.emit(PoolEvents.full, this.info)
54 }
55 }
56
afc003b2 57 /** @inheritDoc */
8881ae32 58 protected get type (): PoolType {
6b27d407 59 return PoolTypes.dynamic
7c0ba920
JB
60 }
61
afc003b2 62 /** @inheritDoc */
c319c66b 63 protected get busy (): boolean {
0527b6db 64 return this.full && this.internalBusy()
c2ade475 65 }
4ade5f1f 66}