refactor(simulator): move configuration checks at initialization
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
2
3 import path from 'node:path';
4 import { fileURLToPath } from 'node:url';
5 import { type Worker, isMainThread } from 'worker_threads';
6
7 import chalk from 'chalk';
8
9 import { ChargingStationUtils } from './ChargingStationUtils';
10 import type { AbstractUIServer } from './ui-server/AbstractUIServer';
11 import UIServerFactory from './ui-server/UIServerFactory';
12 import { version } from '../../package.json';
13 import BaseError from '../exception/BaseError';
14 import type { Storage } from '../performance/storage/Storage';
15 import { StorageFactory } from '../performance/storage/StorageFactory';
16 import {
17 type ChargingStationData,
18 type ChargingStationWorkerData,
19 type ChargingStationWorkerMessage,
20 type ChargingStationWorkerMessageData,
21 ChargingStationWorkerMessageEvents,
22 } from '../types/ChargingStationWorker';
23 import type { StationTemplateUrl } from '../types/ConfigurationData';
24 import type { Statistics } from '../types/Statistics';
25 import type { MessageHandler } from '../types/Worker';
26 import Configuration from '../utils/Configuration';
27 import logger from '../utils/Logger';
28 import Utils from '../utils/Utils';
29 import type WorkerAbstract from '../worker/WorkerAbstract';
30 import WorkerFactory from '../worker/WorkerFactory';
31
32 const moduleName = 'Bootstrap';
33
34 enum exitCodes {
35 missingChargingStationsConfiguration = 1,
36 noChargingStationTemplates = 2,
37 }
38
39 export class Bootstrap {
40 private static instance: Bootstrap | null = null;
41 public numberOfChargingStations!: number;
42 public numberOfChargingStationTemplates!: number;
43 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null;
44 private readonly uiServer!: AbstractUIServer | null;
45 private readonly storage!: Storage;
46 private numberOfStartedChargingStations!: number;
47 private readonly version: string = version;
48 private started: boolean;
49 private readonly workerScript: string;
50
51 private constructor() {
52 this.started = false;
53 this.workerImplementation = null;
54 this.workerScript = path.join(
55 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
56 'charging-station',
57 `ChargingStationWorker${path.extname(fileURLToPath(import.meta.url))}`
58 );
59 this.initialize();
60 Configuration.getUIServer().enabled === true &&
61 (this.uiServer = UIServerFactory.getUIServerImplementation(Configuration.getUIServer()));
62 Configuration.getPerformanceStorage().enabled === true &&
63 (this.storage = StorageFactory.getStorage(
64 Configuration.getPerformanceStorage().type,
65 Configuration.getPerformanceStorage().uri,
66 this.logPrefix()
67 ));
68 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
69 }
70
71 public static getInstance(): Bootstrap {
72 if (Bootstrap.instance === null) {
73 Bootstrap.instance = new Bootstrap();
74 }
75 return Bootstrap.instance;
76 }
77
78 public async start(): Promise<void> {
79 if (isMainThread && this.started === false) {
80 try {
81 // Enable unconditionally for now
82 this.logUnhandledRejection();
83 this.logUncaughtException();
84 this.initialize();
85 await this.storage?.open();
86 await this.workerImplementation?.start();
87 this.uiServer?.start();
88 const stationTemplateUrls = Configuration.getStationTemplateUrls();
89 // Start ChargingStation object in worker thread
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);
95 }
96 } catch (error) {
97 console.error(
98 chalk.red(
99 `Error at starting charging station with template file ${stationTemplateUrl.file}: `
100 ),
101 error
102 );
103 }
104 }
105 console.info(
106 chalk.green(
107 `Charging stations simulator ${
108 this.version
109 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
110 ChargingStationUtils.workerDynamicPoolInUse()
111 ? `${Configuration.getWorker().poolMinSize?.toString()}/`
112 : ''
113 }${this.workerImplementation?.size}${
114 ChargingStationUtils.workerPoolInUse()
115 ? `/${Configuration.getWorker().poolMaxSize?.toString()}`
116 : ''
117 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
118 !Utils.isNullOrUndefined(this.workerImplementation?.maxElementsPerWorker)
119 ? ` (${this.workerImplementation?.maxElementsPerWorker} charging station(s) per worker)`
120 : ''
121 }`
122 )
123 );
124 this.started = true;
125 } catch (error) {
126 console.error(chalk.red('Bootstrap start error: '), error);
127 }
128 } else {
129 console.error(chalk.red('Cannot start an already started charging stations simulator'));
130 }
131 }
132
133 public async stop(): Promise<void> {
134 if (isMainThread && this.started === true) {
135 await this.workerImplementation?.stop();
136 this.workerImplementation = null;
137 this.uiServer?.stop();
138 await this.storage?.close();
139 this.started = false;
140 } else {
141 console.error(chalk.red('Cannot stop a not started charging stations simulator'));
142 }
143 }
144
145 public async restart(): Promise<void> {
146 await this.stop();
147 this.initialize();
148 await this.start();
149 }
150
151 private initializeWorkerImplementation(): void {
152 this.workerImplementation === null &&
153 (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
154 this.workerScript,
155 Configuration.getWorker().processType,
156 {
157 workerStartDelay: Configuration.getWorker().startDelay,
158 elementStartDelay: Configuration.getWorker().elementStartDelay,
159 poolMaxSize: Configuration.getWorker().poolMaxSize,
160 poolMinSize: Configuration.getWorker().poolMinSize,
161 elementsPerWorker: Configuration.getWorker().elementsPerWorker,
162 poolOptions: {
163 workerChoiceStrategy: Configuration.getWorker().poolStrategy,
164 },
165 messageHandler: this.messageHandler.bind(this) as MessageHandler<Worker>,
166 }
167 ));
168 }
169
170 private messageHandler(
171 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
172 ): void {
173 // logger.debug(
174 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
175 // msg,
176 // null,
177 // 2
178 // )}`
179 // );
180 try {
181 switch (msg.id) {
182 case ChargingStationWorkerMessageEvents.STARTED:
183 this.workerEventStarted(msg.data as ChargingStationData);
184 break;
185 case ChargingStationWorkerMessageEvents.STOPPED:
186 this.workerEventStopped(msg.data as ChargingStationData);
187 break;
188 case ChargingStationWorkerMessageEvents.UPDATED:
189 this.workerEventUpdated(msg.data as ChargingStationData);
190 break;
191 case ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS:
192 this.workerEventPerformanceStatistics(msg.data as Statistics);
193 break;
194 default:
195 throw new BaseError(
196 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
197 );
198 }
199 } catch (error) {
200 logger.error(
201 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
202 msg.id
203 }' event:`,
204 error
205 );
206 }
207 }
208
209 private workerEventStarted = (data: ChargingStationData) => {
210 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
211 ++this.numberOfStartedChargingStations;
212 logger.info(
213 `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${
214 data.stationInfo.chargingStationId
215 } (hashId: ${data.stationInfo.hashId}) started (${
216 this.numberOfStartedChargingStations
217 } started from ${this.numberOfChargingStations})`
218 );
219 };
220
221 private workerEventStopped = (data: ChargingStationData) => {
222 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
223 --this.numberOfStartedChargingStations;
224 logger.info(
225 `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${
226 data.stationInfo.chargingStationId
227 } (hashId: ${data.stationInfo.hashId}) stopped (${
228 this.numberOfStartedChargingStations
229 } started from ${this.numberOfChargingStations})`
230 );
231 };
232
233 private workerEventUpdated = (data: ChargingStationData) => {
234 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
235 };
236
237 private workerEventPerformanceStatistics = (data: Statistics) => {
238 this.storage.storePerformanceStatistics(data) as void;
239 };
240
241 private initialize() {
242 this.numberOfChargingStationTemplates = 0;
243 this.numberOfChargingStations = 0;
244 const stationTemplateUrls = Configuration.getStationTemplateUrls();
245 if (!Utils.isEmptyArray(stationTemplateUrls)) {
246 this.numberOfChargingStationTemplates = stationTemplateUrls?.length;
247 stationTemplateUrls.forEach((stationTemplateUrl) => {
248 this.numberOfChargingStations += stationTemplateUrl.numberOfStations ?? 0;
249 });
250 } else {
251 console.warn(
252 chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
253 );
254 process.exit(exitCodes.missingChargingStationsConfiguration);
255 }
256 if (this.numberOfChargingStations === 0) {
257 console.warn(chalk.yellow('No charging station template enabled in configuration, exiting'));
258 process.exit(exitCodes.noChargingStationTemplates);
259 }
260 this.numberOfStartedChargingStations = 0;
261 this.initializeWorkerImplementation();
262 }
263
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
276 private async startChargingStation(
277 index: number,
278 stationTemplateUrl: StationTemplateUrl
279 ): Promise<void> {
280 const workerData: ChargingStationWorkerData = {
281 index,
282 templateFile: path.join(
283 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
284 'assets',
285 'station-templates',
286 stationTemplateUrl.file
287 ),
288 };
289 await this.workerImplementation?.addElement(workerData);
290 }
291
292 private logPrefix = (): string => {
293 return Utils.logPrefix(' Bootstrap |');
294 };
295 }