Commit | Line | Data |
---|---|---|
ffd71f2c | 1 | import { Worker, isMainThread } from 'worker_threads'; |
b8da29bc JB |
2 | import { WorkerOptions, WorkerProcessType } from '../types/Worker'; |
3 | ||
322c9192 | 4 | import Constants from '../utils/Constants'; |
ffd71f2c | 5 | import { PoolOptions } from 'poolifier'; |
fd1fdf1b | 6 | import WorkerAbstract from './WorkerAbstract'; |
a4624c96 | 7 | import WorkerDynamicPool from './WorkerDynamicPool'; |
6013bc53 | 8 | import WorkerSet from './WorkerSet'; |
a4624c96 | 9 | import WorkerStaticPool from './WorkerStaticPool'; |
6013bc53 JB |
10 | |
11 | export default class WorkerFactory { | |
3356aa84 | 12 | // eslint-disable-next-line @typescript-eslint/no-empty-function |
6c3cfef8 JB |
13 | private constructor() { |
14 | // This is intentional | |
15 | } | |
8df3f0a9 | 16 | |
ffd71f2c | 17 | public static getWorkerImplementation<T>(workerScript: string, workerProcessType: WorkerProcessType, options?: WorkerOptions): WorkerAbstract | null { |
ded13d97 JB |
18 | if (!isMainThread) { |
19 | throw new Error('Trying to get a worker implementation outside the main thread'); | |
20 | } | |
535aaa27 | 21 | options = options ?? {} as WorkerOptions; |
2f70f96f | 22 | options.startDelay = options?.startDelay ?? Constants.WORKER_START_DELAY; |
ffd71f2c | 23 | options.poolOptions = options?.poolOptions ?? {} as PoolOptions<Worker>; |
b55c9112 | 24 | options?.messageHandler && (options.poolOptions.messageHandler = options.messageHandler); |
535aaa27 JB |
25 | let workerImplementation: WorkerAbstract = null; |
26 | switch (workerProcessType) { | |
27 | case WorkerProcessType.WORKER_SET: | |
28 | options.elementsPerWorker = options.elementsPerWorker ?? Constants.DEFAULT_CHARGING_STATIONS_PER_WORKER; | |
ffd71f2c | 29 | workerImplementation = new WorkerSet<T>(workerScript, options.elementsPerWorker, options.startDelay, options); |
535aaa27 JB |
30 | break; |
31 | case WorkerProcessType.STATIC_POOL: | |
32 | options.poolMaxSize = options.poolMaxSize ?? Constants.DEFAULT_WORKER_POOL_MAX_SIZE; | |
ffd71f2c | 33 | workerImplementation = new WorkerStaticPool<T>(workerScript, options.poolMaxSize, options.startDelay, options.poolOptions); |
535aaa27 JB |
34 | break; |
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; | |
ffd71f2c | 38 | workerImplementation = new WorkerDynamicPool<T>(workerScript, options.poolMinSize, options.poolMaxSize, options.startDelay, options.poolOptions); |
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 | } |