| 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 pool: DynamicThreadPool<WorkerData>; |
| 11 | |
| 12 | /** |
| 13 | * Create a new `WorkerDynamicPool`. |
| 14 | * |
| 15 | * @param {string} workerScript |
| 16 | * @param {number} min |
| 17 | * @param {number} max |
| 18 | * @param {number} workerStartDelay |
| 19 | * @param {PoolOptions} 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 {Promise<void>} |
| 38 | * @public |
| 39 | */ |
| 40 | // eslint-disable-next-line @typescript-eslint/no-empty-function |
| 41 | public async start(): Promise<void> {} |
| 42 | |
| 43 | /** |
| 44 | * |
| 45 | * @returns {Promise<void>} |
| 46 | * @public |
| 47 | */ |
| 48 | // eslint-disable-next-line @typescript-eslint/require-await |
| 49 | public async stop(): Promise<void> { |
| 50 | return this.pool.destroy(); |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * |
| 55 | * @param {T} elementData |
| 56 | * @returns {Promise<void>} |
| 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 | } |