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