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