Commit | Line | Data |
---|---|---|
4d7227e6 | 1 | import { DynamicThreadPool } from 'poolifier'; |
8114d10e JB |
2 | |
3 | import { WorkerData, WorkerOptions } from '../types/Worker'; | |
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); | |
e7aeea18 JB |
19 | this.workerOptions.poolOptions.exitHandler = |
20 | this.workerOptions?.poolOptions?.exitHandler ?? WorkerUtils.defaultExitHandler; | |
21 | this.pool = new DynamicThreadPool<WorkerData>( | |
22 | this.workerOptions.poolMinSize, | |
23 | this.workerOptions.poolMaxSize, | |
24 | this.workerScript, | |
25 | this.workerOptions.poolOptions | |
26 | ); | |
a4624c96 JB |
27 | } |
28 | ||
29 | get size(): number { | |
30 | return this.pool.workers.length; | |
31 | } | |
32 | ||
6e0964c8 | 33 | get maxElementsPerWorker(): number | null { |
85f78bc0 | 34 | return null; |
a4624c96 JB |
35 | } |
36 | ||
37 | /** | |
38 | * | |
81797102 | 39 | * @returns |
a4624c96 JB |
40 | * @public |
41 | */ | |
6c3cfef8 JB |
42 | public async start(): Promise<void> { |
43 | // This is intentional | |
44 | } | |
a4624c96 | 45 | |
ded13d97 JB |
46 | /** |
47 | * | |
81797102 | 48 | * @returns |
ded13d97 JB |
49 | * @public |
50 | */ | |
51 | public async stop(): Promise<void> { | |
52 | return this.pool.destroy(); | |
53 | } | |
54 | ||
a4624c96 JB |
55 | /** |
56 | * | |
81797102 JB |
57 | * @param elementData |
58 | * @returns | |
a4624c96 JB |
59 | * @public |
60 | */ | |
c3ee95af | 61 | public async addElement(elementData: WorkerData): Promise<void> { |
a4624c96 | 62 | await this.pool.execute(elementData); |
4bfd80fa | 63 | // Start element sequentially to optimize memory at startup |
e7aeea18 JB |
64 | this.workerOptions.elementStartDelay > 0 && |
65 | (await Utils.sleep(this.workerOptions.elementStartDelay)); | |
a4624c96 JB |
66 | } |
67 | } |