| 1 | import { WorkerOptions, WorkerProcessType } from '../types/Worker'; |
| 2 | |
| 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'; |
| 9 | |
| 10 | export default class WorkerFactory { |
| 11 | public static getWorkerImplementation<T>(workerScript: string, workerProcessType: WorkerProcessType, options?: WorkerOptions): WorkerAbstract | null { |
| 12 | if (!isMainThread) { |
| 13 | throw new Error('Trying to get a worker implementation outside the main thread'); |
| 14 | } |
| 15 | options = options ?? {} as WorkerOptions; |
| 16 | options.startDelay = options.startDelay ?? Constants.WORKER_START_DELAY; |
| 17 | switch (workerProcessType) { |
| 18 | case WorkerProcessType.WORKER_SET: |
| 19 | options.elementsPerWorker = options.elementsPerWorker ?? Constants.DEFAULT_CHARGING_STATIONS_PER_WORKER; |
| 20 | return new WorkerSet<T>(workerScript, options.elementsPerWorker, options.startDelay); |
| 21 | case WorkerProcessType.STATIC_POOL: |
| 22 | options.poolMaxSize = options.poolMaxSize ?? Constants.DEFAULT_WORKER_POOL_MAX_SIZE; |
| 23 | return new WorkerStaticPool<T>(workerScript, options.poolMaxSize, options.startDelay, options.poolOptions); |
| 24 | case WorkerProcessType.DYNAMIC_POOL: |
| 25 | options.poolMinSize = options.poolMinSize ?? Constants.DEFAULT_WORKER_POOL_MIN_SIZE; |
| 26 | options.poolMaxSize = options.poolMaxSize ?? Constants.DEFAULT_WORKER_POOL_MAX_SIZE; |
| 27 | return new WorkerDynamicPool<T>(workerScript, options.poolMinSize, options.poolMaxSize, options.startDelay, options.poolOptions); |
| 28 | default: |
| 29 | return null; |
| 30 | } |
| 31 | } |
| 32 | } |