Remove string literal from log messages
[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
d070d967 16 public static getWorkerImplementation<T extends WorkerData>(workerScript: string, workerProcessType: WorkerProcessType, workerOptions?: WorkerOptions): WorkerAbstract<T> | null {
ded13d97
JB
17 if (!isMainThread) {
18 throw new Error('Trying to get a worker implementation outside the main thread');
19 }
d070d967
JB
20 workerOptions = workerOptions ?? {} as WorkerOptions;
21 workerOptions.workerStartDelay = workerOptions?.workerStartDelay ?? Constants.WORKER_START_DELAY;
22 workerOptions.elementStartDelay = workerOptions?.elementStartDelay ?? Constants.ELEMENT_START_DELAY;
23 workerOptions.poolOptions = workerOptions?.poolOptions ?? {} as PoolOptions<Worker>;
24 workerOptions?.messageHandler && (workerOptions.poolOptions.messageHandler = workerOptions.messageHandler);
c3ee95af 25 let workerImplementation: WorkerAbstract<T> = null;
535aaa27
JB
26 switch (workerProcessType) {
27 case WorkerProcessType.WORKER_SET:
d070d967
JB
28 workerOptions.elementsPerWorker = workerOptions?.elementsPerWorker ?? Constants.DEFAULT_CHARGING_STATIONS_PER_WORKER;
29 workerImplementation = new WorkerSet(workerScript, workerOptions);
535aaa27
JB
30 break;
31 case WorkerProcessType.STATIC_POOL:
d070d967
JB
32 workerOptions.poolMaxSize = workerOptions?.poolMaxSize ?? Constants.DEFAULT_WORKER_POOL_MAX_SIZE;
33 workerImplementation = new WorkerStaticPool(workerScript, workerOptions);
535aaa27
JB
34 break;
35 case WorkerProcessType.DYNAMIC_POOL:
d070d967
JB
36 workerOptions.poolMinSize = workerOptions?.poolMinSize ?? Constants.DEFAULT_WORKER_POOL_MIN_SIZE;
37 workerOptions.poolMaxSize = workerOptions?.poolMaxSize ?? Constants.DEFAULT_WORKER_POOL_MAX_SIZE;
38 workerImplementation = new WorkerDynamicPool(workerScript, workerOptions);
535aaa27 39 break;
fb226c9b
JB
40 default:
41 throw new Error(`Worker implementation type '${workerProcessType}' not found`);
6013bc53 42 }
535aaa27 43 return workerImplementation;
6013bc53
JB
44 }
45}