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