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