1 import { WorkerOptions
, WorkerProcessType
} from
'../types/Worker';
3 import Constants from
'../utils/Constants';
4 import WorkerAbstract from
'./WorkerAbstract';
5 import WorkerDynamicPool from
'./WorkerDynamicPool';
6 import WorkerSet from
'./WorkerSet';
7 import WorkerStaticPool from
'./WorkerStaticPool';
8 import { isMainThread
} from
'worker_threads';
10 export default class WorkerFactory
{
11 private static workerImplementation
: WorkerAbstract
| null;
13 private constructor() {}
15 public static getWorkerImplementation
<T
>(workerScript
: string, workerProcessType
: WorkerProcessType
, options
?: WorkerOptions
, forceInstantiation
= false): WorkerAbstract
| null {
17 throw new Error('Trying to get a worker implementation outside the main thread');
19 if (!WorkerFactory
.workerImplementation
|| forceInstantiation
) {
20 options
= options
?? {} as WorkerOptions
;
21 options
.startDelay
= options
.startDelay
?? Constants
.WORKER_START_DELAY
;
22 WorkerFactory
.workerImplementation
= null;
23 switch (workerProcessType
) {
24 case WorkerProcessType
.WORKER_SET
:
25 options
.elementsPerWorker
= options
.elementsPerWorker
?? Constants
.DEFAULT_CHARGING_STATIONS_PER_WORKER
;
26 WorkerFactory
.workerImplementation
= new WorkerSet
<T
>(workerScript
, options
.elementsPerWorker
, options
.startDelay
);
28 case WorkerProcessType
.STATIC_POOL
:
29 options
.poolMaxSize
= options
.poolMaxSize
?? Constants
.DEFAULT_WORKER_POOL_MAX_SIZE
;
30 WorkerFactory
.workerImplementation
= new WorkerStaticPool
<T
>(workerScript
, options
.poolMaxSize
, options
.startDelay
, options
.poolOptions
);
32 case WorkerProcessType
.DYNAMIC_POOL
:
33 options
.poolMinSize
= options
.poolMinSize
?? Constants
.DEFAULT_WORKER_POOL_MIN_SIZE
;
34 options
.poolMaxSize
= options
.poolMaxSize
?? Constants
.DEFAULT_WORKER_POOL_MAX_SIZE
;
35 WorkerFactory
.workerImplementation
= new WorkerDynamicPool
<T
>(workerScript
, options
.poolMinSize
, options
.poolMaxSize
, options
.startDelay
, options
.poolOptions
);
39 return WorkerFactory
.workerImplementation
;