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