Use eslint extension for import sorting instead of unmaintained external ones
[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 { Storage } from '../performance/storage/Storage';
11 import { StorageFactory } from '../performance/storage/StorageFactory';
12 import {
13 ChargingStationWorkerData,
14 ChargingStationWorkerMessage,
15 ChargingStationWorkerMessageEvents,
16 } from '../types/ChargingStationWorker';
17 import { StationTemplateUrl } from '../types/ConfigurationData';
18 import Statistics from '../types/Statistics';
19 import { ApplicationProtocol } from '../types/UIProtocol';
20 import Configuration from '../utils/Configuration';
21 import Utils from '../utils/Utils';
22 import WorkerAbstract from '../worker/WorkerAbstract';
23 import WorkerFactory from '../worker/WorkerFactory';
24 import { ChargingStationUtils } from './ChargingStationUtils';
25 import { AbstractUIServer } from './ui-server/AbstractUIServer';
26 import { UIServiceUtils } from './ui-server/ui-services/UIServiceUtils';
27 import UIServerFactory from './ui-server/UIServerFactory';
28
29 export default class Bootstrap {
30 private static instance: Bootstrap | null = null;
31 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null = null;
32 private readonly uiServer!: AbstractUIServer;
33 private readonly storage!: Storage;
34 private numberOfChargingStationTemplates!: number;
35 private numberOfChargingStations!: number;
36 private readonly version: string = version;
37 private started: boolean;
38 private readonly workerScript: string;
39
40 private constructor() {
41 this.started = false;
42 this.workerScript = path.join(
43 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
44 'charging-station',
45 'ChargingStationWorker' + path.extname(fileURLToPath(import.meta.url))
46 );
47 this.initialize();
48 Configuration.getUIServer().enabled &&
49 (this.uiServer = UIServerFactory.getUIServerImplementation(ApplicationProtocol.WS, {
50 ...Configuration.getUIServer().options,
51 handleProtocols: UIServiceUtils.handleProtocols,
52 }));
53 Configuration.getPerformanceStorage().enabled &&
54 (this.storage = StorageFactory.getStorage(
55 Configuration.getPerformanceStorage().type,
56 Configuration.getPerformanceStorage().uri,
57 this.logPrefix()
58 ));
59 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
60 }
61
62 public static getInstance(): Bootstrap {
63 if (!Bootstrap.instance) {
64 Bootstrap.instance = new Bootstrap();
65 }
66 return Bootstrap.instance;
67 }
68
69 public async start(): Promise<void> {
70 if (isMainThread && !this.started) {
71 try {
72 this.initialize();
73 await this.storage?.open();
74 await this.workerImplementation.start();
75 this.uiServer?.start();
76 const stationTemplateUrls = Configuration.getStationTemplateUrls();
77 this.numberOfChargingStationTemplates = stationTemplateUrls.length;
78 // Start ChargingStation object in worker thread
79 if (!Utils.isEmptyArray(stationTemplateUrls)) {
80 for (const stationTemplateUrl of stationTemplateUrls) {
81 try {
82 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
83 for (let index = 1; index <= nbStations; index++) {
84 await this.startChargingStation(index, stationTemplateUrl);
85 }
86 } catch (error) {
87 console.error(
88 chalk.red(
89 'Error at starting charging station with template file ' +
90 stationTemplateUrl.file +
91 ': '
92 ),
93 error
94 );
95 }
96 }
97 } else {
98 console.warn(
99 chalk.yellow("'stationTemplateUrls' not defined or empty in configuration, exiting")
100 );
101 }
102 if (this.numberOfChargingStations === 0) {
103 console.warn(
104 chalk.yellow('No charging station template enabled in configuration, exiting')
105 );
106 } else {
107 console.log(
108 chalk.green(
109 `Charging stations simulator ${
110 this.version
111 } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${
112 ChargingStationUtils.workerDynamicPoolInUse()
113 ? `${Configuration.getWorker().poolMinSize.toString()}/`
114 : ''
115 }${this.workerImplementation.size}${
116 ChargingStationUtils.workerPoolInUse()
117 ? `/${Configuration.getWorker().poolMaxSize.toString()}`
118 : ''
119 } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${
120 this.workerImplementation.maxElementsPerWorker
121 ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)`
122 : ''
123 }`
124 )
125 );
126 }
127 this.started = true;
128 } catch (error) {
129 console.error(chalk.red('Bootstrap start error '), error);
130 }
131 } else {
132 console.error(chalk.red('Cannot start an already started charging stations simulator'));
133 }
134 }
135
136 public async stop(): Promise<void> {
137 if (isMainThread && this.started) {
138 await this.workerImplementation.stop();
139 this.workerImplementation = null;
140 this.uiServer?.stop();
141 await this.storage?.close();
142 } else {
143 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
144 }
145 this.started = false;
146 }
147
148 public async restart(): Promise<void> {
149 await this.stop();
150 this.initialize();
151 await this.start();
152 }
153
154 private initializeWorkerImplementation(): void {
155 !this.workerImplementation &&
156 (this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
157 this.workerScript,
158 Configuration.getWorker().processType,
159 {
160 workerStartDelay: Configuration.getWorker().startDelay,
161 elementStartDelay: Configuration.getWorker().elementStartDelay,
162 poolMaxSize: Configuration.getWorker().poolMaxSize,
163 poolMinSize: Configuration.getWorker().poolMinSize,
164 elementsPerWorker: Configuration.getWorker().elementsPerWorker,
165 poolOptions: {
166 workerChoiceStrategy: Configuration.getWorker().poolStrategy,
167 },
168 messageHandler: async (msg: ChargingStationWorkerMessage) => {
169 if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
170 this.uiServer.chargingStations.add(msg.data.id as string);
171 } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
172 this.uiServer.chargingStations.delete(msg.data.id as string);
173 } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
174 await this.storage.storePerformanceStatistics(msg.data as unknown as Statistics);
175 }
176 },
177 }
178 ));
179 }
180
181 private initialize() {
182 this.numberOfChargingStations = 0;
183 this.numberOfChargingStationTemplates = 0;
184 this.initializeWorkerImplementation();
185 }
186
187 private async startChargingStation(
188 index: number,
189 stationTemplateUrl: StationTemplateUrl
190 ): Promise<void> {
191 const workerData: ChargingStationWorkerData = {
192 index,
193 templateFile: path.join(
194 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
195 'assets',
196 'station-templates',
197 path.basename(stationTemplateUrl.file)
198 ),
199 };
200 await this.workerImplementation.addElement(workerData);
201 this.numberOfChargingStations++;
202 }
203
204 private logPrefix(): string {
205 return Utils.logPrefix(' Bootstrap |');
206 }
207 }