Remove useless condition test
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import { ChargingStationWorkerData, ChargingStationWorkerMessage, ChargingStationWorkerMessageEvents } from '../types/ChargingStationWorker';
4
5 import Configuration from '../utils/Configuration';
6 import { Storage } from '../performance/storage/Storage';
7 import { StorageFactory } from '../performance/storage/StorageFactory';
8 import Utils from '../utils/Utils';
9 import WebSocketServer from './WebSocketServer';
10 import WorkerAbstract from '../worker/WorkerAbstract';
11 import WorkerFactory from '../worker/WorkerFactory';
12 import chalk from 'chalk';
13 import { isMainThread } from 'worker_threads';
14 import path from 'path';
15 import { version } from '../../package.json';
16
17 export default class Bootstrap {
18 private static instance: Bootstrap | null = null;
19 private workerImplementation: WorkerAbstract | null = null;
20 private readonly webSocketServer: WebSocketServer;
21 private readonly storage: Storage;
22 private numberOfChargingStations: number;
23 private readonly version: string = version;
24 private started: boolean;
25 private readonly workerScript: string;
26
27 private constructor() {
28 this.started = false;
29 this.workerScript = path.join(path.resolve(__dirname, '../'), 'charging-station', 'ChargingStationWorker.js');
30 this.initWorkerImplementation();
31 this.webSocketServer = new WebSocketServer();
32 this.storage = StorageFactory.getStorage(Configuration.getPerformanceStorage().type, Configuration.getPerformanceStorage().URI, this.logPrefix());
33 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
34 }
35
36 public static getInstance(): Bootstrap {
37 if (!Bootstrap.instance) {
38 Bootstrap.instance = new Bootstrap();
39 }
40 return Bootstrap.instance;
41 }
42
43 public async start(): Promise<void> {
44 if (isMainThread && !this.started) {
45 try {
46 this.numberOfChargingStations = 0;
47 await this.storage.open();
48 await this.workerImplementation.start();
49 this.webSocketServer.start();
50 // Start ChargingStation object in worker thread
51 if (Configuration.getStationTemplateURLs()) {
52 for (const stationURL of Configuration.getStationTemplateURLs()) {
53 try {
54 const nbStations = stationURL.numberOfStations ?? 0;
55 for (let index = 1; index <= nbStations; index++) {
56 const workerData: ChargingStationWorkerData = {
57 index,
58 templateFile: path.join(path.resolve(__dirname, '../'), 'assets', 'station-templates', path.basename(stationURL.file))
59 };
60 await this.workerImplementation.addElement(workerData);
61 this.numberOfChargingStations++;
62 }
63 } catch (error) {
64 console.error(chalk.red('Charging station start with template file ' + stationURL.file + ' error '), error);
65 }
66 }
67 } else {
68 console.warn(chalk.yellow('No stationTemplateURLs defined in configuration, exiting'));
69 }
70 if (this.numberOfChargingStations === 0) {
71 console.warn(chalk.yellow('No charging station template enabled in configuration, exiting'));
72 } else {
73 console.log(chalk.green(`Charging stations simulator ${this.version} started with ${this.numberOfChargingStations.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)` : ''}`));
74 }
75 this.started = true;
76 } catch (error) {
77 console.error(chalk.red('Bootstrap start error '), error);
78 }
79 } else {
80 console.error(chalk.red('Cannot start an already started charging stations simulator'));
81 }
82 }
83
84 public async stop(): Promise<void> {
85 if (isMainThread && this.started) {
86 await this.workerImplementation.stop();
87 this.webSocketServer.stop();
88 await this.storage.close();
89 } else {
90 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
91 }
92 this.started = false;
93 }
94
95 public async restart(): Promise<void> {
96 await this.stop();
97 this.initWorkerImplementation();
98 await this.start();
99 }
100
101 private initWorkerImplementation(): void {
102 this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(this.workerScript, Configuration.getWorkerProcess(),
103 {
104 startDelay: Configuration.getWorkerStartDelay(),
105 poolMaxSize: Configuration.getWorkerPoolMaxSize(),
106 poolMinSize: Configuration.getWorkerPoolMinSize(),
107 elementsPerWorker: Configuration.getChargingStationsPerWorker(),
108 poolOptions: {
109 workerChoiceStrategy: Configuration.getWorkerPoolStrategy()
110 },
111 messageHandler: async (msg: ChargingStationWorkerMessage) => {
112 if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
113 this.webSocketServer.webSocketServerService.chargingStations.add(msg.data.id);
114 } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
115 this.webSocketServer.webSocketServerService.chargingStations.delete(msg.data.id);
116 } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
117 await this.storage.storePerformanceStatistics(msg.data);
118 }
119 }
120 });
121 }
122
123 private logPrefix(): string {
124 return Utils.logPrefix(' Bootstrap |');
125 }
126 }