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