Use singleton design pattern directly in the worker object factory
authorJérôme Benoit <jerome.benoit@sap.com>
Mon, 23 Aug 2021 21:07:23 +0000 (23:07 +0200)
committerJérôme Benoit <jerome.benoit@sap.com>
Mon, 23 Aug 2021 21:07:23 +0000 (23:07 +0200)
And remove all now uneeded singleton classes

Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
src/charging-station/Bootstrap.ts
src/worker/WorkerDynamicPool.ts
src/worker/WorkerFactory.ts
src/worker/WorkerStaticPool.ts

index acfd99145e9a33b4d983bbecfc864427c0ebd9ae..52e1242f3973d45d6a6b430260509ba8f5e3b780 100644 (file)
@@ -12,11 +12,12 @@ export default class Bootstrap {
   private version: string = version;
   private started: boolean;
   private workerScript: string;
-  private workerImplementationInstance: WorkerAbstract | null = null;
+  private workerImplementation: WorkerAbstract | null = null;
 
   private constructor() {
     this.started = false;
     this.workerScript = path.join(path.resolve(__dirname, '../'), 'charging-station', 'StationWorker.js');
+    this.initWorkerImplementation();
     Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
   }
 
@@ -31,7 +32,7 @@ export default class Bootstrap {
     if (isMainThread && !this.started) {
       try {
         let numStationsTotal = 0;
-        await this.getWorkerImplementationInstance()?.start();
+        await this.workerImplementation.start();
         // Start ChargingStation object in worker thread
         if (Configuration.getStationTemplateURLs()) {
           for (const stationURL of Configuration.getStationTemplateURLs()) {
@@ -42,7 +43,7 @@ export default class Bootstrap {
                   index,
                   templateFile: path.join(path.resolve(__dirname, '../'), 'assets', 'station-templates', path.basename(stationURL.file))
                 };
-                await this.getWorkerImplementationInstance()?.addElement(workerData);
+                await this.workerImplementation.addElement(workerData);
                 numStationsTotal++;
               }
             } catch (error) {
@@ -55,7 +56,7 @@ export default class Bootstrap {
         if (numStationsTotal === 0) {
           console.log('No charging station template enabled in configuration, exiting');
         } else {
-          console.log(`Charging station simulator ${this.version} started with ${numStationsTotal.toString()} charging station(s) and ${Utils.workerDynamicPoolInUse() ? `${Configuration.getWorkerPoolMinSize().toString()}/` : ''}${this.getWorkerImplementationInstance().size}${Utils.workerPoolInUse() ? `/${Configuration.getWorkerPoolMaxSize().toString()}` : ''} worker(s) concurrently running in '${Configuration.getWorkerProcess()}' mode${this.getWorkerImplementationInstance().maxElementsPerWorker ? ` (${this.getWorkerImplementationInstance().maxElementsPerWorker} charging station(s) per worker)` : ''}`);
+          console.log(`Charging station simulator ${this.version} started with ${numStationsTotal.toString()} charging station(s) and ${Utils.workerDynamicPoolInUse() ? `${Configuration.getWorkerPoolMinSize().toString()}/` : ''}${this.workerImplementation.size}${Utils.workerPoolInUse() ? `/${Configuration.getWorkerPoolMaxSize().toString()}` : ''} worker(s) concurrently running in '${Configuration.getWorkerProcess()}' mode${this.workerImplementation.maxElementsPerWorker ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)` : ''}`);
         }
         this.started = true;
       } catch (error) {
@@ -66,31 +67,30 @@ export default class Bootstrap {
 
   public async stop(): Promise<void> {
     if (isMainThread && this.started) {
-      await this.getWorkerImplementationInstance()?.stop();
-      // Nullify to force worker implementation instance creation
-      this.workerImplementationInstance = null;
+      await this.workerImplementation.stop();
     }
     this.started = false;
   }
 
   public async restart(): Promise<void> {
     await this.stop();
+    this.initWorkerImplementation(true);
     await this.start();
   }
 
-  private getWorkerImplementationInstance(): WorkerAbstract | null {
-    if (!this.workerImplementationInstance) {
-      this.workerImplementationInstance = WorkerFactory.getWorkerImplementation<StationWorkerData>(this.workerScript, Configuration.getWorkerProcess(),
-        {
-          startDelay: Configuration.getWorkerStartDelay(),
-          poolMaxSize: Configuration.getWorkerPoolMaxSize(),
-          poolMinSize: Configuration.getWorkerPoolMinSize(),
-          elementsPerWorker: Configuration.getChargingStationsPerWorker(),
-          poolOptions: {
-            workerChoiceStrategy: Configuration.getWorkerPoolStrategy()
-          }
-        });
+  private initWorkerImplementation(forceInstantiation = false) {
+    this.workerImplementation = WorkerFactory.getWorkerImplementation<StationWorkerData>(this.workerScript, Configuration.getWorkerProcess(),
+      {
+        startDelay: Configuration.getWorkerStartDelay(),
+        poolMaxSize: Configuration.getWorkerPoolMaxSize(),
+        poolMinSize: Configuration.getWorkerPoolMinSize(),
+        elementsPerWorker: Configuration.getChargingStationsPerWorker(),
+        poolOptions: {
+          workerChoiceStrategy: Configuration.getWorkerPoolStrategy()
+        }
+      }, forceInstantiation);
+    if (!this.workerImplementation) {
+      throw new Error('Worker implementation not found');
     }
-    return this.workerImplementationInstance;
   }
 }
index 8ab960f365c986eec798c10e1f7e6d0cf1af8451..306bcd4f38f415b1823a205198e05a8ddb3a38a0 100644 (file)
@@ -7,7 +7,7 @@ import { WorkerData } from '../types/Worker';
 import { WorkerUtils } from './WorkerUtils';
 
 export default class WorkerDynamicPool<T> extends WorkerAbstract {
-  private pool: DynamicPool;
+  private pool: DynamicThreadPool<WorkerData>;
 
   /**
    * Create a new `WorkerDynamicPool`.
@@ -20,7 +20,8 @@ export default class WorkerDynamicPool<T> extends WorkerAbstract {
    */
   constructor(workerScript: string, min: number, max: number, workerStartDelay?: number, opts?: PoolOptions<Worker>) {
     super(workerScript, workerStartDelay);
-    this.pool = DynamicPool.getInstance(min, max, this.workerScript, opts);
+    opts.exitHandler = opts?.exitHandler ?? WorkerUtils.defaultExitHandler;
+    this.pool = new DynamicThreadPool<WorkerData>(min, max, this.workerScript, opts);
   }
 
   get size(): number {
@@ -37,7 +38,7 @@ export default class WorkerDynamicPool<T> extends WorkerAbstract {
    * @public
    */
   // eslint-disable-next-line @typescript-eslint/no-empty-function
-  public async start(): Promise<void> { }
+  public async start(): Promise<void> {}
 
   /**
    *
@@ -61,19 +62,3 @@ export default class WorkerDynamicPool<T> extends WorkerAbstract {
     await Utils.sleep(this.workerStartDelay);
   }
 }
-
-class DynamicPool extends DynamicThreadPool<WorkerData> {
-  private static instance: DynamicPool;
-
-  private constructor(min: number, max: number, workerScript: string, opts?: PoolOptions<Worker>) {
-    super(min, max, workerScript, opts);
-  }
-
-  public static getInstance(min: number, max: number, workerScript: string, opts?: PoolOptions<Worker>): DynamicPool {
-    if (!DynamicPool.instance) {
-      opts.exitHandler = opts?.exitHandler ?? WorkerUtils.defaultExitHandler;
-      DynamicPool.instance = new DynamicPool(min, max, workerScript, opts);
-    }
-    return DynamicPool.instance;
-  }
-}
index 3784e7ab0c572f36a30de55d1181309fa4e2191e..b5cf327c12d57ab7935b27aefb4a26cf2b79ca05 100644 (file)
@@ -8,25 +8,34 @@ import WorkerStaticPool from './WorkerStaticPool';
 import { isMainThread } from 'worker_threads';
 
 export default class WorkerFactory {
-  public static getWorkerImplementation<T>(workerScript: string, workerProcessType: WorkerProcessType, options?: WorkerOptions): WorkerAbstract | null {
+  private static workerImplementation: WorkerAbstract | null;
+
+  private constructor() {}
+
+  public static getWorkerImplementation<T>(workerScript: string, workerProcessType: WorkerProcessType, options?: WorkerOptions, forceInstantiation = false): WorkerAbstract | null {
     if (!isMainThread) {
       throw new Error('Trying to get a worker implementation outside the main thread');
     }
-    options = options ?? {} as WorkerOptions;
-    options.startDelay = options.startDelay ?? Constants.WORKER_START_DELAY;
-    switch (workerProcessType) {
-      case WorkerProcessType.WORKER_SET:
-        options.elementsPerWorker = options.elementsPerWorker ?? Constants.DEFAULT_CHARGING_STATIONS_PER_WORKER;
-        return new WorkerSet<T>(workerScript, options.elementsPerWorker, options.startDelay);
-      case WorkerProcessType.STATIC_POOL:
-        options.poolMaxSize = options.poolMaxSize ?? Constants.DEFAULT_WORKER_POOL_MAX_SIZE;
-        return new WorkerStaticPool<T>(workerScript, options.poolMaxSize, options.startDelay, options.poolOptions);
-      case WorkerProcessType.DYNAMIC_POOL:
-        options.poolMinSize = options.poolMinSize ?? Constants.DEFAULT_WORKER_POOL_MIN_SIZE;
-        options.poolMaxSize = options.poolMaxSize ?? Constants.DEFAULT_WORKER_POOL_MAX_SIZE;
-        return new WorkerDynamicPool<T>(workerScript, options.poolMinSize, options.poolMaxSize, options.startDelay, options.poolOptions);
-      default:
-        return null;
+    if (!WorkerFactory.workerImplementation || forceInstantiation) {
+      options = options ?? {} as WorkerOptions;
+      options.startDelay = options.startDelay ?? Constants.WORKER_START_DELAY;
+      WorkerFactory.workerImplementation = null;
+      switch (workerProcessType) {
+        case WorkerProcessType.WORKER_SET:
+          options.elementsPerWorker = options.elementsPerWorker ?? Constants.DEFAULT_CHARGING_STATIONS_PER_WORKER;
+          WorkerFactory.workerImplementation = new WorkerSet<T>(workerScript, options.elementsPerWorker, options.startDelay);
+          break;
+        case WorkerProcessType.STATIC_POOL:
+          options.poolMaxSize = options.poolMaxSize ?? Constants.DEFAULT_WORKER_POOL_MAX_SIZE;
+          WorkerFactory.workerImplementation = new WorkerStaticPool<T>(workerScript, options.poolMaxSize, options.startDelay, options.poolOptions);
+          break;
+        case WorkerProcessType.DYNAMIC_POOL:
+          options.poolMinSize = options.poolMinSize ?? Constants.DEFAULT_WORKER_POOL_MIN_SIZE;
+          options.poolMaxSize = options.poolMaxSize ?? Constants.DEFAULT_WORKER_POOL_MAX_SIZE;
+          WorkerFactory.workerImplementation = new WorkerDynamicPool<T>(workerScript, options.poolMinSize, options.poolMaxSize, options.startDelay, options.poolOptions);
+          break;
+      }
     }
+    return WorkerFactory.workerImplementation;
   }
 }
index cf46cfa55f7662f671a5a24635c1f9566feb55f4..a7bb193270e88346347f42fa1d2c98efcc31f806 100644 (file)
@@ -7,7 +7,7 @@ import { WorkerData } from '../types/Worker';
 import { WorkerUtils } from './WorkerUtils';
 
 export default class WorkerStaticPool<T> extends WorkerAbstract {
-  private pool: StaticPool;
+  private pool: FixedThreadPool<WorkerData>;
 
   /**
    * Create a new `WorkerStaticPool`.
@@ -19,7 +19,8 @@ export default class WorkerStaticPool<T> extends WorkerAbstract {
    */
   constructor(workerScript: string, numberOfThreads: number, startWorkerDelay?: number, opts?: PoolOptions<Worker>) {
     super(workerScript, startWorkerDelay);
-    this.pool = StaticPool.getInstance(numberOfThreads, this.workerScript, opts);
+    opts.exitHandler = opts?.exitHandler ?? WorkerUtils.defaultExitHandler;
+    this.pool = new FixedThreadPool(numberOfThreads, this.workerScript, opts);
   }
 
   get size(): number {
@@ -36,7 +37,7 @@ export default class WorkerStaticPool<T> extends WorkerAbstract {
    * @public
    */
   // eslint-disable-next-line @typescript-eslint/no-empty-function
-  public async start(): Promise<void> { }
+  public async start(): Promise<void> {}
 
   /**
    *
@@ -59,19 +60,3 @@ export default class WorkerStaticPool<T> extends WorkerAbstract {
     await Utils.sleep(this.workerStartDelay);
   }
 }
-
-class StaticPool extends FixedThreadPool<WorkerData> {
-  private static instance: StaticPool;
-
-  private constructor(numberOfThreads: number, workerScript: string, opts?: PoolOptions<Worker>) {
-    super(numberOfThreads, workerScript, opts);
-  }
-
-  public static getInstance(numberOfThreads: number, workerScript: string, opts?: PoolOptions<Worker>): StaticPool {
-    if (!StaticPool.instance) {
-      opts.exitHandler = opts?.exitHandler ?? WorkerUtils.defaultExitHandler;
-      StaticPool.instance = new StaticPool(numberOfThreads, workerScript, opts);
-    }
-    return StaticPool.instance;
-  }
-}