Commit | Line | Data |
---|---|---|
66a7748d | 1 | import type { EventEmitterAsyncResource } from 'node:events' |
2b59e7f7 | 2 | |
66a7748d | 3 | import { DynamicThreadPool, type PoolInfo } from 'poolifier' |
8114d10e | 4 | |
66a7748d | 5 | import type { WorkerData, WorkerOptions } from './WorkerTypes.js' |
0749233f JB |
6 | |
7 | import { WorkerAbstract } from './WorkerAbstract.js' | |
66a7748d | 8 | import { randomizeDelay, sleep } from './WorkerUtils.js' |
a4624c96 | 9 | |
3b09e788 | 10 | export class WorkerDynamicPool<D extends WorkerData, R extends WorkerData> extends WorkerAbstract< |
d1f5bfd8 JB |
11 | D, |
12 | R | |
3b09e788 JB |
13 | > { |
14 | private readonly pool: DynamicThreadPool<D, R> | |
a4624c96 JB |
15 | |
16 | /** | |
361c98f5 | 17 | * Creates a new `WorkerDynamicPool`. |
0e4fa348 JB |
18 | * @param workerScript - |
19 | * @param workerOptions - | |
a4624c96 | 20 | */ |
66a7748d JB |
21 | constructor (workerScript: string, workerOptions: WorkerOptions) { |
22 | super(workerScript, workerOptions) | |
3b09e788 | 23 | this.pool = new DynamicThreadPool<D, R>( |
e7aeea18 JB |
24 | this.workerOptions.poolMinSize, |
25 | this.workerOptions.poolMaxSize, | |
26 | this.workerScript, | |
66a7748d JB |
27 | this.workerOptions.poolOptions |
28 | ) | |
a4624c96 JB |
29 | } |
30 | ||
0749233f JB |
31 | /** @inheritDoc */ |
32 | public async addElement (elementData: D): Promise<R> { | |
33 | const response = await this.pool.execute(elementData) | |
34 | // Start element sequentially to optimize memory at startup | |
35 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
36 | this.workerOptions.elementAddDelay! > 0 && | |
37 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
38 | (await sleep(randomizeDelay(this.workerOptions.elementAddDelay!))) | |
39 | return response | |
b779c0f8 JB |
40 | } |
41 | ||
0749233f JB |
42 | /** @inheritDoc */ |
43 | public start (): void { | |
44 | this.pool.start() | |
a4624c96 JB |
45 | } |
46 | ||
0749233f JB |
47 | /** @inheritDoc */ |
48 | public async stop (): Promise<void> { | |
49 | await this.pool.destroy() | |
a4624c96 JB |
50 | } |
51 | ||
66a7748d | 52 | get emitter (): EventEmitterAsyncResource | undefined { |
5199f9fd | 53 | return this.pool.emitter |
962a8159 JB |
54 | } |
55 | ||
0749233f JB |
56 | get info (): PoolInfo { |
57 | return this.pool.info | |
6c3cfef8 | 58 | } |
a4624c96 | 59 | |
0749233f JB |
60 | get maxElementsPerWorker (): number | undefined { |
61 | return undefined | |
ded13d97 JB |
62 | } |
63 | ||
0749233f JB |
64 | get size (): number { |
65 | return this.pool.info.workerNodes | |
a4624c96 JB |
66 | } |
67 | } |