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