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