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