| 1 | import type EventEmitterAsyncResource from 'node:events'; |
| 2 | import fs from 'node:fs'; |
| 3 | |
| 4 | import type { PoolInfo } from 'poolifier'; |
| 5 | |
| 6 | import { WorkerConstants } from './WorkerConstants'; |
| 7 | import type { SetInfo, WorkerData, WorkerOptions } from './WorkerTypes'; |
| 8 | |
| 9 | export abstract class WorkerAbstract<T extends WorkerData> { |
| 10 | protected readonly workerScript: string; |
| 11 | protected readonly workerOptions: WorkerOptions; |
| 12 | public abstract readonly info: PoolInfo | SetInfo; |
| 13 | public abstract readonly size: number; |
| 14 | public abstract readonly maxElementsPerWorker: number | undefined; |
| 15 | public abstract readonly emitter: EventEmitterAsyncResource | undefined; |
| 16 | |
| 17 | /** |
| 18 | * `WorkerAbstract` constructor. |
| 19 | * |
| 20 | * @param workerScript - |
| 21 | * @param workerOptions - |
| 22 | */ |
| 23 | constructor( |
| 24 | workerScript: string, |
| 25 | workerOptions: WorkerOptions = { |
| 26 | workerStartDelay: WorkerConstants.DEFAULT_WORKER_START_DELAY, |
| 27 | elementStartDelay: WorkerConstants.DEFAULT_ELEMENT_START_DELAY, |
| 28 | poolMinSize: WorkerConstants.DEFAULT_POOL_MIN_SIZE, |
| 29 | poolMaxSize: WorkerConstants.DEFAULT_POOL_MAX_SIZE, |
| 30 | elementsPerWorker: WorkerConstants.DEFAULT_ELEMENTS_PER_WORKER, |
| 31 | poolOptions: {}, |
| 32 | messageHandler: WorkerConstants.EMPTY_FUNCTION, |
| 33 | } |
| 34 | ) { |
| 35 | if (workerScript === null || workerScript === undefined) { |
| 36 | throw new Error('Worker script is not defined'); |
| 37 | } |
| 38 | if (typeof workerScript === 'string' && workerScript.trim().length === 0) { |
| 39 | throw new Error('Worker script is empty'); |
| 40 | } |
| 41 | if (!fs.existsSync(workerScript)) { |
| 42 | throw new Error('Worker script file does not exist'); |
| 43 | } |
| 44 | this.workerScript = workerScript; |
| 45 | this.workerOptions = workerOptions; |
| 46 | } |
| 47 | |
| 48 | /** |
| 49 | * Start the worker pool/set. |
| 50 | */ |
| 51 | public abstract start(): Promise<void>; |
| 52 | /** |
| 53 | * Stop the worker pool/set. |
| 54 | */ |
| 55 | public abstract stop(): Promise<void>; |
| 56 | /** |
| 57 | * Add a task element to the worker pool/set. |
| 58 | * |
| 59 | * @param elementData - |
| 60 | */ |
| 61 | public abstract addElement(elementData: T): Promise<void>; |
| 62 | } |