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