Make the UI server request handler signature more generic
[e-mobility-charging-stations-simulator.git] / src / utils / Configuration.ts
CommitLineData
e7aeea18
JB
1import ConfigurationData, {
2 StationTemplateUrl,
3 StorageConfiguration,
4 SupervisionUrlDistribution,
5 UIWebSocketServerConfiguration,
6} from '../types/ConfigurationData';
e118beaa 7
322c9192 8import Constants from './Constants';
717c1e56 9import { EmptyObject } from '../types/EmptyObject';
a95873d8 10import { FileType } from '../types/FileType';
e0a50bcd 11import { HandleErrorParams } from '../types/Error';
6a49ad23 12import { ServerOptions } from 'ws';
72f041bd 13import { StorageType } from '../types/Storage';
9efbac5b 14import type { WorkerChoiceStrategy } from 'poolifier';
3fa0f0ed 15import WorkerConstants from '../worker/WorkerConstants';
a4624c96 16import { WorkerProcessType } from '../types/Worker';
8eac9a09 17import chalk from 'chalk';
3f40bc9c 18import fs from 'fs';
bf1866b2 19import path from 'path';
7dde0b73 20
3f40bc9c 21export default class Configuration {
a95873d8 22 private static configurationFile = path.join(
e7aeea18
JB
23 path.resolve(__dirname, '../'),
24 'assets',
25 'config.json'
26 );
10068088 27
ded13d97 28 private static configurationFileWatcher: fs.FSWatcher;
6e0964c8 29 private static configuration: ConfigurationData | null = null;
e57acf6a
JB
30 private static configurationChangeCallback: () => Promise<void>;
31
32 static setConfigurationChangeCallback(cb: () => Promise<void>): void {
33 Configuration.configurationChangeCallback = cb;
34 }
7dde0b73 35
72f041bd 36 static getLogStatisticsInterval(): number {
e7aeea18
JB
37 Configuration.warnDeprecatedConfigurationKey(
38 'statisticsDisplayInterval',
39 null,
40 "Use 'logStatisticsInterval' instead"
41 );
7dde0b73 42 // Read conf
e7aeea18
JB
43 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logStatisticsInterval')
44 ? Configuration.getConfig().logStatisticsInterval
25f5a959 45 : Constants.DEFAULT_LOG_STATISTICS_INTERVAL;
72f041bd
JB
46 }
47
6a49ad23
JB
48 static getUIWebSocketServer(): UIWebSocketServerConfiguration {
49 let options: ServerOptions = {
50 host: Constants.DEFAULT_UI_WEBSOCKET_SERVER_HOST,
e7aeea18 51 port: Constants.DEFAULT_UI_WEBSOCKET_SERVER_PORT,
6a49ad23
JB
52 };
53 let uiWebSocketServerConfiguration: UIWebSocketServerConfiguration = {
54 enabled: true,
e7aeea18 55 options,
6a49ad23
JB
56 };
57 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'uiWebSocketServer')) {
e7aeea18
JB
58 if (
59 Configuration.objectHasOwnProperty(Configuration.getConfig().uiWebSocketServer, 'options')
60 ) {
6a49ad23 61 options = {
1ba1e8fb 62 ...options,
e7aeea18
JB
63 ...(Configuration.objectHasOwnProperty(
64 Configuration.getConfig().uiWebSocketServer.options,
65 'host'
66 ) && { host: Configuration.getConfig().uiWebSocketServer.options.host }),
67 ...(Configuration.objectHasOwnProperty(
68 Configuration.getConfig().uiWebSocketServer.options,
69 'port'
70 ) && { port: Configuration.getConfig().uiWebSocketServer.options.port }),
6a49ad23
JB
71 };
72 }
e7aeea18 73 uiWebSocketServerConfiguration = {
1ba1e8fb 74 ...uiWebSocketServerConfiguration,
e7aeea18
JB
75 ...(Configuration.objectHasOwnProperty(
76 Configuration.getConfig().uiWebSocketServer,
77 'enabled'
78 ) && { enabled: Configuration.getConfig().uiWebSocketServer.enabled }),
79 options,
6a49ad23
JB
80 };
81 }
82 return uiWebSocketServerConfiguration;
83 }
84
72f041bd 85 static getPerformanceStorage(): StorageConfiguration {
e7aeea18 86 Configuration.warnDeprecatedConfigurationKey('URI', 'performanceStorage', "Use 'uri' instead");
6a49ad23
JB
87 let storageConfiguration: StorageConfiguration = {
88 enabled: false,
89 type: StorageType.JSON_FILE,
e7aeea18 90 uri: this.getDefaultPerformanceStorageUri(StorageType.JSON_FILE),
6a49ad23 91 };
72f041bd 92 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'performanceStorage')) {
e7aeea18 93 storageConfiguration = {
1ba1e8fb 94 ...storageConfiguration,
e7aeea18
JB
95 ...(Configuration.objectHasOwnProperty(
96 Configuration.getConfig().performanceStorage,
97 'enabled'
98 ) && { enabled: Configuration.getConfig().performanceStorage.enabled }),
99 ...(Configuration.objectHasOwnProperty(
100 Configuration.getConfig().performanceStorage,
101 'type'
102 ) && { type: Configuration.getConfig().performanceStorage.type }),
103 ...(Configuration.objectHasOwnProperty(
104 Configuration.getConfig().performanceStorage,
105 'uri'
106 ) && {
107 uri: this.getDefaultPerformanceStorageUri(
108 Configuration.getConfig()?.performanceStorage?.type ?? StorageType.JSON_FILE
109 ),
110 }),
72f041bd 111 };
72f041bd
JB
112 }
113 return storageConfiguration;
7dde0b73
JB
114 }
115
9ccca265 116 static getAutoReconnectMaxRetries(): number {
e7aeea18
JB
117 Configuration.warnDeprecatedConfigurationKey(
118 'autoReconnectTimeout',
119 null,
120 "Use 'ConnectionTimeOut' OCPP parameter in charging station template instead"
121 );
122 Configuration.warnDeprecatedConfigurationKey(
123 'connectionTimeout',
124 null,
125 "Use 'ConnectionTimeOut' OCPP parameter in charging station template instead"
126 );
127 Configuration.warnDeprecatedConfigurationKey(
128 'autoReconnectMaxRetries',
129 null,
130 'Use it in charging station template instead'
131 );
7dde0b73 132 // Read conf
963ee397 133 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'autoReconnectMaxRetries')) {
3574dfd3
JB
134 return Configuration.getConfig().autoReconnectMaxRetries;
135 }
7dde0b73
JB
136 }
137
1f5df42a 138 static getStationTemplateUrls(): StationTemplateUrl[] {
e7aeea18
JB
139 Configuration.warnDeprecatedConfigurationKey(
140 'stationTemplateURLs',
141 null,
142 "Use 'stationTemplateUrls' instead"
143 );
144 !Configuration.isUndefined(Configuration.getConfig()['stationTemplateURLs']) &&
145 (Configuration.getConfig().stationTemplateUrls = Configuration.getConfig()[
146 'stationTemplateURLs'
147 ] as StationTemplateUrl[]);
1f5df42a
JB
148 Configuration.getConfig().stationTemplateUrls.forEach((stationUrl: StationTemplateUrl) => {
149 if (!Configuration.isUndefined(stationUrl['numberOfStation'])) {
e7aeea18
JB
150 console.error(
151 chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key 'numberOfStation' usage for template file '${
152 stationUrl.file
153 }' in 'stationTemplateUrls'. Use 'numberOfStations' instead}`
154 );
eb3937cb
JB
155 }
156 });
7dde0b73 157 // Read conf
1f5df42a 158 return Configuration.getConfig().stationTemplateUrls;
7dde0b73
JB
159 }
160
a4624c96 161 static getWorkerProcess(): WorkerProcessType {
e7aeea18 162 Configuration.warnDeprecatedConfigurationKey(
e80bc579 163 'useWorkerPool',
e7aeea18 164 null,
2484ac1e 165 "Use 'workerProcess' to define the type of worker process model to use instead"
e7aeea18
JB
166 );
167 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerProcess')
168 ? Configuration.getConfig().workerProcess
169 : WorkerProcessType.WORKER_SET;
a4624c96
JB
170 }
171
322c9192 172 static getWorkerStartDelay(): number {
e7aeea18
JB
173 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerStartDelay')
174 ? Configuration.getConfig().workerStartDelay
3fa0f0ed 175 : WorkerConstants.DEFAULT_WORKER_START_DELAY;
322c9192
JB
176 }
177
4bfd80fa 178 static getElementStartDelay(): number {
e7aeea18
JB
179 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'elementStartDelay')
180 ? Configuration.getConfig().elementStartDelay
3fa0f0ed 181 : WorkerConstants.DEFAULT_ELEMENT_START_DELAY;
4bfd80fa
JB
182 }
183
a4624c96 184 static getWorkerPoolMinSize(): number {
e7aeea18
JB
185 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMinSize')
186 ? Configuration.getConfig().workerPoolMinSize
3fa0f0ed 187 : WorkerConstants.DEFAULT_POOL_MIN_SIZE;
7dde0b73
JB
188 }
189
4fa59b8a 190 static getWorkerPoolMaxSize(): number {
e7aeea18
JB
191 Configuration.warnDeprecatedConfigurationKey(
192 'workerPoolSize;',
193 null,
194 "Use 'workerPoolMaxSize' instead"
195 );
196 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMaxSize')
197 ? Configuration.getConfig().workerPoolMaxSize
3fa0f0ed 198 : WorkerConstants.DEFAULT_POOL_MAX_SIZE;
7dde0b73
JB
199 }
200
9efbac5b
JB
201 static getWorkerPoolStrategy(): WorkerChoiceStrategy {
202 return Configuration.getConfig().workerPoolStrategy;
203 }
204
3d2ff9e4 205 static getChargingStationsPerWorker(): number {
e7aeea18
JB
206 return Configuration.objectHasOwnProperty(
207 Configuration.getConfig(),
208 'chargingStationsPerWorker'
209 )
210 ? Configuration.getConfig().chargingStationsPerWorker
3fa0f0ed 211 : WorkerConstants.DEFAULT_ELEMENTS_PER_WORKER;
3d2ff9e4
J
212 }
213
7ec46a9a 214 static getLogConsole(): boolean {
e7aeea18
JB
215 Configuration.warnDeprecatedConfigurationKey('consoleLog', null, "Use 'logConsole' instead");
216 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logConsole')
217 ? Configuration.getConfig().logConsole
218 : false;
7dde0b73
JB
219 }
220
a4a21709 221 static getLogFormat(): string {
e7aeea18
JB
222 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFormat')
223 ? Configuration.getConfig().logFormat
224 : 'simple';
027b409a
JB
225 }
226
6bf6769e 227 static getLogRotate(): boolean {
e7aeea18
JB
228 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logRotate')
229 ? Configuration.getConfig().logRotate
230 : true;
6bf6769e
JB
231 }
232
233 static getLogMaxFiles(): number {
e7aeea18
JB
234 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logMaxFiles')
235 ? Configuration.getConfig().logMaxFiles
236 : 7;
6bf6769e
JB
237 }
238
324fd4ee 239 static getLogLevel(): string {
e7aeea18
JB
240 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logLevel')
241 ? Configuration.getConfig().logLevel.toLowerCase()
242 : 'info';
2e6f5966
JB
243 }
244
a4a21709 245 static getLogFile(): string {
e7aeea18
JB
246 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFile')
247 ? Configuration.getConfig().logFile
248 : 'combined.log';
7dde0b73
JB
249 }
250
7ec46a9a 251 static getLogErrorFile(): string {
e7aeea18
JB
252 Configuration.warnDeprecatedConfigurationKey('errorFile', null, "Use 'logErrorFile' instead");
253 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logErrorFile')
254 ? Configuration.getConfig().logErrorFile
255 : 'error.log';
7dde0b73
JB
256 }
257
2dcfe98e 258 static getSupervisionUrls(): string | string[] {
e7aeea18
JB
259 Configuration.warnDeprecatedConfigurationKey(
260 'supervisionURLs',
261 null,
262 "Use 'supervisionUrls' instead"
263 );
264 !Configuration.isUndefined(Configuration.getConfig()['supervisionURLs']) &&
265 (Configuration.getConfig().supervisionUrls = Configuration.getConfig()[
266 'supervisionURLs'
267 ] as string[]);
7dde0b73 268 // Read conf
1f5df42a 269 return Configuration.getConfig().supervisionUrls;
7dde0b73
JB
270 }
271
2dcfe98e 272 static getSupervisionUrlDistribution(): SupervisionUrlDistribution {
e7aeea18
JB
273 Configuration.warnDeprecatedConfigurationKey(
274 'distributeStationToTenantEqually',
275 null,
276 "Use 'supervisionUrlDistribution' instead"
277 );
278 Configuration.warnDeprecatedConfigurationKey(
279 'distributeStationsToTenantsEqually',
280 null,
281 "Use 'supervisionUrlDistribution' instead"
282 );
283 return Configuration.objectHasOwnProperty(
284 Configuration.getConfig(),
285 'supervisionUrlDistribution'
286 )
287 ? Configuration.getConfig().supervisionUrlDistribution
288 : SupervisionUrlDistribution.ROUND_ROBIN;
7dde0b73 289 }
eb3937cb 290
23132a44
JB
291 private static logPrefix(): string {
292 return new Date().toLocaleString() + ' Simulator configuration |';
293 }
294
e7aeea18
JB
295 private static warnDeprecatedConfigurationKey(
296 key: string,
297 sectionName?: string,
298 logMsgToAppend = ''
299 ) {
e7aeea18
JB
300 if (
301 sectionName &&
302 !Configuration.isUndefined(Configuration.getConfig()[sectionName]) &&
455ee9cf
JB
303 !Configuration.isUndefined(
304 (Configuration.getConfig()[sectionName] as Record<string, unknown>)[key]
305 )
e7aeea18
JB
306 ) {
307 console.error(
308 chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage in section '${sectionName}'${
309 logMsgToAppend && '. ' + logMsgToAppend
310 }}`
311 );
912136b1 312 } else if (!Configuration.isUndefined(Configuration.getConfig()[key])) {
e7aeea18
JB
313 console.error(
314 chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage${
315 logMsgToAppend && '. ' + logMsgToAppend
316 }}`
317 );
eb3937cb
JB
318 }
319 }
320
321 // Read the config file
322 private static getConfig(): ConfigurationData {
323 if (!Configuration.configuration) {
23132a44 324 try {
e7aeea18 325 Configuration.configuration = JSON.parse(
a95873d8 326 fs.readFileSync(Configuration.configurationFile, 'utf8')
e7aeea18 327 ) as ConfigurationData;
23132a44 328 } catch (error) {
e7aeea18
JB
329 Configuration.handleFileException(
330 Configuration.logPrefix(),
a95873d8
JB
331 FileType.Configuration,
332 Configuration.configurationFile,
3fa0f0ed 333 error as NodeJS.ErrnoException
e7aeea18 334 );
23132a44 335 }
ded13d97
JB
336 if (!Configuration.configurationFileWatcher) {
337 Configuration.configurationFileWatcher = Configuration.getConfigurationFileWatcher();
338 }
eb3937cb
JB
339 }
340 return Configuration.configuration;
341 }
963ee397 342
ded13d97 343 private static getConfigurationFileWatcher(): fs.FSWatcher {
23132a44 344 try {
a95873d8 345 return fs.watch(Configuration.configurationFile, (event, filename): void => {
3ec10737
JB
346 if (filename && event === 'change') {
347 // Nullify to force configuration file reading
348 Configuration.configuration = null;
349 if (!Configuration.isUndefined(Configuration.configurationChangeCallback)) {
dcaf96dc
JB
350 Configuration.configurationChangeCallback().catch((error) => {
351 throw typeof error === 'string' ? new Error(error) : error;
352 });
3ec10737 353 }
23132a44
JB
354 }
355 });
356 } catch (error) {
e7aeea18
JB
357 Configuration.handleFileException(
358 Configuration.logPrefix(),
a95873d8
JB
359 FileType.Configuration,
360 Configuration.configurationFile,
361 error as NodeJS.ErrnoException
e7aeea18 362 );
23132a44 363 }
ded13d97
JB
364 }
365
1f5df42a 366 private static getDefaultPerformanceStorageUri(storageType: StorageType) {
d5603918
JB
367 const SQLiteFileName = `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`;
368 switch (storageType) {
369 case StorageType.JSON_FILE:
e7aeea18
JB
370 return `file://${path.join(
371 path.resolve(__dirname, '../../'),
372 Constants.DEFAULT_PERFORMANCE_RECORDS_FILENAME
373 )}`;
d5603918
JB
374 case StorageType.SQLITE:
375 return `file://${path.join(path.resolve(__dirname, '../../'), SQLiteFileName)}`;
376 default:
377 throw new Error(`Performance storage URI is mandatory with storage type '${storageType}'`);
378 }
379 }
380
73d09045 381 private static objectHasOwnProperty(object: unknown, property: string): boolean {
23132a44 382 return Object.prototype.hasOwnProperty.call(object, property) as boolean;
963ee397
JB
383 }
384
73d09045 385 private static isUndefined(obj: unknown): boolean {
963ee397
JB
386 return typeof obj === 'undefined';
387 }
23132a44 388
e7aeea18
JB
389 private static handleFileException(
390 logPrefix: string,
a95873d8 391 fileType: FileType,
e7aeea18
JB
392 filePath: string,
393 error: NodeJS.ErrnoException,
394 params: HandleErrorParams<EmptyObject> = { throwError: true }
395 ): void {
23132a44
JB
396 const prefix = logPrefix.length !== 0 ? logPrefix + ' ' : '';
397 if (error.code === 'ENOENT') {
e7aeea18
JB
398 console.error(
399 chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' not found: '),
400 error
401 );
72f041bd 402 } else if (error.code === 'EEXIST') {
e7aeea18
JB
403 console.error(
404 chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' already exists: '),
405 error
406 );
72f041bd 407 } else if (error.code === 'EACCES') {
e7aeea18
JB
408 console.error(
409 chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' access denied: '),
410 error
411 );
23132a44 412 } else {
e7aeea18
JB
413 console.error(
414 chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' error: '),
415 error
416 );
23132a44 417 }
e0a50bcd
JB
418 if (params?.throwError) {
419 throw error;
420 }
23132a44 421 }
7dde0b73 422}