Optimize worker handlers calls by binding them to the current instance
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
1 // Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
3 import path from 'path';
4 import { fileURLToPath } from 'url';
5 import { type Worker, isMainThread } from 'worker_threads';
6
7 import chalk from 'chalk';
8
9 import { version } from '../../package.json';
10 import BaseError from '../exception/BaseError';
11 import type { Storage } from '../performance/storage/Storage';
12 import { StorageFactory } from '../performance/storage/StorageFactory';
13 import {
14 ChargingStationData,
15 ChargingStationWorkerData,
16 ChargingStationWorkerMessage,
17 ChargingStationWorkerMessageData,
18 ChargingStationWorkerMessageEvents,
19 } from '../types/ChargingStationWorker';
20 import type { StationTemplateUrl } from '../types/ConfigurationData';
21 import type { Statistics } from '../types/Statistics';
22 import type { MessageHandler } from '../types/Worker';
23 import Configuration from '../utils/Configuration';
24 import logger from '../utils/Logger';
25 import Utils from '../utils/Utils';
26 import type WorkerAbstract from '../worker/WorkerAbstract';
27 import WorkerFactory from '../worker/WorkerFactory';
28 import { ChargingStationUtils } from './ChargingStationUtils';
29 import type { AbstractUIServer } from './ui-server/AbstractUIServer';
30 import UIServerFactory from './ui-server/UIServerFactory';
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 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null;
42 private readonly uiServer!: AbstractUIServer;
43 private readonly storage!: Storage;
44 private numberOfChargingStationTemplates!: number;
45 private numberOfChargingStations!: number;
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 this.numberOfChargingStationTemplates = stationTemplateUrls.length;
90 // Start ChargingStation object in worker thread
91 if (!Utils.isEmptyArray(stationTemplateUrls)) {
92 for (const stationTemplateUrl of stationTemplateUrls) {
93 try {
94 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
95 for (let index = 1; index <= nbStations; index++) {
96 await this.startChargingStation(index, stationTemplateUrl);
97 }
98 } catch (error) {
99 console.error(
100 chalk.red(
101 'Error at starting charging station with template file ' +
102 stationTemplateUrl.file +
103 ': '
104 ),
105 error
106 );
107 }
108 }
109 } else {
110 console.warn(
111 chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
112 );
113 process.exit(exitCodes.missingChargingStationsConfiguration);
114 }
115 if (this.numberOfChargingStations === 0) {
116 console.warn(
117 chalk.yellow('No charging station template enabled in configuration, exiting')
118 );
119 process.exit(exitCodes.noChargingStationTemplates);
120 } else {
121 console.info(
122 chalk.green(
123 `Charging stations simulator ${
124 this.version
125 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
126 ChargingStationUtils.workerDynamicPoolInUse()
127 ? `${Configuration.getWorker().poolMinSize.toString()}/`
128 : ''
129 }${this.workerImplementation.size}${
130 ChargingStationUtils.workerPoolInUse()
131 ? `/${Configuration.getWorker().poolMaxSize.toString()}`
132 : ''
133 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
134 this.workerImplementation.maxElementsPerWorker
135 ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)`
136 : ''
137 }`
138 )
139 );
140 }
141 this.started = true;
142 } catch (error) {
143 console.error(chalk.red('Bootstrap start error: '), error);
144 }
145 } else {
146 console.error(chalk.red('Cannot start an already started charging stations simulator'));
147 }
148 }
149
150 public async stop(): Promise<void> {
151 if (isMainThread && this.started === true) {
152 await this.workerImplementation.stop();
153 this.workerImplementation = null;
154 this.uiServer?.stop();
155 await this.storage?.close();
156 this.started = false;
157 } else {
158 console.error(chalk.red('Cannot stop a not started charging stations simulator'));
159 }
160 }
161
162 public async restart(): Promise<void> {
163 await this.stop();
164 this.initialize();
165 await this.start();
166 }
167
168 private initializeWorkerImplementation(): void {
169 this.workerImplementation === null &&
170 (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
171 this.workerScript,
172 Configuration.getWorker().processType,
173 {
174 workerStartDelay: Configuration.getWorker().startDelay,
175 elementStartDelay: Configuration.getWorker().elementStartDelay,
176 poolMaxSize: Configuration.getWorker().poolMaxSize,
177 poolMinSize: Configuration.getWorker().poolMinSize,
178 elementsPerWorker: Configuration.getWorker().elementsPerWorker,
179 poolOptions: {
180 workerChoiceStrategy: Configuration.getWorker().poolStrategy,
181 },
182 messageHandler: this.messageHandler.bind(this) as MessageHandler<Worker>,
183 }
184 ));
185 }
186
187 private messageHandler(
188 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
189 ): void {
190 // logger.debug(
191 // `${this.logPrefix()} ${moduleName}.messageHandler: Worker channel message received: ${JSON.stringify(
192 // msg,
193 // null,
194 // 2
195 // )}`
196 // );
197 try {
198 switch (msg.id) {
199 case ChargingStationWorkerMessageEvents.STARTED:
200 this.workerEventStarted(msg.data as ChargingStationData);
201 break;
202 case ChargingStationWorkerMessageEvents.STOPPED:
203 this.workerEventStopped(msg.data as ChargingStationData);
204 break;
205 case ChargingStationWorkerMessageEvents.UPDATED:
206 this.workerEventUpdated(msg.data as ChargingStationData);
207 break;
208 case ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS:
209 this.workerEventPerformanceStatistics(msg.data as Statistics);
210 break;
211 default:
212 throw new BaseError(
213 `Unknown event type: '${msg.id}' for data: ${JSON.stringify(msg.data, null, 2)}`
214 );
215 }
216 } catch (error) {
217 logger.error(
218 `${this.logPrefix()} ${moduleName}.messageHandler: Error occurred while handling '${
219 msg.id
220 }' event:`,
221 error
222 );
223 }
224 }
225
226 private workerEventStarted = (data: ChargingStationData) => {
227 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
228 ++this.numberOfStartedChargingStations;
229 logger.info(
230 `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${
231 data.stationInfo.chargingStationId
232 } (hashId: ${data.stationInfo.hashId}) started (${
233 this.numberOfStartedChargingStations
234 } started from ${this.numberOfChargingStations})`
235 );
236 };
237
238 private workerEventStopped = (data: ChargingStationData) => {
239 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
240 --this.numberOfStartedChargingStations;
241 logger.info(
242 `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${
243 data.stationInfo.chargingStationId
244 } (hashId: ${data.stationInfo.hashId}) stopped (${
245 this.numberOfStartedChargingStations
246 } started from ${this.numberOfChargingStations})`
247 );
248 };
249
250 private workerEventUpdated = (data: ChargingStationData) => {
251 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
252 };
253
254 private workerEventPerformanceStatistics = (data: Statistics) => {
255 this.storage.storePerformanceStatistics(data) as void;
256 };
257
258 private initialize() {
259 this.numberOfChargingStationTemplates = 0;
260 this.numberOfChargingStations = 0;
261 this.numberOfStartedChargingStations = 0;
262 this.initializeWorkerImplementation();
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 ++this.numberOfChargingStations;
292 }
293
294 private logPrefix(): string {
295 return Utils.logPrefix(' Bootstrap |');
296 }
297 }