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