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