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