Optimize worker handlers calls by binding them to the current instance
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
CommitLineData
b4d34251
JB
1// Partial Copyright Jerome Benoit. 2021. All Rights Reserved.
2
8114d10e
JB
3import path from 'path';
4import { fileURLToPath } from 'url';
c72f6634 5import { type Worker, isMainThread } from 'worker_threads';
8114d10e
JB
6
7import chalk from 'chalk';
8
9import { version } from '../../package.json';
32de5a57 10import BaseError from '../exception/BaseError';
6c1761d4 11import type { Storage } from '../performance/storage/Storage';
8114d10e 12import { StorageFactory } from '../performance/storage/StorageFactory';
e7aeea18 13import {
32de5a57 14 ChargingStationData,
e7aeea18
JB
15 ChargingStationWorkerData,
16 ChargingStationWorkerMessage,
53e5fd67 17 ChargingStationWorkerMessageData,
e7aeea18
JB
18 ChargingStationWorkerMessageEvents,
19} from '../types/ChargingStationWorker';
6c1761d4 20import type { StationTemplateUrl } from '../types/ConfigurationData';
8a36b1eb 21import type { Statistics } from '../types/Statistics';
0e4fa348 22import type { MessageHandler } from '../types/Worker';
8114d10e 23import Configuration from '../utils/Configuration';
32de5a57 24import logger from '../utils/Logger';
ded13d97 25import Utils from '../utils/Utils';
6c1761d4 26import type WorkerAbstract from '../worker/WorkerAbstract';
ded13d97 27import WorkerFactory from '../worker/WorkerFactory';
8114d10e 28import { ChargingStationUtils } from './ChargingStationUtils';
6c1761d4 29import type { AbstractUIServer } from './ui-server/AbstractUIServer';
8114d10e 30import UIServerFactory from './ui-server/UIServerFactory';
ded13d97 31
32de5a57
LM
32const moduleName = 'Bootstrap';
33
a307349b
JB
34enum exitCodes {
35 missingChargingStationsConfiguration = 1,
36 noChargingStationTemplates = 2,
37}
e4cb2c14 38
5a010bf0 39export class Bootstrap {
535aaa27 40 private static instance: Bootstrap | null = null;
aa428a31 41 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null;
fe94fce0 42 private readonly uiServer!: AbstractUIServer;
6a49ad23 43 private readonly storage!: Storage;
7c72977b
JB
44 private numberOfChargingStationTemplates!: number;
45 private numberOfChargingStations!: number;
89b7a234 46 private numberOfStartedChargingStations!: number;
9e23580d 47 private readonly version: string = version;
eb87fe87 48 private started: boolean;
9e23580d 49 private readonly workerScript: string;
ded13d97
JB
50
51 private constructor() {
eb87fe87 52 this.started = false;
aa428a31 53 this.workerImplementation = null;
e7aeea18 54 this.workerScript = path.join(
0d8140bd 55 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
e7aeea18 56 'charging-station',
44a95b7f 57 'ChargingStationWorker' + path.extname(fileURLToPath(import.meta.url))
e7aeea18 58 );
7c72977b 59 this.initialize();
5af9aa8a 60 Configuration.getUIServer().enabled === true &&
976d11ec 61 (this.uiServer = UIServerFactory.getUIServerImplementation(Configuration.getUIServer()));
eb3abc4f 62 Configuration.getPerformanceStorage().enabled === true &&
e7aeea18
JB
63 (this.storage = StorageFactory.getStorage(
64 Configuration.getPerformanceStorage().type,
65 Configuration.getPerformanceStorage().uri,
66 this.logPrefix()
67 ));
7874b0b1 68 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
ded13d97
JB
69 }
70
71 public static getInstance(): Bootstrap {
1ca780f9 72 if (Bootstrap.instance === null) {
ded13d97
JB
73 Bootstrap.instance = new Bootstrap();
74 }
75 return Bootstrap.instance;
76 }
77
78 public async start(): Promise<void> {
452a82ca 79 if (isMainThread && this.started === false) {
ded13d97 80 try {
48d17ce2
JB
81 // Enable unconditionally for now
82 this.logUnhandledRejection();
83 this.logUncaughtException();
7c72977b 84 this.initialize();
6a49ad23 85 await this.storage?.open();
a4bc2942 86 await this.workerImplementation.start();
675fa8e3 87 this.uiServer?.start();
1f5df42a 88 const stationTemplateUrls = Configuration.getStationTemplateUrls();
7c72977b 89 this.numberOfChargingStationTemplates = stationTemplateUrls.length;
ded13d97 90 // Start ChargingStation object in worker thread
45bd0627 91 if (!Utils.isEmptyArray(stationTemplateUrls)) {
1f5df42a 92 for (const stationTemplateUrl of stationTemplateUrls) {
ded13d97 93 try {
1f5df42a 94 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
ded13d97 95 for (let index = 1; index <= nbStations; index++) {
717c1e56 96 await this.startChargingStation(index, stationTemplateUrl);
ded13d97
JB
97 }
98 } catch (error) {
e7aeea18
JB
99 console.error(
100 chalk.red(
3d25cc86
JB
101 'Error at starting charging station with template file ' +
102 stationTemplateUrl.file +
103 ': '
e7aeea18
JB
104 ),
105 error
106 );
ded13d97
JB
107 }
108 }
109 } else {
45bd0627
JB
110 console.warn(
111 chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
112 );
a307349b 113 process.exit(exitCodes.missingChargingStationsConfiguration);
ded13d97 114 }
a4bc2942 115 if (this.numberOfChargingStations === 0) {
e7aeea18
JB
116 console.warn(
117 chalk.yellow('No charging station template enabled in configuration, exiting')
118 );
a307349b 119 process.exit(exitCodes.noChargingStationTemplates);
ded13d97 120 } else {
32de5a57 121 console.info(
e7aeea18
JB
122 chalk.green(
123 `Charging stations simulator ${
124 this.version
7c72977b 125 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
17ac262c 126 ChargingStationUtils.workerDynamicPoolInUse()
cf2a5d9b 127 ? `${Configuration.getWorker().poolMinSize.toString()}/`
e7aeea18
JB
128 : ''
129 }${this.workerImplementation.size}${
17ac262c 130 ChargingStationUtils.workerPoolInUse()
cf2a5d9b 131 ? `/${Configuration.getWorker().poolMaxSize.toString()}`
17ac262c 132 : ''
cf2a5d9b 133 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
e7aeea18
JB
134 this.workerImplementation.maxElementsPerWorker
135 ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)`
136 : ''
137 }`
138 )
139 );
ded13d97 140 }
eb87fe87 141 this.started = true;
ded13d97 142 } catch (error) {
10d244c0 143 console.error(chalk.red('Bootstrap start error: '), error);
ded13d97 144 }
b322b8b4
JB
145 } else {
146 console.error(chalk.red('Cannot start an already started charging stations simulator'));
ded13d97
JB
147 }
148 }
149
150 public async stop(): Promise<void> {
452a82ca 151 if (isMainThread && this.started === true) {
a4bc2942 152 await this.workerImplementation.stop();
b19021e2 153 this.workerImplementation = null;
675fa8e3 154 this.uiServer?.stop();
6a49ad23 155 await this.storage?.close();
ba7965c4 156 this.started = false;
b322b8b4 157 } else {
ba7965c4 158 console.error(chalk.red('Cannot stop a not started charging stations simulator'));
ded13d97 159 }
ded13d97
JB
160 }
161
162 public async restart(): Promise<void> {
163 await this.stop();
7c72977b 164 this.initialize();
ded13d97
JB
165 await this.start();
166 }
167
ec7f4dce 168 private initializeWorkerImplementation(): void {
e2c77f10 169 this.workerImplementation === null &&
ec7f4dce
JB
170 (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
171 this.workerScript,
cf2a5d9b 172 Configuration.getWorker().processType,
ec7f4dce 173 {
cf2a5d9b
JB
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,
ec7f4dce 179 poolOptions: {
cf2a5d9b 180 workerChoiceStrategy: Configuration.getWorker().poolStrategy,
ec7f4dce 181 },
0e4fa348 182 messageHandler: this.messageHandler.bind(this) as MessageHandler<Worker>,
ec7f4dce
JB
183 }
184 ));
ded13d97 185 }
81797102 186
32de5a57 187 private messageHandler(
53e5fd67 188 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
32de5a57
LM
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
e2c77f10 226 private workerEventStarted = (data: ChargingStationData) => {
51c83d6f 227 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
89b7a234 228 ++this.numberOfStartedChargingStations;
56eb297e 229 logger.info(
e6159ce8 230 `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${
56eb297e 231 data.stationInfo.chargingStationId
e6159ce8 232 } (hashId: ${data.stationInfo.hashId}) started (${
56eb297e
JB
233 this.numberOfStartedChargingStations
234 } started from ${this.numberOfChargingStations})`
235 );
e2c77f10 236 };
32de5a57 237
e2c77f10 238 private workerEventStopped = (data: ChargingStationData) => {
51c83d6f 239 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
89b7a234 240 --this.numberOfStartedChargingStations;
56eb297e 241 logger.info(
e6159ce8 242 `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${
56eb297e 243 data.stationInfo.chargingStationId
e6159ce8 244 } (hashId: ${data.stationInfo.hashId}) stopped (${
56eb297e
JB
245 this.numberOfStartedChargingStations
246 } started from ${this.numberOfChargingStations})`
247 );
e2c77f10 248 };
32de5a57 249
e2c77f10 250 private workerEventUpdated = (data: ChargingStationData) => {
51c83d6f 251 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
e2c77f10 252 };
32de5a57
LM
253
254 private workerEventPerformanceStatistics = (data: Statistics) => {
255 this.storage.storePerformanceStatistics(data) as void;
256 };
257
7c72977b 258 private initialize() {
7c72977b 259 this.numberOfChargingStationTemplates = 0;
89b7a234
JB
260 this.numberOfChargingStations = 0;
261 this.numberOfStartedChargingStations = 0;
ec7f4dce 262 this.initializeWorkerImplementation();
7c72977b
JB
263 }
264
48d17ce2
JB
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
e7aeea18
JB
277 private async startChargingStation(
278 index: number,
279 stationTemplateUrl: StationTemplateUrl
280 ): Promise<void> {
717c1e56
JB
281 const workerData: ChargingStationWorkerData = {
282 index,
e7aeea18 283 templateFile: path.join(
0d8140bd 284 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
e7aeea18
JB
285 'assets',
286 'station-templates',
ee5f26a2 287 stationTemplateUrl.file
e7aeea18 288 ),
717c1e56
JB
289 };
290 await this.workerImplementation.addElement(workerData);
89b7a234 291 ++this.numberOfChargingStations;
717c1e56
JB
292 }
293
81797102 294 private logPrefix(): string {
689dca78 295 return Utils.logPrefix(' Bootstrap |');
81797102 296 }
ded13d97 297}