2bf7159539988aca847ea9d60539542dc65ddbab
[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.initializeCounters();
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.initializeCounters();
85 this.initializeWorkerImplementation();
86 await this.storage?.open();
87 await this.workerImplementation?.start();
88 this.uiServer?.start();
89 const stationTemplateUrls = Configuration.getStationTemplateUrls();
90 // Start ChargingStation object in worker thread
91 for (const stationTemplateUrl of stationTemplateUrls) {
92 try {
93 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
94 for (let index = 1; index <= nbStations; index++) {
95 await this.startChargingStation(index, stationTemplateUrl);
96 }
97 } catch (error) {
98 console.error(
99 chalk.red(
100 `Error at starting charging station with template file ${stationTemplateUrl.file}: `
101 ),
102 error
103 );
104 }
105 }
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;
126 } catch (error) {
127 console.error(chalk.red('Bootstrap start error: '), error);
128 }
129 } else {
130 console.error(chalk.red('Cannot start an already started charging stations simulator'));
131 }
132 }
133
134 public async stop(): Promise<void> {
135 if (isMainThread && this.started === true) {
136 await this.workerImplementation?.stop();
137 this.workerImplementation = null;
138 this.uiServer?.stop();
139 await this.storage?.close();
140 this.started = false;
141 } else {
142 console.error(chalk.red('Cannot stop a not started charging stations simulator'));
143 }
144 }
145
146 public async restart(): Promise<void> {
147 await this.stop();
148 this.initializeCounters();
149 this.initializeWorkerImplementation();
150 await this.start();
151 }
152
153 private initializeWorkerImplementation(): void {
154 this.workerImplementation === null &&
155 (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
156 this.workerScript,
157 Configuration.getWorker().processType,
158 {
159 workerStartDelay: Configuration.getWorker().startDelay,
160 elementStartDelay: Configuration.getWorker().elementStartDelay,
161 poolMaxSize: Configuration.getWorker().poolMaxSize,
162 poolMinSize: Configuration.getWorker().poolMinSize,
163 elementsPerWorker: Configuration.getWorker().elementsPerWorker,
164 poolOptions: {
165 workerChoiceStrategy: Configuration.getWorker().poolStrategy,
166 },
167 messageHandler: this.messageHandler.bind(this) as MessageHandler<Worker>,
168 }
169 ));
170 }
171
172 private messageHandler(
173 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
174 ): void {
175 // logger.debug(
176 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
177 // msg,
178 // null,
179 // 2
180 // )}`
181 // );
182 try {
183 switch (msg.id) {
184 case ChargingStationWorkerMessageEvents.STARTED:
185 this.workerEventStarted(msg.data as ChargingStationData);
186 break;
187 case ChargingStationWorkerMessageEvents.STOPPED:
188 this.workerEventStopped(msg.data as ChargingStationData);
189 break;
190 case ChargingStationWorkerMessageEvents.UPDATED:
191 this.workerEventUpdated(msg.data as ChargingStationData);
192 break;
193 case ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS:
194 this.workerEventPerformanceStatistics(msg.data as Statistics);
195 break;
196 default:
197 throw new BaseError(
198 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
199 );
200 }
201 } catch (error) {
202 logger.error(
203 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
204 msg.id
205 }' event:`,
206 error
207 );
208 }
209 }
210
211 private workerEventStarted = (data: ChargingStationData) => {
212 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
213 ++this.numberOfStartedChargingStations;
214 logger.info(
215 `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${
216 data.stationInfo.chargingStationId
217 } (hashId: ${data.stationInfo.hashId}) started (${
218 this.numberOfStartedChargingStations
219 } started from ${this.numberOfChargingStations})`
220 );
221 };
222
223 private workerEventStopped = (data: ChargingStationData) => {
224 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
225 --this.numberOfStartedChargingStations;
226 logger.info(
227 `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${
228 data.stationInfo.chargingStationId
229 } (hashId: ${data.stationInfo.hashId}) stopped (${
230 this.numberOfStartedChargingStations
231 } started from ${this.numberOfChargingStations})`
232 );
233 };
234
235 private workerEventUpdated = (data: ChargingStationData) => {
236 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
237 };
238
239 private workerEventPerformanceStatistics = (data: Statistics) => {
240 this.storage.storePerformanceStatistics(data) as void;
241 };
242
243 private initializeCounters() {
244 this.numberOfChargingStationTemplates = 0;
245 this.numberOfChargingStations = 0;
246 const stationTemplateUrls = Configuration.getStationTemplateUrls();
247 if (!Utils.isEmptyArray(stationTemplateUrls)) {
248 this.numberOfChargingStationTemplates = stationTemplateUrls?.length;
249 stationTemplateUrls.forEach((stationTemplateUrl) => {
250 this.numberOfChargingStations += stationTemplateUrl.numberOfStations ?? 0;
251 });
252 } else {
253 console.warn(
254 chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
255 );
256 process.exit(exitCodes.missingChargingStationsConfiguration);
257 }
258 if (this.numberOfChargingStations === 0) {
259 console.warn(chalk.yellow('No charging station template enabled in configuration, exiting'));
260 process.exit(exitCodes.noChargingStationTemplates);
261 }
262 this.numberOfStartedChargingStations = 0;
263 }
264
265 private logUncaughtException(): void {
266 process.on('uncaughtException', (error: Error) => {
267 console.error(chalk.red('Uncaught exception: '), error);
268 });
269 }
270
271 private logUnhandledRejection(): void {
272 process.on('unhandledRejection', (reason: unknown) => {
273 console.error(chalk.red('Unhandled rejection: '), reason);
274 });
275 }
276
277 private async startChargingStation(
278 index: number,
279 stationTemplateUrl: StationTemplateUrl
280 ): Promise<void> {
281 const workerData: ChargingStationWorkerData = {
282 index,
283 templateFile: path.join(
284 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
285 'assets',
286 'station-templates',
287 stationTemplateUrl.file
288 ),
289 };
290 await this.workerImplementation?.addElement(workerData);
291 }
292
293 private logPrefix = (): string => {
294 return Utils.logPrefix(' Bootstrap |');
295 };
296 }