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