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