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