Commit | Line | Data |
---|---|---|
4d7227e6 | 1 | import { WorkerData, WorkerOptions } from '../types/Worker'; |
a4624c96 | 2 | |
4d7227e6 | 3 | import { DynamicThreadPool } from 'poolifier'; |
a4624c96 | 4 | import Utils from '../utils/Utils'; |
fd1fdf1b | 5 | import WorkerAbstract from './WorkerAbstract'; |
7874b0b1 | 6 | import { WorkerUtils } from './WorkerUtils'; |
a4624c96 | 7 | |
c3ee95af | 8 | export default class WorkerDynamicPool extends WorkerAbstract<WorkerData> { |
f2bf9948 | 9 | private readonly pool: DynamicThreadPool<WorkerData>; |
a4624c96 JB |
10 | |
11 | /** | |
12 | * Create a new `WorkerDynamicPool`. | |
13 | * | |
81797102 | 14 | * @param workerScript |
4d7227e6 | 15 | * @param workerOptions |
a4624c96 | 16 | */ |
4d7227e6 JB |
17 | constructor(workerScript: string, workerOptions?: WorkerOptions) { |
18 | super(workerScript, workerOptions); | |
57678745 | 19 | this.workerOptions.poolOptions.exitHandler = this.workerOptions?.poolOptions?.exitHandler ?? WorkerUtils.defaultExitHandler; |
4d7227e6 | 20 | this.pool = new DynamicThreadPool<WorkerData>(this.workerOptions.poolMinSize, this.workerOptions.poolMaxSize, this.workerScript, this.workerOptions.poolOptions); |
a4624c96 JB |
21 | } |
22 | ||
23 | get size(): number { | |
24 | return this.pool.workers.length; | |
25 | } | |
26 | ||
6e0964c8 | 27 | get maxElementsPerWorker(): number | null { |
85f78bc0 | 28 | return null; |
a4624c96 JB |
29 | } |
30 | ||
31 | /** | |
32 | * | |
81797102 | 33 | * @returns |
a4624c96 JB |
34 | * @public |
35 | */ | |
6c3cfef8 JB |
36 | public async start(): Promise<void> { |
37 | // This is intentional | |
38 | } | |
a4624c96 | 39 | |
ded13d97 JB |
40 | /** |
41 | * | |
81797102 | 42 | * @returns |
ded13d97 JB |
43 | * @public |
44 | */ | |
45 | public async stop(): Promise<void> { | |
46 | return this.pool.destroy(); | |
47 | } | |
48 | ||
a4624c96 JB |
49 | /** |
50 | * | |
81797102 JB |
51 | * @param elementData |
52 | * @returns | |
a4624c96 JB |
53 | * @public |
54 | */ | |
c3ee95af | 55 | public async addElement(elementData: WorkerData): Promise<void> { |
a4624c96 | 56 | await this.pool.execute(elementData); |
4bfd80fa | 57 | // Start element sequentially to optimize memory at startup |
4d7227e6 | 58 | this.workerOptions.elementStartDelay > 0 && await Utils.sleep(this.workerOptions.elementStartDelay); |
a4624c96 JB |
59 | } |
60 | } |