| 1 | import { DynamicThreadPool, PoolOptions } from 'poolifier'; |
| 2 | |
| 3 | import Utils from '../utils/Utils'; |
| 4 | import { Worker } from 'worker_threads'; |
| 5 | import WorkerAbstract from './WorkerAbstract'; |
| 6 | import { WorkerData } from '../types/Worker'; |
| 7 | import { WorkerUtils } from './WorkerUtils'; |
| 8 | |
| 9 | export default class WorkerDynamicPool<T> extends WorkerAbstract { |
| 10 | private readonly pool: DynamicThreadPool<WorkerData>; |
| 11 | |
| 12 | /** |
| 13 | * Create a new `WorkerDynamicPool`. |
| 14 | * |
| 15 | * @param workerScript |
| 16 | * @param min |
| 17 | * @param max |
| 18 | * @param workerStartDelay |
| 19 | * @param opts |
| 20 | */ |
| 21 | constructor(workerScript: string, min: number, max: number, workerStartDelay?: number, opts?: PoolOptions<Worker>) { |
| 22 | super(workerScript, workerStartDelay); |
| 23 | opts.exitHandler = opts?.exitHandler ?? WorkerUtils.defaultExitHandler; |
| 24 | this.pool = new DynamicThreadPool<WorkerData>(min, max, this.workerScript, opts); |
| 25 | } |
| 26 | |
| 27 | get size(): number { |
| 28 | return this.pool.workers.length; |
| 29 | } |
| 30 | |
| 31 | get maxElementsPerWorker(): number | null { |
| 32 | return null; |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * |
| 37 | * @returns |
| 38 | * @public |
| 39 | */ |
| 40 | public async start(): Promise<void> { |
| 41 | // This is intentional |
| 42 | } |
| 43 | |
| 44 | /** |
| 45 | * |
| 46 | * @returns |
| 47 | * @public |
| 48 | */ |
| 49 | public async stop(): Promise<void> { |
| 50 | return this.pool.destroy(); |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * |
| 55 | * @param elementData |
| 56 | * @returns |
| 57 | * @public |
| 58 | */ |
| 59 | public async addElement(elementData: T): Promise<void> { |
| 60 | await this.pool.execute(elementData); |
| 61 | // Start worker sequentially to optimize memory at startup |
| 62 | await Utils.sleep(this.workerStartDelay); |
| 63 | } |
| 64 | } |