| 1 | import type { EventEmitterAsyncResource } from 'node:events' |
| 2 | import { existsSync } from 'node:fs' |
| 3 | |
| 4 | import type { PoolInfo } from 'poolifier' |
| 5 | |
| 6 | import type { SetInfo, WorkerData, WorkerOptions } from './WorkerTypes.js' |
| 7 | |
| 8 | export abstract class WorkerAbstract<D extends WorkerData, R extends WorkerData> { |
| 9 | protected readonly workerScript: string |
| 10 | protected readonly workerOptions: WorkerOptions |
| 11 | public abstract readonly info: PoolInfo | SetInfo |
| 12 | public abstract readonly size: number |
| 13 | public abstract readonly maxElementsPerWorker: number | undefined |
| 14 | public abstract readonly emitter: EventEmitterAsyncResource | undefined |
| 15 | |
| 16 | /** |
| 17 | * `WorkerAbstract` constructor. |
| 18 | * |
| 19 | * @param workerScript - |
| 20 | * @param workerOptions - |
| 21 | */ |
| 22 | constructor (workerScript: string | undefined, workerOptions: WorkerOptions) { |
| 23 | if (workerScript == null) { |
| 24 | throw new TypeError('Worker script is not defined') |
| 25 | } |
| 26 | if (typeof workerScript !== 'string') { |
| 27 | throw new TypeError('Worker script must be a string') |
| 28 | } |
| 29 | if (workerScript.trim().length === 0) { |
| 30 | throw new Error('Worker script is an empty string') |
| 31 | } |
| 32 | if (!existsSync(workerScript)) { |
| 33 | throw new Error('Worker script file does not exist') |
| 34 | } |
| 35 | this.workerScript = workerScript |
| 36 | this.workerOptions = workerOptions |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * Starts the worker pool/set. |
| 41 | */ |
| 42 | public abstract start (): void | Promise<void> |
| 43 | /** |
| 44 | * Stops the worker pool/set. |
| 45 | */ |
| 46 | public abstract stop (): Promise<void> |
| 47 | /** |
| 48 | * Adds a task element to the worker pool/set. |
| 49 | * |
| 50 | * @param elementData - |
| 51 | */ |
| 52 | public abstract addElement (elementData: D): Promise<R> |
| 53 | } |