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