Commit | Line | Data |
---|---|---|
962a8159 | 1 | import type EventEmitterAsyncResource from 'node:events'; |
0e4fa348 | 2 | |
be245fda | 3 | import { FixedThreadPool, type PoolInfo } from 'poolifier'; |
8114d10e | 4 | |
268a74bb JB |
5 | import { WorkerAbstract } from './WorkerAbstract'; |
6 | import type { WorkerData, WorkerOptions } from './WorkerTypes'; | |
be245fda | 7 | import { sleep } from './WorkerUtils'; |
a4624c96 | 8 | |
268a74bb | 9 | export class WorkerStaticPool extends WorkerAbstract<WorkerData> { |
f2bf9948 | 10 | private readonly pool: FixedThreadPool<WorkerData>; |
a4624c96 JB |
11 | |
12 | /** | |
13 | * Create a new `WorkerStaticPool`. | |
14 | * | |
0e4fa348 JB |
15 | * @param workerScript - |
16 | * @param workerOptions - | |
a4624c96 | 17 | */ |
4d7227e6 JB |
18 | constructor(workerScript: string, workerOptions?: WorkerOptions) { |
19 | super(workerScript, workerOptions); | |
e7aeea18 JB |
20 | this.pool = new FixedThreadPool( |
21 | this.workerOptions.poolMaxSize, | |
22 | this.workerScript, | |
23 | this.workerOptions.poolOptions | |
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 | ||
962a8159 JB |
39 | get emitter(): EventEmitterAsyncResource | undefined { |
40 | return this.pool?.emitter; | |
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 |
789871d6 | 57 | this.workerOptions.elementStartDelay > 0 && (await sleep(this.workerOptions.elementStartDelay)); |
a4624c96 JB |
58 | } |
59 | } |