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 | * | |
81797102 JB |
15 | * @param workerScript |
16 | * @param min | |
17 | * @param max | |
18 | * @param workerStartDelay | |
19 | * @param opts | |
a4624c96 | 20 | */ |
ffd71f2c JB |
21 | constructor(workerScript: string, min: number, max: number, workerStartDelay?: number, opts?: PoolOptions<Worker>) { |
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 | * | |
81797102 | 37 | * @returns |
a4624c96 JB |
38 | * @public |
39 | */ | |
40 | // eslint-disable-next-line @typescript-eslint/no-empty-function | |
6c3cfef8 JB |
41 | public async start(): Promise<void> { |
42 | // This is intentional | |
43 | } | |
a4624c96 | 44 | |
ded13d97 JB |
45 | /** |
46 | * | |
81797102 | 47 | * @returns |
ded13d97 JB |
48 | * @public |
49 | */ | |
50 | public async stop(): Promise<void> { | |
51 | return this.pool.destroy(); | |
52 | } | |
53 | ||
a4624c96 JB |
54 | /** |
55 | * | |
81797102 JB |
56 | * @param elementData |
57 | * @returns | |
a4624c96 JB |
58 | * @public |
59 | */ | |
8434025b | 60 | public async addElement(elementData: T): Promise<void> { |
a4624c96 JB |
61 | await this.pool.execute(elementData); |
62 | // Start worker sequentially to optimize memory at startup | |
322c9192 | 63 | await Utils.sleep(this.workerStartDelay); |
a4624c96 JB |
64 | } |
65 | } |