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