fix: untangle worker pool/set init from start
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerFactory.ts
CommitLineData
66a7748d 1import { isMainThread } from 'node:worker_threads'
b8da29bc 2
66a7748d
JB
3import type { WorkerAbstract } from './WorkerAbstract.js'
4import { DEFAULT_WORKER_OPTIONS } from './WorkerConstants.js'
5import { WorkerDynamicPool } from './WorkerDynamicPool.js'
6import { WorkerFixedPool } from './WorkerFixedPool.js'
7import { WorkerSet } from './WorkerSet.js'
8import { type WorkerData, type WorkerOptions, WorkerProcessType } from './WorkerTypes.js'
6013bc53 9
66a7748d 10// eslint-disable-next-line @typescript-eslint/no-extraneous-class
268a74bb 11export class WorkerFactory {
66a7748d 12 private constructor () {
6c3cfef8
JB
13 // This is intentional
14 }
8df3f0a9 15
e7aeea18
JB
16 public static getWorkerImplementation<T extends WorkerData>(
17 workerScript: string,
18 workerProcessType: WorkerProcessType,
66a7748d 19 workerOptions?: WorkerOptions
6d2b7d01 20 ): WorkerAbstract<T> | undefined {
ded13d97 21 if (!isMainThread) {
66a7748d 22 throw new Error('Cannot get a worker implementation outside the main thread')
ded13d97 23 }
66a7748d
JB
24 workerOptions = { ...DEFAULT_WORKER_OPTIONS, ...workerOptions }
25 let workerImplementation: WorkerAbstract<T>
535aaa27 26 switch (workerProcessType) {
721646e9 27 case WorkerProcessType.workerSet:
66a7748d
JB
28 workerImplementation = new WorkerSet(workerScript, workerOptions)
29 break
1d8f226b 30 case WorkerProcessType.fixedPool:
66a7748d
JB
31 workerImplementation = new WorkerFixedPool(workerScript, workerOptions)
32 break
721646e9 33 case WorkerProcessType.dynamicPool:
66a7748d
JB
34 workerImplementation = new WorkerDynamicPool(workerScript, workerOptions)
35 break
fb226c9b 36 default:
3fa0f0ed 37 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
66a7748d 38 throw new Error(`Worker implementation type '${workerProcessType}' not found`)
6013bc53 39 }
66a7748d 40 return workerImplementation
6013bc53
JB
41 }
42}