Refine an error message
[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';
ded13d97 23import { isMainThread } from 'worker_threads';
bf1866b2 24import path from 'path';
84e52c2c 25import { version } from '../../package.json';
ded13d97
JB
26
27export default class Bootstrap {
535aaa27 28 private static instance: Bootstrap | null = null;
c3ee95af 29 private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null = null;
fe94fce0 30 private readonly uiServer!: AbstractUIServer;
6a49ad23 31 private readonly storage!: Storage;
a4bc2942 32 private numberOfChargingStations: number;
9e23580d 33 private readonly version: string = version;
eb87fe87 34 private started: boolean;
9e23580d 35 private readonly workerScript: string;
ded13d97
JB
36
37 private constructor() {
eb87fe87 38 this.started = false;
e7aeea18
JB
39 this.workerScript = path.join(
40 path.resolve(__dirname, '../'),
41 'charging-station',
42 'ChargingStationWorker.js'
43 );
8df3f0a9 44 this.initWorkerImplementation();
675fa8e3 45 Configuration.getUIServer().enabled &&
fe94fce0 46 (this.uiServer = UIServerFactory.getUIServerImplementation(ApplicationProtocol.WS, {
675fa8e3 47 ...Configuration.getUIServer().options,
e7aeea18
JB
48 handleProtocols: UIServiceUtils.handleProtocols,
49 }));
50 Configuration.getPerformanceStorage().enabled &&
51 (this.storage = StorageFactory.getStorage(
52 Configuration.getPerformanceStorage().type,
53 Configuration.getPerformanceStorage().uri,
54 this.logPrefix()
55 ));
7874b0b1 56 Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart());
ded13d97
JB
57 }
58
59 public static getInstance(): Bootstrap {
60 if (!Bootstrap.instance) {
61 Bootstrap.instance = new Bootstrap();
62 }
63 return Bootstrap.instance;
64 }
65
66 public async start(): Promise<void> {
eb87fe87 67 if (isMainThread && !this.started) {
ded13d97 68 try {
a4bc2942 69 this.numberOfChargingStations = 0;
6a49ad23 70 await this.storage?.open();
a4bc2942 71 await this.workerImplementation.start();
675fa8e3 72 this.uiServer?.start();
1f5df42a 73 const stationTemplateUrls = Configuration.getStationTemplateUrls();
ded13d97 74 // Start ChargingStation object in worker thread
1f5df42a
JB
75 if (stationTemplateUrls) {
76 for (const stationTemplateUrl of stationTemplateUrls) {
ded13d97 77 try {
1f5df42a 78 const nbStations = stationTemplateUrl.numberOfStations ?? 0;
ded13d97 79 for (let index = 1; index <= nbStations; index++) {
717c1e56 80 await this.startChargingStation(index, stationTemplateUrl);
ded13d97
JB
81 }
82 } catch (error) {
e7aeea18
JB
83 console.error(
84 chalk.red(
3d25cc86
JB
85 'Error at starting charging station with template file ' +
86 stationTemplateUrl.file +
87 ': '
e7aeea18
JB
88 ),
89 error
90 );
ded13d97
JB
91 }
92 }
93 } else {
3d25cc86 94 console.warn(chalk.yellow("No 'stationTemplateUrls' defined in configuration, exiting"));
ded13d97 95 }
a4bc2942 96 if (this.numberOfChargingStations === 0) {
e7aeea18
JB
97 console.warn(
98 chalk.yellow('No charging station template enabled in configuration, exiting')
99 );
ded13d97 100 } else {
e7aeea18
JB
101 console.log(
102 chalk.green(
103 `Charging stations simulator ${
104 this.version
105 } started with ${this.numberOfChargingStations.toString()} charging station(s) and ${
17ac262c 106 ChargingStationUtils.workerDynamicPoolInUse()
e7aeea18
JB
107 ? `${Configuration.getWorkerPoolMinSize().toString()}/`
108 : ''
109 }${this.workerImplementation.size}${
17ac262c
JB
110 ChargingStationUtils.workerPoolInUse()
111 ? `/${Configuration.getWorkerPoolMaxSize().toString()}`
112 : ''
e7aeea18
JB
113 } worker(s) concurrently running in '${Configuration.getWorkerProcess()}' mode${
114 this.workerImplementation.maxElementsPerWorker
115 ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)`
116 : ''
117 }`
118 )
119 );
ded13d97 120 }
eb87fe87 121 this.started = true;
ded13d97 122 } catch (error) {
8eac9a09 123 console.error(chalk.red('Bootstrap start error '), error);
ded13d97 124 }
b322b8b4
JB
125 } else {
126 console.error(chalk.red('Cannot start an already started charging stations simulator'));
ded13d97
JB
127 }
128 }
129
130 public async stop(): Promise<void> {
eb87fe87 131 if (isMainThread && this.started) {
a4bc2942 132 await this.workerImplementation.stop();
675fa8e3 133 this.uiServer?.stop();
6a49ad23 134 await this.storage?.close();
b322b8b4
JB
135 } else {
136 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
ded13d97 137 }
eb87fe87 138 this.started = false;
ded13d97
JB
139 }
140
141 public async restart(): Promise<void> {
142 await this.stop();
535aaa27 143 this.initWorkerImplementation();
ded13d97
JB
144 await this.start();
145 }
146
2a370053 147 private initWorkerImplementation(): void {
e7aeea18
JB
148 this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
149 this.workerScript,
150 Configuration.getWorkerProcess(),
8df3f0a9 151 {
4bfd80fa
JB
152 workerStartDelay: Configuration.getWorkerStartDelay(),
153 elementStartDelay: Configuration.getElementStartDelay(),
8df3f0a9
JB
154 poolMaxSize: Configuration.getWorkerPoolMaxSize(),
155 poolMinSize: Configuration.getWorkerPoolMinSize(),
156 elementsPerWorker: Configuration.getChargingStationsPerWorker(),
157 poolOptions: {
e7aeea18 158 workerChoiceStrategy: Configuration.getWorkerPoolStrategy(),
ffd71f2c 159 },
98dc07fa 160 messageHandler: async (msg: ChargingStationWorkerMessage) => {
ee0f106b 161 if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
675fa8e3 162 this.uiServer.chargingStations.add(msg.data.id as string);
ee0f106b 163 } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
675fa8e3 164 this.uiServer.chargingStations.delete(msg.data.id as string);
ee0f106b 165 } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
c3ee95af 166 await this.storage.storePerformanceStatistics(msg.data as unknown as Statistics);
ffd71f2c 167 }
e7aeea18
JB
168 },
169 }
170 );
ded13d97 171 }
81797102 172
e7aeea18
JB
173 private async startChargingStation(
174 index: number,
175 stationTemplateUrl: StationTemplateUrl
176 ): Promise<void> {
717c1e56
JB
177 const workerData: ChargingStationWorkerData = {
178 index,
e7aeea18
JB
179 templateFile: path.join(
180 path.resolve(__dirname, '../'),
181 'assets',
182 'station-templates',
183 path.basename(stationTemplateUrl.file)
184 ),
717c1e56
JB
185 };
186 await this.workerImplementation.addElement(workerData);
187 this.numberOfChargingStations++;
188 }
189
81797102 190 private logPrefix(): string {
689dca78 191 return Utils.logPrefix(' Bootstrap |');
81797102 192 }
ded13d97 193}