fix(simulator): initialize charging station worker outside the
[e-mobility-charging-stations-simulator.git] / src / charging-station / Bootstrap.ts
CommitLineData
edd13439 1// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
b4d34251 2
130783a7
JB
3import path from 'node:path';
4import { fileURLToPath } from 'node:url';
c72f6634 5import { type Worker, isMainThread } from 'worker_threads';
8114d10e
JB
6
7import chalk from 'chalk';
8
78202038
JB
9import { ChargingStationUtils } from './ChargingStationUtils';
10import type { AbstractUIServer } from './ui-server/AbstractUIServer';
11import UIServerFactory from './ui-server/UIServerFactory';
8114d10e 12import { version } from '../../package.json';
32de5a57 13import BaseError from '../exception/BaseError';
6c1761d4 14import type { Storage } from '../performance/storage/Storage';
8114d10e 15import { StorageFactory } from '../performance/storage/StorageFactory';
e7aeea18 16import {
bbe10d5f
JB
17 type ChargingStationData,
18 type ChargingStationWorkerData,
19 type ChargingStationWorkerMessage,
20 type ChargingStationWorkerMessageData,
e7aeea18
JB
21 ChargingStationWorkerMessageEvents,
22} from '../types/ChargingStationWorker';
6c1761d4 23import type { StationTemplateUrl } from '../types/ConfigurationData';
8a36b1eb 24import type { Statistics } from '../types/Statistics';
0e4fa348 25import type { MessageHandler } from '../types/Worker';
8114d10e 26import Configuration from '../utils/Configuration';
32de5a57 27import logger from '../utils/Logger';
ded13d97 28import Utils from '../utils/Utils';
6c1761d4 29import type WorkerAbstract from '../worker/WorkerAbstract';
ded13d97 30import WorkerFactory from '../worker/WorkerFactory';
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;
d1c99c59
JB
41 public numberOfChargingStations!: number;
42 public numberOfChargingStationTemplates!: number;
aa428a31 43 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null;
551e477c 44 private readonly uiServer!: AbstractUIServer | null;
6a49ad23 45 private readonly storage!: Storage;
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',
44eb6026 57 `ChargingStationWorker${path.extname(fileURLToPath(import.meta.url))}`
e7aeea18 58 );
326cec2d 59 this.initializeCounters();
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();
326cec2d
JB
84 this.initializeCounters();
85 this.initializeWorkerImplementation();
6a49ad23 86 await this.storage?.open();
1895299d 87 await this.workerImplementation?.start();
675fa8e3 88 this.uiServer?.start();
1f5df42a 89 const stationTemplateUrls = Configuration.getStationTemplateUrls();
ded13d97 90 // Start ChargingStation object in worker thread
d1c99c59
JB
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);
ded13d97 96 }
d1c99c59
JB
97 } catch (error) {
98 console.error(
99 chalk.red(
100 `Error at starting charging station with template file ${stationTemplateUrl.file}: `
101 ),
102 error
103 );
ded13d97 104 }
ded13d97 105 }
846d2851
JB
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 );
eb87fe87 125 this.started = true;
ded13d97 126 } catch (error) {
10d244c0 127 console.error(chalk.red('Bootstrap start error: '), error);
ded13d97 128 }
b322b8b4
JB
129 } else {
130 console.error(chalk.red('Cannot start an already started charging stations simulator'));
ded13d97
JB
131 }
132 }
133
134 public async stop(): Promise<void> {
452a82ca 135 if (isMainThread && this.started === true) {
1895299d 136 await this.workerImplementation?.stop();
b19021e2 137 this.workerImplementation = null;
675fa8e3 138 this.uiServer?.stop();
6a49ad23 139 await this.storage?.close();
ba7965c4 140 this.started = false;
b322b8b4 141 } else {
ba7965c4 142 console.error(chalk.red('Cannot stop a not started charging stations simulator'));
ded13d97 143 }
ded13d97
JB
144 }
145
146 public async restart(): Promise<void> {
147 await this.stop();
326cec2d
JB
148 this.initializeCounters();
149 this.initializeWorkerImplementation();
ded13d97
JB
150 await this.start();
151 }
152
ec7f4dce 153 private initializeWorkerImplementation(): void {
e2c77f10 154 this.workerImplementation === null &&
ec7f4dce
JB
155 (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
156 this.workerScript,
cf2a5d9b 157 Configuration.getWorker().processType,
ec7f4dce 158 {
cf2a5d9b
JB
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,
ec7f4dce 164 poolOptions: {
cf2a5d9b 165 workerChoiceStrategy: Configuration.getWorker().poolStrategy,
ec7f4dce 166 },
0e4fa348 167 messageHandler: this.messageHandler.bind(this) as MessageHandler<Worker>,
ec7f4dce
JB
168 }
169 ));
ded13d97 170 }
81797102 171
32de5a57 172 private messageHandler(
53e5fd67 173 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
32de5a57
LM
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
e2c77f10 211 private workerEventStarted = (data: ChargingStationData) => {
51c83d6f 212 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
89b7a234 213 ++this.numberOfStartedChargingStations;
56eb297e 214 logger.info(
e6159ce8 215 `${this.logPrefix()} ${moduleName}.workerEventStarted: Charging station ${
56eb297e 216 data.stationInfo.chargingStationId
e6159ce8 217 } (hashId: ${data.stationInfo.hashId}) started (${
56eb297e
JB
218 this.numberOfStartedChargingStations
219 } started from ${this.numberOfChargingStations})`
220 );
e2c77f10 221 };
32de5a57 222
e2c77f10 223 private workerEventStopped = (data: ChargingStationData) => {
51c83d6f 224 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
89b7a234 225 --this.numberOfStartedChargingStations;
56eb297e 226 logger.info(
e6159ce8 227 `${this.logPrefix()} ${moduleName}.workerEventStopped: Charging station ${
56eb297e 228 data.stationInfo.chargingStationId
e6159ce8 229 } (hashId: ${data.stationInfo.hashId}) stopped (${
56eb297e
JB
230 this.numberOfStartedChargingStations
231 } started from ${this.numberOfChargingStations})`
232 );
e2c77f10 233 };
32de5a57 234
e2c77f10 235 private workerEventUpdated = (data: ChargingStationData) => {
51c83d6f 236 this.uiServer?.chargingStations.set(data.stationInfo.hashId, data);
e2c77f10 237 };
32de5a57
LM
238
239 private workerEventPerformanceStatistics = (data: Statistics) => {
240 this.storage.storePerformanceStatistics(data) as void;
241 };
242
326cec2d 243 private initializeCounters() {
7c72977b 244 this.numberOfChargingStationTemplates = 0;
89b7a234 245 this.numberOfChargingStations = 0;
d1c99c59
JB
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 }
846d2851
JB
258 if (this.numberOfChargingStations === 0) {
259 console.warn(chalk.yellow('No charging station template enabled in configuration, exiting'));
260 process.exit(exitCodes.noChargingStationTemplates);
261 }
89b7a234 262 this.numberOfStartedChargingStations = 0;
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 289 };
72092cfc 290 await this.workerImplementation?.addElement(workerData);
717c1e56
JB
291 }
292
8b7072dc 293 private logPrefix = (): string => {
689dca78 294 return Utils.logPrefix(' Bootstrap |');
8b7072dc 295 };
ded13d97 296}