Ensure 1:1 mapping between charging station and ATG instances
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerFactory.ts
CommitLineData
ffd71f2c 1import { Worker, isMainThread } from 'worker_threads';
c3ee95af 2import { WorkerData, WorkerOptions, WorkerProcessType } from '../types/Worker';
b8da29bc 3
322c9192 4import Constants from '../utils/Constants';
ffd71f2c 5import { PoolOptions } from 'poolifier';
73b9adec 6import type WorkerAbstract from './WorkerAbstract';
a4624c96 7import WorkerDynamicPool from './WorkerDynamicPool';
6013bc53 8import WorkerSet from './WorkerSet';
a4624c96 9import WorkerStaticPool from './WorkerStaticPool';
6013bc53
JB
10
11export default class WorkerFactory {
6c3cfef8
JB
12 private constructor() {
13 // This is intentional
14 }
8df3f0a9 15
c3ee95af 16 public static getWorkerImplementation<T extends WorkerData>(workerScript: string, workerProcessType: WorkerProcessType, options?: WorkerOptions): WorkerAbstract<T> | null {
ded13d97
JB
17 if (!isMainThread) {
18 throw new Error('Trying to get a worker implementation outside the main thread');
19 }
535aaa27 20 options = options ?? {} as WorkerOptions;
2f70f96f 21 options.startDelay = options?.startDelay ?? Constants.WORKER_START_DELAY;
ffd71f2c 22 options.poolOptions = options?.poolOptions ?? {} as PoolOptions<Worker>;
b55c9112 23 options?.messageHandler && (options.poolOptions.messageHandler = options.messageHandler);
c3ee95af 24 let workerImplementation: WorkerAbstract<T> = null;
535aaa27
JB
25 switch (workerProcessType) {
26 case WorkerProcessType.WORKER_SET:
27 options.elementsPerWorker = options.elementsPerWorker ?? Constants.DEFAULT_CHARGING_STATIONS_PER_WORKER;
c3ee95af 28 workerImplementation = new WorkerSet(workerScript, options.elementsPerWorker, options.startDelay, options);
535aaa27
JB
29 break;
30 case WorkerProcessType.STATIC_POOL:
31 options.poolMaxSize = options.poolMaxSize ?? Constants.DEFAULT_WORKER_POOL_MAX_SIZE;
c3ee95af 32 workerImplementation = new WorkerStaticPool(workerScript, options.poolMaxSize, options.startDelay, options.poolOptions);
535aaa27
JB
33 break;
34 case WorkerProcessType.DYNAMIC_POOL:
35 options.poolMinSize = options.poolMinSize ?? Constants.DEFAULT_WORKER_POOL_MIN_SIZE;
36 options.poolMaxSize = options.poolMaxSize ?? Constants.DEFAULT_WORKER_POOL_MAX_SIZE;
c3ee95af 37 workerImplementation = new WorkerDynamicPool(workerScript, options.poolMinSize, options.poolMaxSize, options.startDelay, options.poolOptions);
535aaa27 38 break;
fb226c9b
JB
39 default:
40 throw new Error(`Worker implementation type '${workerProcessType}' not found`);
6013bc53 41 }
535aaa27 42 return workerImplementation;
6013bc53
JB
43 }
44}