build: make eslint configuration use strict type checking
[poolifier.git] / src / pools / thread / dynamic.ts
1 import { PoolEvents, type PoolType, PoolTypes } from '../pool.js'
2 import { checkDynamicPoolSize } from '../utils.js'
3 import { FixedThreadPool, type ThreadPoolOptions } from './fixed.js'
4
5 /**
6 * A thread pool with a dynamic number of threads, but a guaranteed minimum number of threads.
7 *
8 * This thread pool creates new threads when the others are busy, up to the maximum number of threads.
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`.
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 [Alessandro Pio Ardizio](https://github.com/pioardi)
14 * @since 0.0.1
15 */
16 export class DynamicThreadPool<
17 Data = unknown,
18 Response = unknown
19 > extends FixedThreadPool<Data, Response> {
20 /**
21 * Constructs a new poolifier dynamic thread pool.
22 *
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.
27 */
28 public constructor (
29 min: number,
30 max: number,
31 filePath: string,
32 opts: ThreadPoolOptions = {}
33 ) {
34 super(min, filePath, opts, max)
35 checkDynamicPoolSize(
36 this.minimumNumberOfWorkers,
37 this.maximumNumberOfWorkers
38 )
39 }
40
41 /** @inheritDoc */
42 protected shallCreateDynamicWorker (): boolean {
43 return (
44 (!this.full && this.internalBusy()) ||
45 (this.minimumNumberOfWorkers === 0 && this.workerNodes.length === 0)
46 )
47 }
48
49 /** @inheritDoc */
50 protected checkAndEmitDynamicWorkerCreationEvents (): void {
51 if (this.full) {
52 this.emitter?.emit(PoolEvents.full, this.info)
53 }
54 }
55
56 /** @inheritDoc */
57 protected get type (): PoolType {
58 return PoolTypes.dynamic
59 }
60
61 /** @inheritDoc */
62 protected get busy (): boolean {
63 return this.full && this.internalBusy()
64 }
65 }