Apply dependencies update
[e-mobility-charging-stations-simulator.git] / src / utils / Configuration.ts
CommitLineData
2dcfe98e 1import ConfigurationData, { StationTemplateUrl, StorageConfiguration, SupervisionUrlDistribution, UIWebSocketServerConfiguration } from '../types/ConfigurationData';
e118beaa 2
322c9192 3import Constants from './Constants';
e0a50bcd 4import { HandleErrorParams } from '../types/Error';
6a49ad23 5import { ServerOptions } from 'ws';
72f041bd 6import { StorageType } from '../types/Storage';
9efbac5b 7import type { WorkerChoiceStrategy } from 'poolifier';
a4624c96 8import { WorkerProcessType } from '../types/Worker';
8eac9a09 9import chalk from 'chalk';
3f40bc9c 10import fs from 'fs';
bf1866b2 11import path from 'path';
7dde0b73 12
3f40bc9c 13export default class Configuration {
bf1866b2 14 private static configurationFilePath = path.join(path.resolve(__dirname, '../'), 'assets', 'config.json');
ded13d97 15 private static configurationFileWatcher: fs.FSWatcher;
6e0964c8 16 private static configuration: ConfigurationData | null = null;
e57acf6a
JB
17 private static configurationChangeCallback: () => Promise<void>;
18
19 static setConfigurationChangeCallback(cb: () => Promise<void>): void {
20 Configuration.configurationChangeCallback = cb;
21 }
7dde0b73 22
72f041bd 23 static getLogStatisticsInterval(): number {
e4362ed7 24 Configuration.warnDeprecatedConfigurationKey('statisticsDisplayInterval', null, 'Use \'logStatisticsInterval\' instead');
7dde0b73 25 // Read conf
72f041bd
JB
26 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logStatisticsInterval') ? Configuration.getConfig().logStatisticsInterval : 60;
27 }
28
6a49ad23
JB
29 static getUIWebSocketServer(): UIWebSocketServerConfiguration {
30 let options: ServerOptions = {
31 host: Constants.DEFAULT_UI_WEBSOCKET_SERVER_HOST,
32 port: Constants.DEFAULT_UI_WEBSOCKET_SERVER_PORT
33 };
34 let uiWebSocketServerConfiguration: UIWebSocketServerConfiguration = {
35 enabled: true,
36 options
37 };
38 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'uiWebSocketServer')) {
39 if (Configuration.objectHasOwnProperty(Configuration.getConfig().uiWebSocketServer, 'options')) {
40 options = {
1ba1e8fb 41 ...options,
6a49ad23
JB
42 ...Configuration.objectHasOwnProperty(Configuration.getConfig().uiWebSocketServer.options, 'host') && { host: Configuration.getConfig().uiWebSocketServer.options.host },
43 ...Configuration.objectHasOwnProperty(Configuration.getConfig().uiWebSocketServer.options, 'port') && { port: Configuration.getConfig().uiWebSocketServer.options.port }
44 };
45 }
46 uiWebSocketServerConfiguration =
47 {
1ba1e8fb 48 ...uiWebSocketServerConfiguration,
6a49ad23
JB
49 ...Configuration.objectHasOwnProperty(Configuration.getConfig().uiWebSocketServer, 'enabled') && { enabled: Configuration.getConfig().uiWebSocketServer.enabled },
50 options
51 };
52 }
53 return uiWebSocketServerConfiguration;
54 }
55
72f041bd 56 static getPerformanceStorage(): StorageConfiguration {
1f5df42a 57 Configuration.warnDeprecatedConfigurationKey('URI', 'performanceStorage', 'Use \'uri\' instead');
6a49ad23
JB
58 let storageConfiguration: StorageConfiguration = {
59 enabled: false,
60 type: StorageType.JSON_FILE,
1f5df42a 61 uri: this.getDefaultPerformanceStorageUri(StorageType.JSON_FILE)
6a49ad23 62 };
72f041bd
JB
63 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'performanceStorage')) {
64 storageConfiguration =
65 {
1ba1e8fb
JB
66 ...storageConfiguration,
67 ...Configuration.objectHasOwnProperty(Configuration.getConfig().performanceStorage, 'enabled') && { enabled: Configuration.getConfig().performanceStorage.enabled },
68 ...Configuration.objectHasOwnProperty(Configuration.getConfig().performanceStorage, 'type') && { type: Configuration.getConfig().performanceStorage.type },
69 ...Configuration.objectHasOwnProperty(Configuration.getConfig().performanceStorage, 'uri') && { uri: this.getDefaultPerformanceStorageUri(Configuration.getConfig()?.performanceStorage?.type ?? StorageType.JSON_FILE) }
72f041bd 70 };
72f041bd
JB
71 }
72 return storageConfiguration;
7dde0b73
JB
73 }
74
9ccca265 75 static getAutoReconnectMaxRetries(): number {
e4362ed7
JB
76 Configuration.warnDeprecatedConfigurationKey('autoReconnectTimeout', null, 'Use \'ConnectionTimeOut\' OCPP parameter in charging station template instead');
77 Configuration.warnDeprecatedConfigurationKey('connectionTimeout', null, 'Use \'ConnectionTimeOut\' OCPP parameter in charging station template instead');
78 Configuration.warnDeprecatedConfigurationKey('autoReconnectMaxRetries', null, 'Use it in charging station template instead');
7dde0b73 79 // Read conf
963ee397 80 if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'autoReconnectMaxRetries')) {
3574dfd3
JB
81 return Configuration.getConfig().autoReconnectMaxRetries;
82 }
7dde0b73
JB
83 }
84
1f5df42a
JB
85 static getStationTemplateUrls(): StationTemplateUrl[] {
86 Configuration.warnDeprecatedConfigurationKey('stationTemplateURLs', null, 'Use \'stationTemplateUrls\' instead');
87 !Configuration.isUndefined(Configuration.getConfig()['stationTemplateURLs']) && (Configuration.getConfig().stationTemplateUrls = Configuration.getConfig()['stationTemplateURLs'] as StationTemplateUrl[]);
88 Configuration.getConfig().stationTemplateUrls.forEach((stationUrl: StationTemplateUrl) => {
89 if (!Configuration.isUndefined(stationUrl['numberOfStation'])) {
90 console.error(chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key 'numberOfStation' usage for template file '${stationUrl.file}' in 'stationTemplateUrls'. Use 'numberOfStations' instead}`);
eb3937cb
JB
91 }
92 });
7dde0b73 93 // Read conf
1f5df42a 94 return Configuration.getConfig().stationTemplateUrls;
7dde0b73
JB
95 }
96
a4624c96 97 static getWorkerProcess(): WorkerProcessType {
e4362ed7 98 Configuration.warnDeprecatedConfigurationKey('useWorkerPool;', null, 'Use \'workerProcess\' to define the type of worker process to use instead');
a4624c96
JB
99 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerProcess') ? Configuration.getConfig().workerProcess : WorkerProcessType.WORKER_SET;
100 }
101
322c9192
JB
102 static getWorkerStartDelay(): number {
103 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerStartDelay') ? Configuration.getConfig().workerStartDelay : Constants.WORKER_START_DELAY;
104 }
105
a4624c96 106 static getWorkerPoolMinSize(): number {
1f0052b9 107 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMinSize') ? Configuration.getConfig().workerPoolMinSize : Constants.DEFAULT_WORKER_POOL_MIN_SIZE;
7dde0b73
JB
108 }
109
4fa59b8a 110 static getWorkerPoolMaxSize(): number {
e4362ed7 111 Configuration.warnDeprecatedConfigurationKey('workerPoolSize;', null, 'Use \'workerPoolMaxSize\' instead');
1f0052b9 112 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerPoolMaxSize') ? Configuration.getConfig().workerPoolMaxSize : Constants.DEFAULT_WORKER_POOL_MAX_SIZE;
7dde0b73
JB
113 }
114
9efbac5b
JB
115 static getWorkerPoolStrategy(): WorkerChoiceStrategy {
116 return Configuration.getConfig().workerPoolStrategy;
117 }
118
3d2ff9e4 119 static getChargingStationsPerWorker(): number {
1f0052b9 120 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'chargingStationsPerWorker') ? Configuration.getConfig().chargingStationsPerWorker : Constants.DEFAULT_CHARGING_STATIONS_PER_WORKER;
3d2ff9e4
J
121 }
122
7ec46a9a 123 static getLogConsole(): boolean {
e4362ed7 124 Configuration.warnDeprecatedConfigurationKey('consoleLog', null, 'Use \'logConsole\' instead');
963ee397 125 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logConsole') ? Configuration.getConfig().logConsole : false;
7dde0b73
JB
126 }
127
a4a21709 128 static getLogFormat(): string {
963ee397 129 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFormat') ? Configuration.getConfig().logFormat : 'simple';
027b409a
JB
130 }
131
6bf6769e 132 static getLogRotate(): boolean {
963ee397 133 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logRotate') ? Configuration.getConfig().logRotate : true;
6bf6769e
JB
134 }
135
136 static getLogMaxFiles(): number {
963ee397 137 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logMaxFiles') ? Configuration.getConfig().logMaxFiles : 7;
6bf6769e
JB
138 }
139
324fd4ee
JB
140 static getLogLevel(): string {
141 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logLevel') ? Configuration.getConfig().logLevel.toLowerCase() : 'info';
2e6f5966
JB
142 }
143
a4a21709 144 static getLogFile(): string {
963ee397 145 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFile') ? Configuration.getConfig().logFile : 'combined.log';
7dde0b73
JB
146 }
147
7ec46a9a 148 static getLogErrorFile(): string {
e4362ed7 149 Configuration.warnDeprecatedConfigurationKey('errorFile', null, 'Use \'logErrorFile\' instead');
963ee397 150 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logErrorFile') ? Configuration.getConfig().logErrorFile : 'error.log';
7dde0b73
JB
151 }
152
2dcfe98e 153 static getSupervisionUrls(): string | string[] {
1f5df42a
JB
154 Configuration.warnDeprecatedConfigurationKey('supervisionURLs', null, 'Use \'supervisionUrls\' instead');
155 !Configuration.isUndefined(Configuration.getConfig()['supervisionURLs']) && (Configuration.getConfig().supervisionUrls = Configuration.getConfig()['supervisionURLs'] as string[]);
7dde0b73 156 // Read conf
1f5df42a 157 return Configuration.getConfig().supervisionUrls;
7dde0b73
JB
158 }
159
2dcfe98e
JB
160 static getSupervisionUrlDistribution(): SupervisionUrlDistribution {
161 Configuration.warnDeprecatedConfigurationKey('distributeStationToTenantEqually', null, 'Use \'supervisionUrlDistribution\' instead');
162 Configuration.warnDeprecatedConfigurationKey('distributeStationsToTenantsEqually', null, 'Use \'supervisionUrlDistribution\' instead');
163 return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'supervisionUrlDistribution') ? Configuration.getConfig().supervisionUrlDistribution : SupervisionUrlDistribution.ROUND_ROBIN;
7dde0b73 164 }
eb3937cb 165
23132a44
JB
166 private static logPrefix(): string {
167 return new Date().toLocaleString() + ' Simulator configuration |';
168 }
169
912136b1
JB
170 private static warnDeprecatedConfigurationKey(key: string, sectionName?: string, logMsgToAppend = '') {
171 // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
172 if (sectionName && !Configuration.isUndefined(Configuration.getConfig()[sectionName]) && !Configuration.isUndefined(Configuration.getConfig()[sectionName][key])) {
e4362ed7 173 console.error(chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage in section '${sectionName}'${logMsgToAppend && '. ' + logMsgToAppend}}`);
912136b1 174 } else if (!Configuration.isUndefined(Configuration.getConfig()[key])) {
e4362ed7 175 console.error(chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage${logMsgToAppend && '. ' + logMsgToAppend}}`);
eb3937cb
JB
176 }
177 }
178
179 // Read the config file
180 private static getConfig(): ConfigurationData {
181 if (!Configuration.configuration) {
23132a44
JB
182 try {
183 Configuration.configuration = JSON.parse(fs.readFileSync(Configuration.configurationFilePath, 'utf8')) as ConfigurationData;
184 } catch (error) {
185 Configuration.handleFileException(Configuration.logPrefix(), 'Configuration', Configuration.configurationFilePath, error);
186 }
ded13d97
JB
187 if (!Configuration.configurationFileWatcher) {
188 Configuration.configurationFileWatcher = Configuration.getConfigurationFileWatcher();
189 }
eb3937cb
JB
190 }
191 return Configuration.configuration;
192 }
963ee397 193
ded13d97 194 private static getConfigurationFileWatcher(): fs.FSWatcher {
23132a44 195 try {
860a9c5a 196 return fs.watch(Configuration.configurationFilePath, (event, filename): void => {
3ec10737
JB
197 if (filename && event === 'change') {
198 // Nullify to force configuration file reading
199 Configuration.configuration = null;
200 if (!Configuration.isUndefined(Configuration.configurationChangeCallback)) {
dcaf96dc
JB
201 Configuration.configurationChangeCallback().catch((error) => {
202 throw typeof error === 'string' ? new Error(error) : error;
203 });
3ec10737 204 }
23132a44
JB
205 }
206 });
207 } catch (error) {
860a9c5a 208 Configuration.handleFileException(Configuration.logPrefix(), 'Configuration', Configuration.configurationFilePath, error as Error);
23132a44 209 }
ded13d97
JB
210 }
211
1f5df42a 212 private static getDefaultPerformanceStorageUri(storageType: StorageType) {
d5603918
JB
213 const SQLiteFileName = `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`;
214 switch (storageType) {
215 case StorageType.JSON_FILE:
216 return `file://${path.join(path.resolve(__dirname, '../../'), Constants.DEFAULT_PERFORMANCE_RECORDS_FILENAME)}`;
217 case StorageType.SQLITE:
218 return `file://${path.join(path.resolve(__dirname, '../../'), SQLiteFileName)}`;
219 default:
220 throw new Error(`Performance storage URI is mandatory with storage type '${storageType}'`);
221 }
222 }
223
73d09045 224 private static objectHasOwnProperty(object: unknown, property: string): boolean {
23132a44 225 return Object.prototype.hasOwnProperty.call(object, property) as boolean;
963ee397
JB
226 }
227
73d09045 228 private static isUndefined(obj: unknown): boolean {
963ee397
JB
229 return typeof obj === 'undefined';
230 }
23132a44 231
e0a50bcd 232 private static handleFileException(logPrefix: string, fileType: string, filePath: string, error: NodeJS.ErrnoException, params: HandleErrorParams = { throwError: true }): void {
23132a44
JB
233 const prefix = logPrefix.length !== 0 ? logPrefix + ' ' : '';
234 if (error.code === 'ENOENT') {
e4362ed7 235 console.error(chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' not found: '), error);
72f041bd 236 } else if (error.code === 'EEXIST') {
e4362ed7 237 console.error(chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' already exists: '), error);
72f041bd 238 } else if (error.code === 'EACCES') {
e4362ed7 239 console.error(chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' access denied: '), error);
23132a44 240 } else {
e4362ed7 241 console.error(chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' error: '), error);
23132a44 242 }
e0a50bcd
JB
243 if (params?.throwError) {
244 throw error;
245 }
23132a44 246 }
7dde0b73 247}