1 import { Worker
, isMainThread
} from
'worker_threads';
2 import { WorkerData
, WorkerOptions
, WorkerProcessType
} from
'../types/Worker';
4 import Constants from
'../utils/Constants';
5 import { PoolOptions
} from
'poolifier';
6 import type WorkerAbstract from
'./WorkerAbstract';
7 import WorkerDynamicPool from
'./WorkerDynamicPool';
8 import WorkerSet from
'./WorkerSet';
9 import WorkerStaticPool from
'./WorkerStaticPool';
11 export default class WorkerFactory
{
12 private constructor() {
13 // This is intentional
16 public static getWorkerImplementation
<T
extends WorkerData
>(workerScript
: string, workerProcessType
: WorkerProcessType
, options
?: WorkerOptions
): WorkerAbstract
<T
> | null {
18 throw new Error('Trying to get a worker implementation outside the main thread');
20 options
= options
?? {} as WorkerOptions
;
21 options
.workerStartDelay
= options
?.workerStartDelay
?? Constants
.WORKER_START_DELAY
;
22 options
.elementStartDelay
= options
?.elementStartDelay
?? Constants
.ELEMENT_START_DELAY
;
23 options
.poolOptions
= options
?.poolOptions
?? {} as PoolOptions
<Worker
>;
24 options
?.messageHandler
&& (options
.poolOptions
.messageHandler
= options
.messageHandler
);
25 let workerImplementation
: WorkerAbstract
<T
> = null;
26 switch (workerProcessType
) {
27 case WorkerProcessType
.WORKER_SET
:
28 options
.elementsPerWorker
= options
.elementsPerWorker
?? Constants
.DEFAULT_CHARGING_STATIONS_PER_WORKER
;
29 workerImplementation
= new WorkerSet(workerScript
, options
.elementsPerWorker
, { workerStartDelay
: options
.workerStartDelay
, elementStartDelay
: options
.elementStartDelay
}, options
);
31 case WorkerProcessType
.STATIC_POOL
:
32 options
.poolMaxSize
= options
.poolMaxSize
?? Constants
.DEFAULT_WORKER_POOL_MAX_SIZE
;
33 workerImplementation
= new WorkerStaticPool(workerScript
, options
.poolMaxSize
, { workerStartDelay
: options
.workerStartDelay
, elementStartDelay
: options
.elementStartDelay
}, options
.poolOptions
);
35 case WorkerProcessType
.DYNAMIC_POOL
:
36 options
.poolMinSize
= options
.poolMinSize
?? Constants
.DEFAULT_WORKER_POOL_MIN_SIZE
;
37 options
.poolMaxSize
= options
.poolMaxSize
?? Constants
.DEFAULT_WORKER_POOL_MAX_SIZE
;
38 workerImplementation
= new WorkerDynamicPool(workerScript
, options
.poolMinSize
, options
.poolMaxSize
, { workerStartDelay
: options
.workerStartDelay
, elementStartDelay
: options
.elementStartDelay
}, options
.poolOptions
);
41 throw new Error(`Worker implementation type '${workerProcessType}' not found`);
43 return workerImplementation
;