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