Commit | Line | Data |
---|---|---|
c32882b0 | 1 | import { DynamicThreadPool, PoolOptions } from 'poolifier'; |
a4624c96 | 2 | |
a4624c96 | 3 | import Utils from '../utils/Utils'; |
c32882b0 | 4 | import { Worker } from 'worker_threads'; |
fd1fdf1b | 5 | import WorkerAbstract from './WorkerAbstract'; |
a4624c96 | 6 | import { WorkerData } from '../types/Worker'; |
7874b0b1 | 7 | import { WorkerUtils } from './WorkerUtils'; |
a4624c96 | 8 | |
fd1fdf1b | 9 | export default class WorkerDynamicPool<T> extends WorkerAbstract { |
8df3f0a9 | 10 | private pool: DynamicThreadPool<WorkerData>; |
a4624c96 JB |
11 | |
12 | /** | |
13 | * Create a new `WorkerDynamicPool`. | |
14 | * | |
15 | * @param {string} workerScript | |
e71cccf3 JB |
16 | * @param {number} min |
17 | * @param {number} max | |
322c9192 | 18 | * @param {number} workerStartDelay |
9efbac5b | 19 | * @param {PoolOptions} opts |
a4624c96 | 20 | */ |
9efbac5b | 21 | constructor(workerScript: string, min: number, max: number, workerStartDelay?: number, opts?: PoolOptions<Worker>) { |
322c9192 | 22 | super(workerScript, workerStartDelay); |
8df3f0a9 JB |
23 | opts.exitHandler = opts?.exitHandler ?? WorkerUtils.defaultExitHandler; |
24 | this.pool = new DynamicThreadPool<WorkerData>(min, max, this.workerScript, opts); | |
a4624c96 JB |
25 | } |
26 | ||
27 | get size(): number { | |
28 | return this.pool.workers.length; | |
29 | } | |
30 | ||
6e0964c8 | 31 | get maxElementsPerWorker(): number | null { |
85f78bc0 | 32 | return null; |
a4624c96 JB |
33 | } |
34 | ||
35 | /** | |
36 | * | |
3340259a | 37 | * @returns {Promise<void>} |
a4624c96 JB |
38 | * @public |
39 | */ | |
40 | // eslint-disable-next-line @typescript-eslint/no-empty-function | |
8df3f0a9 | 41 | public async start(): Promise<void> {} |
a4624c96 | 42 | |
ded13d97 JB |
43 | /** |
44 | * | |
3340259a | 45 | * @returns {Promise<void>} |
ded13d97 JB |
46 | * @public |
47 | */ | |
fd1fdf1b | 48 | // eslint-disable-next-line @typescript-eslint/require-await |
ded13d97 JB |
49 | public async stop(): Promise<void> { |
50 | return this.pool.destroy(); | |
51 | } | |
52 | ||
a4624c96 JB |
53 | /** |
54 | * | |
6e0964c8 | 55 | * @param {T} elementData |
3340259a | 56 | * @returns {Promise<void>} |
a4624c96 JB |
57 | * @public |
58 | */ | |
8434025b | 59 | public async addElement(elementData: T): Promise<void> { |
a4624c96 JB |
60 | await this.pool.execute(elementData); |
61 | // Start worker sequentially to optimize memory at startup | |
322c9192 | 62 | await Utils.sleep(this.workerStartDelay); |
a4624c96 JB |
63 | } |
64 | } |