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