Commit | Line | Data |
---|---|---|
38b2428f | 1 | import type { EventEmitterAsyncResource } from 'node:events'; |
d972af76 | 2 | import { existsSync } from 'node:fs'; |
4bfd80fa | 3 | |
2b59e7f7 | 4 | import type { PoolInfo } from 'poolifier'; |
b779c0f8 | 5 | |
a6ef1ece JB |
6 | import type { SetInfo, WorkerData, WorkerOptions } from './WorkerTypes.js'; |
7 | import { defaultErrorHandler, defaultExitHandler } from './WorkerUtils.js'; | |
7dde0b73 | 8 | |
268a74bb | 9 | export abstract class WorkerAbstract<T extends WorkerData> { |
322c9192 | 10 | protected readonly workerScript: string; |
4d7227e6 | 11 | protected readonly workerOptions: WorkerOptions; |
b779c0f8 | 12 | public abstract readonly info: PoolInfo | SetInfo; |
f2bf9948 | 13 | public abstract readonly size: number; |
72092cfc | 14 | public abstract readonly maxElementsPerWorker: number | undefined; |
38b2428f | 15 | public abstract readonly emitter: EventEmitterAsyncResource | undefined; |
6af9012e | 16 | |
7dde0b73 | 17 | /** |
e71cccf3 | 18 | * `WorkerAbstract` constructor. |
7dde0b73 | 19 | * |
0e4fa348 JB |
20 | * @param workerScript - |
21 | * @param workerOptions - | |
7dde0b73 | 22 | */ |
4a3807d1 | 23 | constructor(workerScript: string, workerOptions: WorkerOptions) { |
a78c196b | 24 | if (workerScript == null) { |
49e2c1e5 | 25 | throw new TypeError('Worker script is not defined'); |
44a95b7f | 26 | } |
49e2c1e5 JB |
27 | if (typeof workerScript !== 'string') { |
28 | throw new TypeError('Worker script must be a string'); | |
29 | } | |
30 | if (workerScript.trim().length === 0) { | |
31 | throw new Error('Worker script is an empty string'); | |
ba516f9c | 32 | } |
d972af76 | 33 | if (!existsSync(workerScript)) { |
44a95b7f JB |
34 | throw new Error('Worker script file does not exist'); |
35 | } | |
ad2f27c3 | 36 | this.workerScript = workerScript; |
4d7227e6 | 37 | this.workerOptions = workerOptions; |
a37fc6dc JB |
38 | this.workerOptions.poolOptions!.errorHandler = |
39 | this.workerOptions.poolOptions?.errorHandler ?? defaultErrorHandler; | |
40 | this.workerOptions.poolOptions!.exitHandler = | |
41 | this.workerOptions.poolOptions?.exitHandler ?? defaultExitHandler; | |
7dde0b73 JB |
42 | } |
43 | ||
8baf3f8f | 44 | /** |
361c98f5 | 45 | * Starts the worker pool/set. |
8baf3f8f | 46 | */ |
418106c8 | 47 | public abstract start(): Promise<void>; |
8baf3f8f | 48 | /** |
361c98f5 | 49 | * Stops the worker pool/set. |
8baf3f8f | 50 | */ |
ded13d97 | 51 | public abstract stop(): Promise<void>; |
8baf3f8f | 52 | /** |
361c98f5 | 53 | * Adds a task element to the worker pool/set. |
8baf3f8f JB |
54 | * |
55 | * @param elementData - | |
56 | */ | |
c3ee95af | 57 | public abstract addElement(elementData: T): Promise<void>; |
7dde0b73 | 58 | } |