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