refactor(simulator): remove unneeded duplicate initialization at startup
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
CommitLineData
edd13439 1// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
b4d34251 2
130783a7
JB
3import path from 'node:path';
4import { fileURLToPath } from 'node:url';
c72f6634 5import { type Worker, isMainThread } from 'worker_threads';
8114d10e
JB
6
7import chalk from 'chalk';
8
78202038
JB
9import { ChargingStationUtils } from './ChargingStationUtils';
10import type { AbstractUIServer } from './ui-server/AbstractUIServer';
11import UIServerFactory from './ui-server/UIServerFactory';
8114d10e 12import { version } from '../../package.json';
32de5a57 13import BaseError from '../exception/BaseError';
6c1761d4 14import type { Storage } from '../performance/storage/Storage';
8114d10e 15import { StorageFactory } from '../performance/storage/StorageFactory';
e7aeea18 16import {
bbe10d5f
JB
17 type ChargingStationData,
18 type ChargingStationWorkerData,
19 type ChargingStationWorkerMessage,
20 type ChargingStationWorkerMessageData,
e7aeea18
JB
21 ChargingStationWorkerMessageEvents,
22} from '../types/ChargingStationWorker';
6c1761d4 23import type { StationTemplateUrl } from '../types/ConfigurationData';
8a36b1eb 24import type { Statistics } from '../types/Statistics';
0e4fa348 25import type { MessageHandler } from '../types/Worker';
8114d10e 26import Configuration from '../utils/Configuration';
32de5a57 27import logger from '../utils/Logger';
ded13d97 28import Utils from '../utils/Utils';
6c1761d4 29import type WorkerAbstract from '../worker/WorkerAbstract';
ded13d97 30import WorkerFactory from '../worker/WorkerFactory';
ded13d97 31
32de5a57
LM
32const moduleName = 'Bootstrap';
33
a307349b
JB
34enum exitCodes {
35 missingChargingStationsConfiguration = 1,
36 noChargingStationTemplates = 2,
37}
e4cb2c14 38
5a010bf0 39export class Bootstrap {
535aaa27 40 private static instance: Bootstrap | null = null;
d1c99c59
JB
41 public numberOfChargingStations!: number;
42 public numberOfChargingStationTemplates!: number;
aa428a31 43 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null;
551e477c 44 private readonly uiServer!: AbstractUIServer | null;
6a49ad23 45 private readonly storage!: Storage;
89b7a234 46 private numberOfStartedChargingStations!: number;
9e23580d 47 private readonly version: string = version;
eb87fe87 48 private started: boolean;
9e23580d 49 private readonly workerScript: string;
ded13d97
JB
50
51 private constructor() {
4724a293
JB
52 // Enable unconditionally for now
53 this.logUnhandledRejection();
54 this.logUncaughtException();
af8e02ca
JB
55 this.started = false;
56 this.workerImplementation = null;
e7aeea18 57 this.workerScript = path.join(
0d8140bd 58 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
e7aeea18 59 'charging-station',
44eb6026 60 `ChargingStationWorker${path.extname(fileURLToPath(import.meta.url))}`
e7aeea18 61 );
5af9aa8a 62 Configuration.getUIServer().enabled === true &&
976d11ec 63 (this.uiServer = UIServerFactory.getUIServerImplementation(Configuration.getUIServer()));
eb3abc4f 64 Configuration.getPerformanceStorage().enabled === true &&
e7aeea18
JB
65 (this.storage = StorageFactory.getStorage(
66 Configuration.getPerformanceStorage().type,
67 Configuration.getPerformanceStorage().uri,
68 this.logPrefix()
69 ));
7874b0b1 70 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
ded13d97
JB
71 }
72
73 public static getInstance(): Bootstrap {
1ca780f9 74 if (Bootstrap.instance === null) {
ded13d97
JB
75 Bootstrap.instance = new Bootstrap();
76 }
77 return Bootstrap.instance;
78 }
79
80 public async start(): Promise<void> {
452a82ca 81 if (isMainThread && this.started === false) {
ded13d97 82 try {
326cec2d
JB
83 this.initializeCounters();
84 this.initializeWorkerImplementation();
6a49ad23 85 await this.storage?.open();
1895299d 86 await this.workerImplementation?.start();
675fa8e3 87 this.uiServer?.start();
1f5df42a 88 const stationTemplateUrls = Configuration.getStationTemplateUrls();
ded13d97 89 // Start ChargingStation object in worker thread
d1c99c59
JB
90 for (const stationTemplateUrl of stationTemplateUrls) {
91 try {
92 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
93 for (let index = 1; index <= nbStations; index++) {
94 await this.startChargingStation(index, stationTemplateUrl);
ded13d97 95 }
d1c99c59
JB
96 } catch (error) {
97 console.error(
98 chalk.red(
99 `Error at starting charging station with template file ${stationTemplateUrl.file}: `
100 ),
101 error
102 );
ded13d97 103 }
ded13d97 104 }
846d2851
JB
105 console.info(
106 chalk.green(
107 `Charging stations simulator ${
108 this.version
109 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
110 ChargingStationUtils.workerDynamicPoolInUse()
111 ? `${Configuration.getWorker().poolMinSize?.toString()}/`
112 : ''
113 }${this.workerImplementation?.size}${
114 ChargingStationUtils.workerPoolInUse()
115 ? `/${Configuration.getWorker().poolMaxSize?.toString()}`
116 : ''
117 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
118 !Utils.isNullOrUndefined(this.workerImplementation?.maxElementsPerWorker)
119 ? ` (${this.workerImplementation?.maxElementsPerWorker} charging station(s) per worker)`
120 : ''
121 }`
122 )
123 );
eb87fe87 124 this.started = true;
ded13d97 125 } catch (error) {
10d244c0 126 console.error(chalk.red('Bootstrap start error: '), error);
ded13d97 127 }
b322b8b4
JB
128 } else {
129 console.error(chalk.red('Cannot start an already started charging stations simulator'));
ded13d97
JB
130 }
131 }
132
133 public async stop(): Promise<void> {
452a82ca 134 if (isMainThread && this.started === true) {
1895299d 135 await this.workerImplementation?.stop();
b19021e2 136 this.workerImplementation = null;
675fa8e3 137 this.uiServer?.stop();
6a49ad23 138 await this.storage?.close();
ba7965c4 139 this.started = false;
b322b8b4 140 } else {
ba7965c4 141 console.error(chalk.red('Cannot stop a not started charging stations simulator'));
ded13d97 142 }
ded13d97
JB
143 }
144
145 public async restart(): Promise<void> {
146 await this.stop();
147 await this.start();
148 }
149
ec7f4dce 150 private initializeWorkerImplementation(): void {
e2c77f10 151 this.workerImplementation === null &&
ec7f4dce
JB
152 (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
153 this.workerScript,
cf2a5d9b 154 Configuration.getWorker().processType,
ec7f4dce 155 {
cf2a5d9b
JB
156 workerStartDelay: Configuration.getWorker().startDelay,
157 elementStartDelay: Configuration.getWorker().elementStartDelay,
158 poolMaxSize: Configuration.getWorker().poolMaxSize,
159 poolMinSize: Configuration.getWorker().poolMinSize,
160 elementsPerWorker: Configuration.getWorker().elementsPerWorker,
ec7f4dce 161 poolOptions: {
cf2a5d9b 162 workerChoiceStrategy: Configuration.getWorker().poolStrategy,
ec7f4dce 163 },
0e4fa348 164 messageHandler: this.messageHandler.bind(this) as MessageHandler<Worker>,
ec7f4dce
JB
165 }
166 ));
ded13d97 167 }
81797102 168
32de5a57 169 private messageHandler(
53e5fd67 170 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
32de5a57
LM
171 ): void {
172 // logger.debug(
173 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
174 // msg,
175 // null,
176 // 2
177 // )}`
178 // );
179 try {
180 switch (msg.id) {
181 case ChargingStationWorkerMessageEvents.STARTED:
182 this.workerEventStarted(msg.data as ChargingStationData);
183 break;
184 case ChargingStationWorkerMessageEvents.STOPPED:
185 this.workerEventStopped(msg.data as ChargingStationData);
186 break;
187 case ChargingStationWorkerMessageEvents.UPDATED:
188 this.workerEventUpdated(msg.data as ChargingStationData);
189 break;
190 case ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS:
191 this.workerEventPerformanceStatistics(msg.data as Statistics);
192 break;
193 default:
194 throw new BaseError(
195 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
196 );
197 }
198 } catch (error) {
199 logger.error(
200 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
201 msg.id
202 }' event:`,
203 error
204 );
205 }
206 }
207
e2c77f10 208 private workerEventStarted = (data: ChargingStationData) => {
51c83d6f 209 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
89b7a234 210 ++this.numberOfStartedChargingStations;
56eb297e 211 logger.info(
e6159ce8 212 `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${
56eb297e 213 data.stationInfo.chargingStationId
e6159ce8 214 } (hashId: ${data.stationInfo.hashId}) started (${
56eb297e
JB
215 this.numberOfStartedChargingStations
216 } started from ${this.numberOfChargingStations})`
217 );
e2c77f10 218 };
32de5a57 219
e2c77f10 220 private workerEventStopped = (data: ChargingStationData) => {
51c83d6f 221 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
89b7a234 222 --this.numberOfStartedChargingStations;
56eb297e 223 logger.info(
e6159ce8 224 `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${
56eb297e 225 data.stationInfo.chargingStationId
e6159ce8 226 } (hashId: ${data.stationInfo.hashId}) stopped (${
56eb297e
JB
227 this.numberOfStartedChargingStations
228 } started from ${this.numberOfChargingStations})`
229 );
e2c77f10 230 };
32de5a57 231
e2c77f10 232 private workerEventUpdated = (data: ChargingStationData) => {
51c83d6f 233 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
e2c77f10 234 };
32de5a57
LM
235
236 private workerEventPerformanceStatistics = (data: Statistics) => {
237 this.storage.storePerformanceStatistics(data) as void;
238 };
239
326cec2d 240 private initializeCounters() {
7c72977b 241 this.numberOfChargingStationTemplates = 0;
89b7a234 242 this.numberOfChargingStations = 0;
d1c99c59
JB
243 const stationTemplateUrls = Configuration.getStationTemplateUrls();
244 if (!Utils.isEmptyArray(stationTemplateUrls)) {
245 this.numberOfChargingStationTemplates = stationTemplateUrls?.length;
246 stationTemplateUrls.forEach((stationTemplateUrl) => {
247 this.numberOfChargingStations += stationTemplateUrl.numberOfStations ?? 0;
248 });
249 } else {
250 console.warn(
251 chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
252 );
253 process.exit(exitCodes.missingChargingStationsConfiguration);
254 }
846d2851
JB
255 if (this.numberOfChargingStations === 0) {
256 console.warn(chalk.yellow('No charging station template enabled in configuration, exiting'));
257 process.exit(exitCodes.noChargingStationTemplates);
258 }
89b7a234 259 this.numberOfStartedChargingStations = 0;
7c72977b
JB
260 }
261
48d17ce2
JB
262 private logUncaughtException(): void {
263 process.on('uncaughtException', (error: Error) => {
264 console.error(chalk.red('Uncaught exception: '), error);
265 });
266 }
267
268 private logUnhandledRejection(): void {
269 process.on('unhandledRejection', (reason: unknown) => {
270 console.error(chalk.red('Unhandled rejection: '), reason);
271 });
272 }
273
e7aeea18
JB
274 private async startChargingStation(
275 index: number,
276 stationTemplateUrl: StationTemplateUrl
277 ): Promise<void> {
717c1e56
JB
278 const workerData: ChargingStationWorkerData = {
279 index,
e7aeea18 280 templateFile: path.join(
0d8140bd 281 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
e7aeea18
JB
282 'assets',
283 'station-templates',
ee5f26a2 284 stationTemplateUrl.file
e7aeea18 285 ),
717c1e56 286 };
72092cfc 287 await this.workerImplementation?.addElement(workerData);
717c1e56
JB
288 }
289
8b7072dc 290 private logPrefix = (): string => {
689dca78 291 return Utils.logPrefix(' Bootstrap |');
8b7072dc 292 };
ded13d97 293}