Ensure that workerSet always properly start a worker at init
[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;
7c72977b
JB
32 private numberOfChargingStationTemplates!: number;
33 private numberOfChargingStations!: number;
9e23580d 34 private readonly version: string = version;
eb87fe87 35 private started: boolean;
9e23580d 36 private readonly workerScript: string;
ded13d97
JB
37
38 private constructor() {
eb87fe87 39 this.started = false;
e7aeea18
JB
40 this.workerScript = path.join(
41 path.resolve(__dirname, '../'),
42 'charging-station',
43 'ChargingStationWorker.js'
44 );
7c72977b 45 this.initialize();
8df3f0a9 46 this.initWorkerImplementation();
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()
e7aeea18
JB
112 ? `${Configuration.getWorkerPoolMinSize().toString()}/`
113 : ''
114 }${this.workerImplementation.size}${
17ac262c
JB
115 ChargingStationUtils.workerPoolInUse()
116 ? `/${Configuration.getWorkerPoolMaxSize().toString()}`
117 : ''
e7aeea18
JB
118 } worker(s) concurrently running in '${Configuration.getWorkerProcess()}' mode${
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();
675fa8e3 138 this.uiServer?.stop();
6a49ad23 139 await this.storage?.close();
b322b8b4
JB
140 } else {
141 console.error(chalk.red('Trying to stop the charging stations simulator while not started'));
ded13d97 142 }
eb87fe87 143 this.started = false;
ded13d97
JB
144 }
145
146 public async restart(): Promise<void> {
147 await this.stop();
7c72977b 148 this.initialize();
535aaa27 149 this.initWorkerImplementation();
ded13d97
JB
150 await this.start();
151 }
152
2a370053 153 private initWorkerImplementation(): void {
e7aeea18
JB
154 this.workerImplementation = WorkerFactory.getWorkerImplementation<ChargingStationWorkerData>(
155 this.workerScript,
156 Configuration.getWorkerProcess(),
8df3f0a9 157 {
4bfd80fa
JB
158 workerStartDelay: Configuration.getWorkerStartDelay(),
159 elementStartDelay: Configuration.getElementStartDelay(),
8df3f0a9
JB
160 poolMaxSize: Configuration.getWorkerPoolMaxSize(),
161 poolMinSize: Configuration.getWorkerPoolMinSize(),
162 elementsPerWorker: Configuration.getChargingStationsPerWorker(),
163 poolOptions: {
e7aeea18 164 workerChoiceStrategy: Configuration.getWorkerPoolStrategy(),
ffd71f2c 165 },
98dc07fa 166 messageHandler: async (msg: ChargingStationWorkerMessage) => {
ee0f106b 167 if (msg.id === ChargingStationWorkerMessageEvents.STARTED) {
675fa8e3 168 this.uiServer.chargingStations.add(msg.data.id as string);
ee0f106b 169 } else if (msg.id === ChargingStationWorkerMessageEvents.STOPPED) {
675fa8e3 170 this.uiServer.chargingStations.delete(msg.data.id as string);
ee0f106b 171 } else if (msg.id === ChargingStationWorkerMessageEvents.PERFORMANCE_STATISTICS) {
c3ee95af 172 await this.storage.storePerformanceStatistics(msg.data as unknown as Statistics);
ffd71f2c 173 }
e7aeea18
JB
174 },
175 }
176 );
ded13d97 177 }
81797102 178
7c72977b
JB
179 private initialize() {
180 this.numberOfChargingStations = 0;
181 this.numberOfChargingStationTemplates = 0;
182 }
183
e7aeea18
JB
184 private async startChargingStation(
185 index: number,
186 stationTemplateUrl: StationTemplateUrl
187 ): Promise<void> {
717c1e56
JB
188 const workerData: ChargingStationWorkerData = {
189 index,
e7aeea18
JB
190 templateFile: path.join(
191 path.resolve(__dirname, '../'),
192 'assets',
193 'station-templates',
194 path.basename(stationTemplateUrl.file)
195 ),
717c1e56
JB
196 };
197 await this.workerImplementation.addElement(workerData);
198 this.numberOfChargingStations++;
199 }
200
81797102 201 private logPrefix(): string {
689dca78 202 return Utils.logPrefix(' Bootstrap |');
81797102 203 }
ded13d97 204}