Add UI HTTP server (#6)
[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';
5import { isMainThread } from 'worker_threads';
6
7import chalk from 'chalk';
8
9import { version } from '../../package.json';
32de5a57 10import BaseError from '../exception/BaseError';
8114d10e
JB
11import { Storage } from '../performance/storage/Storage';
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';
717c1e56 20import { StationTemplateUrl } from '../types/ConfigurationData';
c3ee95af 21import Statistics from '../types/Statistics';
8114d10e 22import Configuration from '../utils/Configuration';
32de5a57 23import logger from '../utils/Logger';
ded13d97 24import Utils from '../utils/Utils';
fd1fdf1b 25import WorkerAbstract from '../worker/WorkerAbstract';
ded13d97 26import WorkerFactory from '../worker/WorkerFactory';
8114d10e
JB
27import { ChargingStationUtils } from './ChargingStationUtils';
28import { AbstractUIServer } from './ui-server/AbstractUIServer';
29import { UIServiceUtils } from './ui-server/ui-services/UIServiceUtils';
30import UIServerFactory from './ui-server/UIServerFactory';
ded13d97 31
32de5a57
LM
32const moduleName = 'Bootstrap';
33
e4cb2c14
JB
34const missingChargingStationsConfigurationExitCode = 1;
35const noChargingStationTemplatesExitCode = 2;
36
5a010bf0 37export class Bootstrap {
535aaa27 38 private static instance: Bootstrap | null = null;
c3ee95af 39 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null = null;
fe94fce0 40 private readonly uiServer!: AbstractUIServer;
6a49ad23 41 private readonly storage!: Storage;
7c72977b
JB
42 private numberOfChargingStationTemplates!: number;
43 private numberOfChargingStations!: number;
89b7a234 44 private numberOfStartedChargingStations!: number;
9e23580d 45 private readonly version: string = version;
eb87fe87 46 private started: boolean;
9e23580d 47 private readonly workerScript: string;
ded13d97
JB
48
49 private constructor() {
eb87fe87 50 this.started = false;
e7aeea18 51 this.workerScript = path.join(
0d8140bd 52 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
e7aeea18 53 'charging-station',
44a95b7f 54 'ChargingStationWorker' + path.extname(fileURLToPath(import.meta.url))
e7aeea18 55 );
7c72977b 56 this.initialize();
675fa8e3 57 Configuration.getUIServer().enabled &&
1f7fa4de 58 (this.uiServer = UIServerFactory.getUIServerImplementation(Configuration.getUIServer().type, {
675fa8e3 59 ...Configuration.getUIServer().options,
e7aeea18
JB
60 handleProtocols: UIServiceUtils.handleProtocols,
61 }));
62 Configuration.getPerformanceStorage().enabled &&
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> {
eb87fe87 79 if (isMainThread && !this.started) {
ded13d97 80 try {
7c72977b 81 this.initialize();
6a49ad23 82 await this.storage?.open();
a4bc2942 83 await this.workerImplementation.start();
675fa8e3 84 this.uiServer?.start();
1f5df42a 85 const stationTemplateUrls = Configuration.getStationTemplateUrls();
7c72977b 86 this.numberOfChargingStationTemplates = stationTemplateUrls.length;
ded13d97 87 // Start ChargingStation object in worker thread
45bd0627 88 if (!Utils.isEmptyArray(stationTemplateUrls)) {
1f5df42a 89 for (const stationTemplateUrl of stationTemplateUrls) {
ded13d97 90 try {
1f5df42a 91 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
ded13d97 92 for (let index = 1; index <= nbStations; index++) {
717c1e56 93 await this.startChargingStation(index, stationTemplateUrl);
ded13d97
JB
94 }
95 } catch (error) {
e7aeea18
JB
96 console.error(
97 chalk.red(
3d25cc86
JB
98 'Error at starting charging station with template file ' +
99 stationTemplateUrl.file +
100 ': '
e7aeea18
JB
101 ),
102 error
103 );
ded13d97
JB
104 }
105 }
106 } else {
45bd0627
JB
107 console.warn(
108 chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
109 );
e4cb2c14 110 process.exit(missingChargingStationsConfigurationExitCode);
ded13d97 111 }
a4bc2942 112 if (this.numberOfChargingStations === 0) {
e7aeea18
JB
113 console.warn(
114 chalk.yellow('No charging station template enabled in configuration, exiting')
115 );
e4cb2c14 116 process.exit(noChargingStationTemplatesExitCode);
ded13d97 117 } else {
32de5a57 118 console.info(
e7aeea18
JB
119 chalk.green(
120 `Charging stations simulator ${
121 this.version
7c72977b 122 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
17ac262c 123 ChargingStationUtils.workerDynamicPoolInUse()
cf2a5d9b 124 ? `${Configuration.getWorker().poolMinSize.toString()}/`
e7aeea18
JB
125 : ''
126 }${this.workerImplementation.size}${
17ac262c 127 ChargingStationUtils.workerPoolInUse()
cf2a5d9b 128 ? `/${Configuration.getWorker().poolMaxSize.toString()}`
17ac262c 129 : ''
cf2a5d9b 130 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
e7aeea18
JB
131 this.workerImplementation.maxElementsPerWorker
132 ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)`
133 : ''
134 }`
135 )
136 );
ded13d97 137 }
eb87fe87 138 this.started = true;
ded13d97 139 } catch (error) {
8eac9a09 140 console.error(chalk.red('Bootstrap start error '), error);
ded13d97 141 }
b322b8b4
JB
142 } else {
143 console.error(chalk.red('Cannot start an already started charging stations simulator'));
ded13d97
JB
144 }
145 }
146
147 public async stop(): Promise<void> {
eb87fe87 148 if (isMainThread && this.started) {
a4bc2942 149 await this.workerImplementation.stop();
b19021e2 150 this.workerImplementation = null;
675fa8e3 151 this.uiServer?.stop();
6a49ad23 152 await this.storage?.close();
b322b8b4
JB
153 } else {
154 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
ded13d97 155 }
eb87fe87 156 this.started = false;
ded13d97
JB
157 }
158
159 public async restart(): Promise<void> {
160 await this.stop();
7c72977b 161 this.initialize();
ded13d97
JB
162 await this.start();
163 }
164
ec7f4dce
JB
165 private initializeWorkerImplementation(): void {
166 !this.workerImplementation &&
167 (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
168 this.workerScript,
cf2a5d9b 169 Configuration.getWorker().processType,
ec7f4dce 170 {
cf2a5d9b
JB
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,
ec7f4dce 176 poolOptions: {
cf2a5d9b 177 workerChoiceStrategy: Configuration.getWorker().poolStrategy,
ec7f4dce 178 },
32de5a57 179 messageHandler: this.messageHandler.bind(this) as (
53e5fd67 180 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
32de5a57 181 ) => void,
ec7f4dce
JB
182 }
183 ));
ded13d97 184 }
81797102 185
32de5a57 186 private messageHandler(
53e5fd67 187 msg: ChargingStationWorkerMessage<ChargingStationWorkerMessageData>
32de5a57
LM
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.hashId, data);
89b7a234 227 ++this.numberOfStartedChargingStations;
32de5a57
LM
228 }
229
230 private workerEventStopped(data: ChargingStationData) {
89b7a234
JB
231 this.uiServer?.chargingStations.set(data.hashId, data);
232 --this.numberOfStartedChargingStations;
32de5a57
LM
233 }
234
235 private workerEventUpdated(data: ChargingStationData) {
236 this.uiServer?.chargingStations.set(data.hashId, data);
237 }
238
239 private workerEventPerformanceStatistics = (data: Statistics) => {
240 this.storage.storePerformanceStatistics(data) as void;
241 };
242
7c72977b 243 private initialize() {
7c72977b 244 this.numberOfChargingStationTemplates = 0;
89b7a234
JB
245 this.numberOfChargingStations = 0;
246 this.numberOfStartedChargingStations = 0;
ec7f4dce 247 this.initializeWorkerImplementation();
7c72977b
JB
248 }
249
e7aeea18
JB
250 private async startChargingStation(
251 index: number,
252 stationTemplateUrl: StationTemplateUrl
253 ): Promise<void> {
717c1e56
JB
254 const workerData: ChargingStationWorkerData = {
255 index,
e7aeea18 256 templateFile: path.join(
0d8140bd 257 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
e7aeea18
JB
258 'assets',
259 'station-templates',
ee5f26a2 260 stationTemplateUrl.file
e7aeea18 261 ),
717c1e56
JB
262 };
263 await this.workerImplementation.addElement(workerData);
89b7a234 264 ++this.numberOfChargingStations;
717c1e56
JB
265 }
266
81797102 267 private logPrefix(): string {
689dca78 268 return Utils.logPrefix(' Bootstrap |');
81797102 269 }
ded13d97 270}