Add WebSocket connection close and open support to the UI protocol
[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;
89b7a234 41 private numberOfStartedChargingStations!: number;
9e23580d 42 private readonly version: string = version;
eb87fe87 43 private started: boolean;
9e23580d 44 private readonly workerScript: string;
ded13d97
JB
45
46 private constructor() {
eb87fe87 47 this.started = false;
e7aeea18 48 this.workerScript = path.join(
0d8140bd 49 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
e7aeea18 50 'charging-station',
44a95b7f 51 'ChargingStationWorker' + path.extname(fileURLToPath(import.meta.url))
e7aeea18 52 );
7c72977b 53 this.initialize();
675fa8e3 54 Configuration.getUIServer().enabled &&
fe94fce0 55 (this.uiServer = UIServerFactory.getUIServerImplementation(ApplicationProtocol.WS, {
675fa8e3 56 ...Configuration.getUIServer().options,
e7aeea18
JB
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 ));
7874b0b1 65 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
ded13d97
JB
66 }
67
68 public static getInstance(): Bootstrap {
1ca780f9 69 if (Bootstrap.instance === null) {
ded13d97
JB
70 Bootstrap.instance = new Bootstrap();
71 }
72 return Bootstrap.instance;
73 }
74
75 public async start(): Promise<void> {
eb87fe87 76 if (isMainThread && !this.started) {
ded13d97 77 try {
7c72977b 78 this.initialize();
6a49ad23 79 await this.storage?.open();
a4bc2942 80 await this.workerImplementation.start();
675fa8e3 81 this.uiServer?.start();
1f5df42a 82 const stationTemplateUrls = Configuration.getStationTemplateUrls();
7c72977b 83 this.numberOfChargingStationTemplates = stationTemplateUrls.length;
ded13d97 84 // Start ChargingStation object in worker thread
45bd0627 85 if (!Utils.isEmptyArray(stationTemplateUrls)) {
1f5df42a 86 for (const stationTemplateUrl of stationTemplateUrls) {
ded13d97 87 try {
1f5df42a 88 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
ded13d97 89 for (let index = 1; index <= nbStations; index++) {
717c1e56 90 await this.startChargingStation(index, stationTemplateUrl);
ded13d97
JB
91 }
92 } catch (error) {
e7aeea18
JB
93 console.error(
94 chalk.red(
3d25cc86
JB
95 'Error at starting charging station with template file ' +
96 stationTemplateUrl.file +
97 ': '
e7aeea18
JB
98 ),
99 error
100 );
ded13d97
JB
101 }
102 }
103 } else {
45bd0627
JB
104 console.warn(
105 chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
106 );
ded13d97 107 }
a4bc2942 108 if (this.numberOfChargingStations === 0) {
e7aeea18
JB
109 console.warn(
110 chalk.yellow('No charging station template enabled in configuration, exiting')
111 );
32de5a57 112 process.exit();
ded13d97 113 } else {
32de5a57 114 console.info(
e7aeea18
JB
115 chalk.green(
116 `Charging stations simulator ${
117 this.version
7c72977b 118 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
17ac262c 119 ChargingStationUtils.workerDynamicPoolInUse()
cf2a5d9b 120 ? `${Configuration.getWorker().poolMinSize.toString()}/`
e7aeea18
JB
121 : ''
122 }${this.workerImplementation.size}${
17ac262c 123 ChargingStationUtils.workerPoolInUse()
cf2a5d9b 124 ? `/${Configuration.getWorker().poolMaxSize.toString()}`
17ac262c 125 : ''
cf2a5d9b 126 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
e7aeea18
JB
127 this.workerImplementation.maxElementsPerWorker
128 ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)`
129 : ''
130 }`
131 )
132 );
ded13d97 133 }
eb87fe87 134 this.started = true;
ded13d97 135 } catch (error) {
8eac9a09 136 console.error(chalk.red('Bootstrap start error '), error);
ded13d97 137 }
b322b8b4
JB
138 } else {
139 console.error(chalk.red('Cannot start an already started charging stations simulator'));
ded13d97
JB
140 }
141 }
142
143 public async stop(): Promise<void> {
eb87fe87 144 if (isMainThread && this.started) {
a4bc2942 145 await this.workerImplementation.stop();
b19021e2 146 this.workerImplementation = null;
675fa8e3 147 this.uiServer?.stop();
6a49ad23 148 await this.storage?.close();
b322b8b4
JB
149 } else {
150 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
ded13d97 151 }
eb87fe87 152 this.started = false;
ded13d97
JB
153 }
154
155 public async restart(): Promise<void> {
156 await this.stop();
7c72977b 157 this.initialize();
ded13d97
JB
158 await this.start();
159 }
160
ec7f4dce
JB
161 private initializeWorkerImplementation(): void {
162 !this.workerImplementation &&
163 (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
164 this.workerScript,
cf2a5d9b 165 Configuration.getWorker().processType,
ec7f4dce 166 {
cf2a5d9b
JB
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,
ec7f4dce 172 poolOptions: {
cf2a5d9b 173 workerChoiceStrategy: Configuration.getWorker().poolStrategy,
ec7f4dce 174 },
32de5a57
LM
175 messageHandler: this.messageHandler.bind(this) as (
176 msg: ChargingStationWorkerMessage<ChargingStationData | Statistics>
177 ) => void,
ec7f4dce
JB
178 }
179 ));
ded13d97 180 }
81797102 181
32de5a57
LM
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);
89b7a234 223 ++this.numberOfStartedChargingStations;
32de5a57
LM
224 }
225
226 private workerEventStopped(data: ChargingStationData) {
89b7a234
JB
227 this.uiServer?.chargingStations.set(data.hashId, data);
228 --this.numberOfStartedChargingStations;
32de5a57
LM
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
7c72977b 239 private initialize() {
7c72977b 240 this.numberOfChargingStationTemplates = 0;
89b7a234
JB
241 this.numberOfChargingStations = 0;
242 this.numberOfStartedChargingStations = 0;
ec7f4dce 243 this.initializeWorkerImplementation();
7c72977b
JB
244 }
245
e7aeea18
JB
246 private async startChargingStation(
247 index: number,
248 stationTemplateUrl: StationTemplateUrl
249 ): Promise<void> {
717c1e56
JB
250 const workerData: ChargingStationWorkerData = {
251 index,
e7aeea18 252 templateFile: path.join(
0d8140bd 253 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
e7aeea18
JB
254 'assets',
255 'station-templates',
ee5f26a2 256 stationTemplateUrl.file
e7aeea18 257 ),
717c1e56
JB
258 };
259 await this.workerImplementation.addElement(workerData);
89b7a234 260 ++this.numberOfChargingStations;
717c1e56
JB
261 }
262
81797102 263 private logPrefix(): string {
689dca78 264 return Utils.logPrefix(' Bootstrap |');
81797102 265 }
ded13d97 266}