refactor: remove now uneeded sanity check at worker message handling
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerFactory.ts
CommitLineData
be245fda 1import { isMainThread } from 'node:worker_threads';
b8da29bc 2
268a74bb
JB
3import type { WorkerAbstract } from './WorkerAbstract';
4import { WorkerConstants } from './WorkerConstants';
5import { WorkerDynamicPool } from './WorkerDynamicPool';
6import { WorkerSet } from './WorkerSet';
7import { WorkerStaticPool } from './WorkerStaticPool';
8import { type WorkerData, type WorkerOptions, WorkerProcessType } from './WorkerTypes';
6013bc53 9
4a3807d1
JB
10const DEFAULT_WORKER_OPTIONS: WorkerOptions = {
11 workerStartDelay: WorkerConstants.DEFAULT_WORKER_START_DELAY,
12 elementStartDelay: WorkerConstants.DEFAULT_ELEMENT_START_DELAY,
13 poolMinSize: WorkerConstants.DEFAULT_POOL_MIN_SIZE,
14 poolMaxSize: WorkerConstants.DEFAULT_POOL_MAX_SIZE,
15 elementsPerWorker: WorkerConstants.DEFAULT_ELEMENTS_PER_WORKER,
16 poolOptions: {},
17};
18
268a74bb 19export class WorkerFactory {
6c3cfef8
JB
20 private constructor() {
21 // This is intentional
22 }
8df3f0a9 23
e7aeea18
JB
24 public static getWorkerImplementation<T extends WorkerData>(
25 workerScript: string,
26 workerProcessType: WorkerProcessType,
5edd8ba0 27 workerOptions?: WorkerOptions,
e7aeea18 28 ): WorkerAbstract<T> | null {
ded13d97 29 if (!isMainThread) {
44a95b7f 30 throw new Error('Cannot get a worker implementation outside the main thread');
ded13d97 31 }
4a3807d1 32 workerOptions = { ...DEFAULT_WORKER_OPTIONS, ...workerOptions };
1895299d 33 let workerImplementation: WorkerAbstract<T> | null = null;
535aaa27 34 switch (workerProcessType) {
721646e9 35 case WorkerProcessType.workerSet:
d070d967 36 workerImplementation = new WorkerSet(workerScript, workerOptions);
535aaa27 37 break;
721646e9 38 case WorkerProcessType.staticPool:
d070d967 39 workerImplementation = new WorkerStaticPool(workerScript, workerOptions);
535aaa27 40 break;
721646e9 41 case WorkerProcessType.dynamicPool:
d070d967 42 workerImplementation = new WorkerDynamicPool(workerScript, workerOptions);
535aaa27 43 break;
fb226c9b 44 default:
3fa0f0ed 45 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
fb226c9b 46 throw new Error(`Worker implementation type '${workerProcessType}' not found`);
6013bc53 47 }
535aaa27 48 return workerImplementation;
6013bc53
JB
49 }
50}