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