build(deps-dev): apply updates
[e-mobility-charging-stations-simulator.git] / src / utils / Configuration.ts
1 import fs from 'node:fs';
2 import path from 'node:path';
3 import { fileURLToPath } from 'node:url';
4
5 import chalk from 'chalk';
6 import merge from 'just-merge';
7 import { WorkerChoiceStrategies } from 'poolifier';
8
9 // import { Constants, FileUtils, Utils } from './internal';
10 import { Constants } from './Constants';
11 import { FileUtils } from './FileUtils';
12 import { Utils } from './Utils';
13 import {
14 ApplicationProtocol,
15 type ConfigurationData,
16 FileType,
17 type StationTemplateUrl,
18 type StorageConfiguration,
19 StorageType,
20 SupervisionUrlDistribution,
21 type UIServerConfiguration,
22 type WorkerConfiguration,
23 } from '../types';
24 import { WorkerConstants, WorkerProcessType } from '../worker';
25
26 export class Configuration {
27 private static configurationFile = path.join(
28 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../'),
29 'assets',
30 'config.json'
31 );
32
33 private static configurationFileWatcher: fs.FSWatcher | undefined;
34 private static configuration: ConfigurationData | null = null;
35 private static configurationChangeCallback: () => Promise<void>;
36
37 private constructor() {
38 // This is intentional
39 }
40
41 static setConfigurationChangeCallback(cb: () => Promise<void>): void {
42 Configuration.configurationChangeCallback = cb;
43 }
44
45 static getLogStatisticsInterval(): number | undefined {
46 Configuration.warnDeprecatedConfigurationKey(
47 'statisticsDisplayInterval',
48 undefined,
49 "Use 'logStatisticsInterval' instead"
50 );
51 // Read conf
52 return Utils.hasOwnProp(Configuration.getConfig(), 'logStatisticsInterval')
53 ? Configuration.getConfig()?.logStatisticsInterval
54 : Constants.DEFAULT_LOG_STATISTICS_INTERVAL;
55 }
56
57 static getUIServer(): UIServerConfiguration {
58 if (Utils.hasOwnProp(Configuration.getConfig(), 'uiWebSocketServer')) {
59 console.error(
60 chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration section 'uiWebSocketServer' usage. Use 'uiServer' instead}`
61 );
62 }
63 let uiServerConfiguration: UIServerConfiguration = {
64 enabled: false,
65 type: ApplicationProtocol.WS,
66 options: {
67 host: Constants.DEFAULT_UI_SERVER_HOST,
68 port: Constants.DEFAULT_UI_SERVER_PORT,
69 },
70 };
71 if (Utils.hasOwnProp(Configuration.getConfig(), 'uiServer')) {
72 uiServerConfiguration = merge<UIServerConfiguration>(
73 uiServerConfiguration,
74 Configuration.getConfig()?.uiServer
75 );
76 }
77 if (Utils.isCFEnvironment() === true) {
78 delete uiServerConfiguration.options?.host;
79 uiServerConfiguration.options.port = parseInt(process.env.PORT);
80 }
81 return uiServerConfiguration;
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 (Utils.hasOwnProp(Configuration.getConfig(), 'performanceStorage')) {
92 storageConfiguration = {
93 ...storageConfiguration,
94 ...Configuration.getConfig()?.performanceStorage,
95 };
96 }
97 return storageConfiguration;
98 }
99
100 static getAutoReconnectMaxRetries(): number | undefined {
101 Configuration.warnDeprecatedConfigurationKey(
102 'autoReconnectTimeout',
103 undefined,
104 "Use 'ConnectionTimeOut' OCPP parameter in charging station template instead"
105 );
106 Configuration.warnDeprecatedConfigurationKey(
107 'connectionTimeout',
108 undefined,
109 "Use 'ConnectionTimeOut' OCPP parameter in charging station template instead"
110 );
111 Configuration.warnDeprecatedConfigurationKey(
112 'autoReconnectMaxRetries',
113 undefined,
114 'Use it in charging station template instead'
115 );
116 // Read conf
117 if (Utils.hasOwnProp(Configuration.getConfig(), 'autoReconnectMaxRetries')) {
118 return Configuration.getConfig()?.autoReconnectMaxRetries;
119 }
120 }
121
122 static getStationTemplateUrls(): StationTemplateUrl[] | undefined {
123 Configuration.warnDeprecatedConfigurationKey(
124 'stationTemplateURLs',
125 undefined,
126 "Use 'stationTemplateUrls' instead"
127 );
128 !Utils.isUndefined(Configuration.getConfig()['stationTemplateURLs']) &&
129 (Configuration.getConfig().stationTemplateUrls = Configuration.getConfig()[
130 'stationTemplateURLs'
131 ] as StationTemplateUrl[]);
132 Configuration.getConfig().stationTemplateUrls.forEach(
133 (stationTemplateUrl: StationTemplateUrl) => {
134 if (!Utils.isUndefined(stationTemplateUrl['numberOfStation'])) {
135 console.error(
136 chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key 'numberOfStation' usage for template file '${
137 stationTemplateUrl.file
138 }' in 'stationTemplateUrls'. Use 'numberOfStations' instead}`
139 );
140 }
141 }
142 );
143 // Read conf
144 return Configuration.getConfig()?.stationTemplateUrls;
145 }
146
147 static getWorker(): WorkerConfiguration {
148 Configuration.warnDeprecatedConfigurationKey(
149 'useWorkerPool',
150 undefined,
151 "Use 'worker' section to define the type of worker process model instead"
152 );
153 Configuration.warnDeprecatedConfigurationKey(
154 'workerProcess',
155 undefined,
156 "Use 'worker' section to define the type of worker process model instead"
157 );
158 Configuration.warnDeprecatedConfigurationKey(
159 'workerStartDelay',
160 undefined,
161 "Use 'worker' section to define the worker start delay instead"
162 );
163 Configuration.warnDeprecatedConfigurationKey(
164 'chargingStationsPerWorker',
165 undefined,
166 "Use 'worker' section to define the number of element(s) per worker instead"
167 );
168 Configuration.warnDeprecatedConfigurationKey(
169 'elementStartDelay',
170 undefined,
171 "Use 'worker' section to define the worker's element start delay instead"
172 );
173 Configuration.warnDeprecatedConfigurationKey(
174 'workerPoolMinSize',
175 undefined,
176 "Use 'worker' section to define the worker pool minimum size instead"
177 );
178 Configuration.warnDeprecatedConfigurationKey(
179 'workerPoolSize;',
180 undefined,
181 "Use 'worker' section to define the worker pool maximum size instead"
182 );
183 Configuration.warnDeprecatedConfigurationKey(
184 'workerPoolMaxSize;',
185 undefined,
186 "Use 'worker' section to define the worker pool maximum size instead"
187 );
188 Configuration.warnDeprecatedConfigurationKey(
189 'workerPoolStrategy;',
190 undefined,
191 "Use 'worker' section to define the worker pool strategy instead"
192 );
193 let workerConfiguration: WorkerConfiguration = {
194 processType: Utils.hasOwnProp(Configuration.getConfig(), 'workerProcess')
195 ? Configuration.getConfig()?.workerProcess
196 : WorkerProcessType.workerSet,
197 startDelay: Utils.hasOwnProp(Configuration.getConfig(), 'workerStartDelay')
198 ? Configuration.getConfig()?.workerStartDelay
199 : WorkerConstants.DEFAULT_WORKER_START_DELAY,
200 elementsPerWorker: Utils.hasOwnProp(Configuration.getConfig(), 'chargingStationsPerWorker')
201 ? Configuration.getConfig()?.chargingStationsPerWorker
202 : WorkerConstants.DEFAULT_ELEMENTS_PER_WORKER,
203 elementStartDelay: Utils.hasOwnProp(Configuration.getConfig(), 'elementStartDelay')
204 ? Configuration.getConfig()?.elementStartDelay
205 : WorkerConstants.DEFAULT_ELEMENT_START_DELAY,
206 poolMinSize: Utils.hasOwnProp(Configuration.getConfig(), 'workerPoolMinSize')
207 ? Configuration.getConfig()?.workerPoolMinSize
208 : WorkerConstants.DEFAULT_POOL_MIN_SIZE,
209 poolMaxSize: Utils.hasOwnProp(Configuration.getConfig(), 'workerPoolMaxSize')
210 ? Configuration.getConfig()?.workerPoolMaxSize
211 : WorkerConstants.DEFAULT_POOL_MAX_SIZE,
212 poolStrategy:
213 Configuration.getConfig()?.workerPoolStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN,
214 };
215 if (Utils.hasOwnProp(Configuration.getConfig(), 'worker')) {
216 workerConfiguration = { ...workerConfiguration, ...Configuration.getConfig()?.worker };
217 }
218 return workerConfiguration;
219 }
220
221 static getLogConsole(): boolean | undefined {
222 Configuration.warnDeprecatedConfigurationKey(
223 'consoleLog',
224 undefined,
225 "Use 'logConsole' instead"
226 );
227 return Utils.hasOwnProp(Configuration.getConfig(), 'logConsole')
228 ? Configuration.getConfig()?.logConsole
229 : false;
230 }
231
232 static getLogFormat(): string | undefined {
233 return Utils.hasOwnProp(Configuration.getConfig(), 'logFormat')
234 ? Configuration.getConfig()?.logFormat
235 : 'simple';
236 }
237
238 static getLogRotate(): boolean | undefined {
239 return Utils.hasOwnProp(Configuration.getConfig(), 'logRotate')
240 ? Configuration.getConfig()?.logRotate
241 : true;
242 }
243
244 static getLogMaxFiles(): number | string | false | undefined {
245 return (
246 Utils.hasOwnProp(Configuration.getConfig(), 'logMaxFiles') &&
247 Configuration.getConfig()?.logMaxFiles
248 );
249 }
250
251 static getLogMaxSize(): number | string | false | undefined {
252 return (
253 Utils.hasOwnProp(Configuration.getConfig(), 'logMaxFiles') &&
254 Configuration.getConfig()?.logMaxSize
255 );
256 }
257
258 static getLogLevel(): string | undefined {
259 return Utils.hasOwnProp(Configuration.getConfig(), 'logLevel')
260 ? Configuration.getConfig()?.logLevel?.toLowerCase()
261 : 'info';
262 }
263
264 static getLogFile(): string | undefined {
265 return Utils.hasOwnProp(Configuration.getConfig(), 'logFile')
266 ? Configuration.getConfig()?.logFile
267 : 'combined.log';
268 }
269
270 static getLogErrorFile(): string | undefined {
271 Configuration.warnDeprecatedConfigurationKey(
272 'errorFile',
273 undefined,
274 "Use 'logErrorFile' instead"
275 );
276 return Utils.hasOwnProp(Configuration.getConfig(), 'logErrorFile')
277 ? Configuration.getConfig()?.logErrorFile
278 : 'error.log';
279 }
280
281 static getSupervisionUrls(): string | string[] | undefined {
282 Configuration.warnDeprecatedConfigurationKey(
283 'supervisionURLs',
284 undefined,
285 "Use 'supervisionUrls' instead"
286 );
287 !Utils.isUndefined(Configuration.getConfig()['supervisionURLs']) &&
288 (Configuration.getConfig().supervisionUrls = Configuration.getConfig()['supervisionURLs'] as
289 | string
290 | string[]);
291 // Read conf
292 return Configuration.getConfig()?.supervisionUrls;
293 }
294
295 static getSupervisionUrlDistribution(): SupervisionUrlDistribution | undefined {
296 Configuration.warnDeprecatedConfigurationKey(
297 'distributeStationToTenantEqually',
298 undefined,
299 "Use 'supervisionUrlDistribution' instead"
300 );
301 Configuration.warnDeprecatedConfigurationKey(
302 'distributeStationsToTenantsEqually',
303 undefined,
304 "Use 'supervisionUrlDistribution' instead"
305 );
306 return Utils.hasOwnProp(Configuration.getConfig(), 'supervisionUrlDistribution')
307 ? Configuration.getConfig()?.supervisionUrlDistribution
308 : SupervisionUrlDistribution.ROUND_ROBIN;
309 }
310
311 private static logPrefix = (): string => {
312 return `${new Date().toLocaleString()} Simulator configuration |`;
313 };
314
315 private static warnDeprecatedConfigurationKey(
316 key: string,
317 sectionName?: string,
318 logMsgToAppend = ''
319 ) {
320 if (
321 sectionName &&
322 !Utils.isUndefined(Configuration.getConfig()[sectionName]) &&
323 !Utils.isUndefined((Configuration.getConfig()[sectionName] as Record<string, unknown>)[key])
324 ) {
325 console.error(
326 chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage in section '${sectionName}'${
327 logMsgToAppend.trim().length > 0 ? `. ${logMsgToAppend}` : ''
328 }}`
329 );
330 } else if (!Utils.isUndefined(Configuration.getConfig()[key])) {
331 console.error(
332 chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage${
333 logMsgToAppend.trim().length > 0 ? `. ${logMsgToAppend}` : ''
334 }}`
335 );
336 }
337 }
338
339 // Read the config file
340 private static getConfig(): ConfigurationData | null {
341 if (!Configuration.configuration) {
342 try {
343 Configuration.configuration = JSON.parse(
344 fs.readFileSync(Configuration.configurationFile, 'utf8')
345 ) as ConfigurationData;
346 } catch (error) {
347 FileUtils.handleFileException(
348 Configuration.configurationFile,
349 FileType.Configuration,
350 error as NodeJS.ErrnoException,
351 Configuration.logPrefix(),
352 { consoleOut: true }
353 );
354 }
355 if (!Configuration.configurationFileWatcher) {
356 Configuration.configurationFileWatcher = Configuration.getConfigurationFileWatcher();
357 }
358 }
359 return Configuration.configuration;
360 }
361
362 private static getConfigurationFileWatcher(): fs.FSWatcher | undefined {
363 try {
364 return fs.watch(Configuration.configurationFile, (event, filename): void => {
365 if (filename?.trim().length > 0 && event === 'change') {
366 // Nullify to force configuration file reading
367 Configuration.configuration = null;
368 if (!Utils.isUndefined(Configuration.configurationChangeCallback)) {
369 Configuration.configurationChangeCallback().catch((error) => {
370 throw typeof error === 'string' ? new Error(error) : error;
371 });
372 }
373 }
374 });
375 } catch (error) {
376 FileUtils.handleFileException(
377 Configuration.configurationFile,
378 FileType.Configuration,
379 error as NodeJS.ErrnoException,
380 Configuration.logPrefix(),
381 { consoleOut: true }
382 );
383 }
384 }
385
386 private static getDefaultPerformanceStorageUri(storageType: StorageType) {
387 switch (storageType) {
388 case StorageType.JSON_FILE:
389 return `file://${path.join(
390 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../'),
391 Constants.DEFAULT_PERFORMANCE_RECORDS_FILENAME
392 )}`;
393 case StorageType.SQLITE:
394 return `file://${path.join(
395 path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../'),
396 `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`
397 )}`;
398 default:
399 throw new Error(`Performance storage URI is mandatory with storage type '${storageType}'`);
400 }
401 }
402 }