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