Commit | Line | Data |
---|---|---|
a4624c96 JB |
1 | import { DynamicThreadPool, DynamicThreadPoolOptions } from 'poolifier'; |
2 | ||
3 | import Constants from '../utils/Constants'; | |
4 | import Utils from '../utils/Utils'; | |
5 | import { WorkerData } from '../types/Worker'; | |
6 | import Wrk from './Wrk'; | |
a4624c96 JB |
7 | |
8 | export default class WorkerDynamicPool extends Wrk { | |
9 | private pool: DynamicPool; | |
10 | ||
11 | /** | |
12 | * Create a new `WorkerDynamicPool`. | |
13 | * | |
14 | * @param {string} workerScript | |
15 | */ | |
16 | constructor(workerScript: string, min: number, max: number,) { | |
17 | super(workerScript); | |
18 | this.pool = DynamicPool.getInstance(min, max, this.workerScript); | |
19 | } | |
20 | ||
21 | get size(): number { | |
22 | return this.pool.workers.length; | |
23 | } | |
24 | ||
25 | get maxElementsPerWorker(): number { | |
26 | return 1; | |
27 | } | |
28 | ||
29 | /** | |
30 | * | |
31 | * @return {Promise<void>} | |
32 | * @public | |
33 | */ | |
34 | // eslint-disable-next-line @typescript-eslint/no-empty-function | |
35 | public async start(): Promise<void> { } | |
36 | ||
37 | /** | |
38 | * | |
39 | * @return {Promise<void>} | |
40 | * @public | |
41 | */ | |
42 | public async addElement(elementData: WorkerData): Promise<void> { | |
43 | await this.pool.execute(elementData); | |
44 | // Start worker sequentially to optimize memory at startup | |
45 | await Utils.sleep(Constants.START_WORKER_DELAY); | |
46 | } | |
47 | } | |
48 | ||
49 | class DynamicPool extends DynamicThreadPool<WorkerData> { | |
50 | private static instance: DynamicPool; | |
51 | ||
52 | private constructor(min: number, max: number, filename: string, opts?: DynamicThreadPoolOptions) { | |
53 | super(min, max, filename, opts); | |
54 | } | |
55 | ||
56 | public static getInstance(min: number, max: number, filename: string): DynamicPool { | |
57 | if (!DynamicPool.instance) { | |
58 | DynamicPool.instance = new DynamicPool(min, max, filename, | |
59 | { | |
60 | exitHandler: (code) => { | |
61 | if (code !== 0) { | |
1e924543 | 62 | console.error(`Worker stopped with exit code ${code}`); |
a4624c96 JB |
63 | } |
64 | } | |
65 | } | |
66 | ); | |
67 | } | |
68 | return DynamicPool.instance; | |
69 | } | |
70 | } |