Commit | Line | Data |
---|---|---|
d972af76 | 1 | import { DynamicThreadPool, type PoolEmitter, type PoolInfo } from 'poolifier'; |
8114d10e | 2 | |
268a74bb JB |
3 | import { WorkerAbstract } from './WorkerAbstract'; |
4 | import type { WorkerData, WorkerOptions } from './WorkerTypes'; | |
ab93b184 | 5 | import { randomizeDelay, sleep } from './WorkerUtils'; |
a4624c96 | 6 | |
268a74bb | 7 | export class WorkerDynamicPool extends WorkerAbstract<WorkerData> { |
f2bf9948 | 8 | private readonly pool: DynamicThreadPool<WorkerData>; |
a4624c96 JB |
9 | |
10 | /** | |
361c98f5 | 11 | * Creates a new `WorkerDynamicPool`. |
a4624c96 | 12 | * |
0e4fa348 JB |
13 | * @param workerScript - |
14 | * @param workerOptions - | |
a4624c96 | 15 | */ |
4a3807d1 | 16 | constructor(workerScript: string, workerOptions: WorkerOptions) { |
4d7227e6 | 17 | super(workerScript, workerOptions); |
e7aeea18 JB |
18 | this.pool = new DynamicThreadPool<WorkerData>( |
19 | this.workerOptions.poolMinSize, | |
20 | this.workerOptions.poolMaxSize, | |
21 | this.workerScript, | |
5edd8ba0 | 22 | this.workerOptions.poolOptions, |
e7aeea18 | 23 | ); |
a4624c96 JB |
24 | } |
25 | ||
b779c0f8 JB |
26 | get info(): PoolInfo { |
27 | return this.pool.info; | |
28 | } | |
29 | ||
a4624c96 | 30 | get size(): number { |
b779c0f8 | 31 | return this.pool.info.workerNodes; |
a4624c96 JB |
32 | } |
33 | ||
72092cfc JB |
34 | get maxElementsPerWorker(): number | undefined { |
35 | return undefined; | |
a4624c96 JB |
36 | } |
37 | ||
d972af76 | 38 | get emitter(): PoolEmitter | undefined { |
962a8159 JB |
39 | return this.pool?.emitter; |
40 | } | |
41 | ||
8baf3f8f | 42 | /** @inheritDoc */ |
6c3cfef8 JB |
43 | public async start(): Promise<void> { |
44 | // This is intentional | |
45 | } | |
a4624c96 | 46 | |
8baf3f8f | 47 | /** @inheritDoc */ |
ded13d97 JB |
48 | public async stop(): Promise<void> { |
49 | return this.pool.destroy(); | |
50 | } | |
51 | ||
8baf3f8f | 52 | /** @inheritDoc */ |
c3ee95af | 53 | public async addElement(elementData: WorkerData): Promise<void> { |
a4624c96 | 54 | await this.pool.execute(elementData); |
4bfd80fa | 55 | // Start element sequentially to optimize memory at startup |
e1d9a0f4 | 56 | this.workerOptions.elementStartDelay! > 0 && |
ab93b184 | 57 | (await sleep(randomizeDelay(this.workerOptions.elementStartDelay!))); |
a4624c96 JB |
58 | } |
59 | } |