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