| 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'; |
| 7 | import { defaultErrorHandler, defaultExitHandler } from './WorkerUtils'; |
| 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(workerScript: string, workerOptions: WorkerOptions) { |
| 24 | if (workerScript === null || workerScript === undefined) { |
| 25 | throw new Error('Worker script is not defined'); |
| 26 | } |
| 27 | if (typeof workerScript === 'string' && workerScript.trim().length === 0) { |
| 28 | throw new Error('Worker script is empty'); |
| 29 | } |
| 30 | if (!existsSync(workerScript)) { |
| 31 | throw new Error('Worker script file does not exist'); |
| 32 | } |
| 33 | this.workerScript = workerScript; |
| 34 | this.workerOptions = workerOptions; |
| 35 | this.workerOptions.poolOptions!.errorHandler = |
| 36 | this.workerOptions.poolOptions?.errorHandler ?? defaultErrorHandler; |
| 37 | this.workerOptions.poolOptions!.exitHandler = |
| 38 | this.workerOptions.poolOptions?.exitHandler ?? defaultExitHandler; |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Starts the worker pool/set. |
| 43 | */ |
| 44 | public abstract start(): Promise<void>; |
| 45 | /** |
| 46 | * Stops the worker pool/set. |
| 47 | */ |
| 48 | public abstract stop(): Promise<void>; |
| 49 | /** |
| 50 | * Adds a task element to the worker pool/set. |
| 51 | * |
| 52 | * @param elementData - |
| 53 | */ |
| 54 | public abstract addElement(elementData: T): Promise<void>; |
| 55 | } |