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