1 import type { EventEmitterAsyncResource
} from
'node:events';
2 import { existsSync
} from
'node:fs';
4 import type { PoolInfo
} from
'poolifier';
6 import type { SetInfo
, WorkerData
, WorkerOptions
} from
'./WorkerTypes';
7 import { defaultErrorHandler
, defaultExitHandler
} from
'./WorkerUtils';
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;
18 * `WorkerAbstract` constructor.
20 * @param workerScript -
21 * @param workerOptions -
23 constructor(workerScript
: string, workerOptions
: WorkerOptions
) {
24 if (workerScript
== null) {
25 throw new TypeError('Worker script is not defined');
27 if (typeof workerScript
!== 'string') {
28 throw new TypeError('Worker script must be a string');
30 if (workerScript
.trim().length
=== 0) {
31 throw new Error('Worker script is an empty string');
33 if (!existsSync(workerScript
)) {
34 throw new Error('Worker script file does not exist');
36 this.workerScript
= workerScript
;
37 this.workerOptions
= workerOptions
;
38 this.workerOptions
.poolOptions
!.errorHandler
=
39 this.workerOptions
.poolOptions
?.errorHandler
?? defaultErrorHandler
;
40 this.workerOptions
.poolOptions
!.exitHandler
=
41 this.workerOptions
.poolOptions
?.exitHandler
?? defaultExitHandler
;
45 * Starts the worker pool/set.
47 public abstract start(): Promise
<void>;
49 * Stops the worker pool/set.
51 public abstract stop(): Promise
<void>;
53 * Adds a task element to the worker pool/set.
55 * @param elementData -
57 public abstract addElement(elementData
: T
): Promise
<void>;