| 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 unknown as StationTemplateUrl[]); |
| 132 | Configuration.getConfig().stationTemplateUrls.forEach((stationUrl: StationTemplateUrl) => { |
| 133 | if (!Utils.isUndefined(stationUrl['numberOfStation'])) { |
| 134 | console.error( |
| 135 | chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key 'numberOfStation' usage for template file '${ |
| 136 | stationUrl.file |
| 137 | }' in 'stationTemplateUrls'. Use 'numberOfStations' instead}` |
| 138 | ); |
| 139 | } |
| 140 | }); |
| 141 | // Read conf |
| 142 | return Configuration.getConfig()?.stationTemplateUrls; |
| 143 | } |
| 144 | |
| 145 | static getWorker(): WorkerConfiguration { |
| 146 | Configuration.warnDeprecatedConfigurationKey( |
| 147 | 'useWorkerPool', |
| 148 | undefined, |
| 149 | "Use 'worker' section to define the type of worker process model instead" |
| 150 | ); |
| 151 | Configuration.warnDeprecatedConfigurationKey( |
| 152 | 'workerProcess', |
| 153 | undefined, |
| 154 | "Use 'worker' section to define the type of worker process model instead" |
| 155 | ); |
| 156 | Configuration.warnDeprecatedConfigurationKey( |
| 157 | 'workerStartDelay', |
| 158 | undefined, |
| 159 | "Use 'worker' section to define the worker start delay instead" |
| 160 | ); |
| 161 | Configuration.warnDeprecatedConfigurationKey( |
| 162 | 'chargingStationsPerWorker', |
| 163 | undefined, |
| 164 | "Use 'worker' section to define the number of element(s) per worker instead" |
| 165 | ); |
| 166 | Configuration.warnDeprecatedConfigurationKey( |
| 167 | 'elementStartDelay', |
| 168 | undefined, |
| 169 | "Use 'worker' section to define the worker's element start delay instead" |
| 170 | ); |
| 171 | Configuration.warnDeprecatedConfigurationKey( |
| 172 | 'workerPoolMinSize', |
| 173 | undefined, |
| 174 | "Use 'worker' section to define the worker pool minimum size instead" |
| 175 | ); |
| 176 | Configuration.warnDeprecatedConfigurationKey( |
| 177 | 'workerPoolSize;', |
| 178 | undefined, |
| 179 | "Use 'worker' section to define the worker pool maximum size instead" |
| 180 | ); |
| 181 | Configuration.warnDeprecatedConfigurationKey( |
| 182 | 'workerPoolMaxSize;', |
| 183 | undefined, |
| 184 | "Use 'worker' section to define the worker pool maximum size instead" |
| 185 | ); |
| 186 | Configuration.warnDeprecatedConfigurationKey( |
| 187 | 'workerPoolStrategy;', |
| 188 | undefined, |
| 189 | "Use 'worker' section to define the worker pool strategy instead" |
| 190 | ); |
| 191 | let workerConfiguration: WorkerConfiguration = { |
| 192 | processType: Utils.hasOwnProp(Configuration.getConfig(), 'workerProcess') |
| 193 | ? Configuration.getConfig()?.workerProcess |
| 194 | : WorkerProcessType.WORKER_SET, |
| 195 | startDelay: Utils.hasOwnProp(Configuration.getConfig(), 'workerStartDelay') |
| 196 | ? Configuration.getConfig()?.workerStartDelay |
| 197 | : WorkerConstants.DEFAULT_WORKER_START_DELAY, |
| 198 | elementsPerWorker: Utils.hasOwnProp(Configuration.getConfig(), 'chargingStationsPerWorker') |
| 199 | ? Configuration.getConfig()?.chargingStationsPerWorker |
| 200 | : WorkerConstants.DEFAULT_ELEMENTS_PER_WORKER, |
| 201 | elementStartDelay: Utils.hasOwnProp(Configuration.getConfig(), 'elementStartDelay') |
| 202 | ? Configuration.getConfig()?.elementStartDelay |
| 203 | : WorkerConstants.DEFAULT_ELEMENT_START_DELAY, |
| 204 | poolMinSize: Utils.hasOwnProp(Configuration.getConfig(), 'workerPoolMinSize') |
| 205 | ? Configuration.getConfig()?.workerPoolMinSize |
| 206 | : WorkerConstants.DEFAULT_POOL_MIN_SIZE, |
| 207 | poolMaxSize: Utils.hasOwnProp(Configuration.getConfig(), 'workerPoolMaxSize') |
| 208 | ? Configuration.getConfig()?.workerPoolMaxSize |
| 209 | : WorkerConstants.DEFAULT_POOL_MAX_SIZE, |
| 210 | poolStrategy: |
| 211 | Configuration.getConfig()?.workerPoolStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN, |
| 212 | }; |
| 213 | if (Utils.hasOwnProp(Configuration.getConfig(), 'worker')) { |
| 214 | workerConfiguration = { ...workerConfiguration, ...Configuration.getConfig()?.worker }; |
| 215 | } |
| 216 | return workerConfiguration; |
| 217 | } |
| 218 | |
| 219 | static getLogConsole(): boolean | undefined { |
| 220 | Configuration.warnDeprecatedConfigurationKey( |
| 221 | 'consoleLog', |
| 222 | undefined, |
| 223 | "Use 'logConsole' instead" |
| 224 | ); |
| 225 | return Utils.hasOwnProp(Configuration.getConfig(), 'logConsole') |
| 226 | ? Configuration.getConfig()?.logConsole |
| 227 | : false; |
| 228 | } |
| 229 | |
| 230 | static getLogFormat(): string | undefined { |
| 231 | return Utils.hasOwnProp(Configuration.getConfig(), 'logFormat') |
| 232 | ? Configuration.getConfig()?.logFormat |
| 233 | : 'simple'; |
| 234 | } |
| 235 | |
| 236 | static getLogRotate(): boolean | undefined { |
| 237 | return Utils.hasOwnProp(Configuration.getConfig(), 'logRotate') |
| 238 | ? Configuration.getConfig()?.logRotate |
| 239 | : true; |
| 240 | } |
| 241 | |
| 242 | static getLogMaxFiles(): number | string | false | undefined { |
| 243 | return ( |
| 244 | Utils.hasOwnProp(Configuration.getConfig(), 'logMaxFiles') && |
| 245 | Configuration.getConfig()?.logMaxFiles |
| 246 | ); |
| 247 | } |
| 248 | |
| 249 | static getLogMaxSize(): number | string | false | undefined { |
| 250 | return ( |
| 251 | Utils.hasOwnProp(Configuration.getConfig(), 'logMaxFiles') && |
| 252 | Configuration.getConfig()?.logMaxSize |
| 253 | ); |
| 254 | } |
| 255 | |
| 256 | static getLogLevel(): string | undefined { |
| 257 | return Utils.hasOwnProp(Configuration.getConfig(), 'logLevel') |
| 258 | ? Configuration.getConfig()?.logLevel?.toLowerCase() |
| 259 | : 'info'; |
| 260 | } |
| 261 | |
| 262 | static getLogFile(): string | undefined { |
| 263 | return Utils.hasOwnProp(Configuration.getConfig(), 'logFile') |
| 264 | ? Configuration.getConfig()?.logFile |
| 265 | : 'combined.log'; |
| 266 | } |
| 267 | |
| 268 | static getLogErrorFile(): string | undefined { |
| 269 | Configuration.warnDeprecatedConfigurationKey( |
| 270 | 'errorFile', |
| 271 | undefined, |
| 272 | "Use 'logErrorFile' instead" |
| 273 | ); |
| 274 | return Utils.hasOwnProp(Configuration.getConfig(), 'logErrorFile') |
| 275 | ? Configuration.getConfig()?.logErrorFile |
| 276 | : 'error.log'; |
| 277 | } |
| 278 | |
| 279 | static getSupervisionUrls(): string | string[] | undefined { |
| 280 | Configuration.warnDeprecatedConfigurationKey( |
| 281 | 'supervisionURLs', |
| 282 | undefined, |
| 283 | "Use 'supervisionUrls' instead" |
| 284 | ); |
| 285 | !Utils.isUndefined(Configuration.getConfig()['supervisionURLs']) && |
| 286 | (Configuration.getConfig().supervisionUrls = Configuration.getConfig()['supervisionURLs'] as |
| 287 | | string |
| 288 | | string[]); |
| 289 | // Read conf |
| 290 | return Configuration.getConfig()?.supervisionUrls; |
| 291 | } |
| 292 | |
| 293 | static getSupervisionUrlDistribution(): SupervisionUrlDistribution | undefined { |
| 294 | Configuration.warnDeprecatedConfigurationKey( |
| 295 | 'distributeStationToTenantEqually', |
| 296 | undefined, |
| 297 | "Use 'supervisionUrlDistribution' instead" |
| 298 | ); |
| 299 | Configuration.warnDeprecatedConfigurationKey( |
| 300 | 'distributeStationsToTenantsEqually', |
| 301 | undefined, |
| 302 | "Use 'supervisionUrlDistribution' instead" |
| 303 | ); |
| 304 | return Utils.hasOwnProp(Configuration.getConfig(), 'supervisionUrlDistribution') |
| 305 | ? Configuration.getConfig()?.supervisionUrlDistribution |
| 306 | : SupervisionUrlDistribution.ROUND_ROBIN; |
| 307 | } |
| 308 | |
| 309 | private static logPrefix = (): string => { |
| 310 | return `${new Date().toLocaleString()} Simulator configuration |`; |
| 311 | }; |
| 312 | |
| 313 | private static warnDeprecatedConfigurationKey( |
| 314 | key: string, |
| 315 | sectionName?: string, |
| 316 | logMsgToAppend = '' |
| 317 | ) { |
| 318 | if ( |
| 319 | sectionName && |
| 320 | !Utils.isUndefined(Configuration.getConfig()[sectionName]) && |
| 321 | !Utils.isUndefined((Configuration.getConfig()[sectionName] as Record<string, unknown>)[key]) |
| 322 | ) { |
| 323 | console.error( |
| 324 | chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage in section '${sectionName}'${ |
| 325 | logMsgToAppend.trim().length > 0 && `. ${logMsgToAppend}` |
| 326 | }}` |
| 327 | ); |
| 328 | } else if (!Utils.isUndefined(Configuration.getConfig()[key])) { |
| 329 | console.error( |
| 330 | chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage${ |
| 331 | logMsgToAppend.trim().length > 0 && `. ${logMsgToAppend}` |
| 332 | }}` |
| 333 | ); |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | // Read the config file |
| 338 | private static getConfig(): ConfigurationData | null { |
| 339 | if (!Configuration.configuration) { |
| 340 | try { |
| 341 | Configuration.configuration = JSON.parse( |
| 342 | fs.readFileSync(Configuration.configurationFile, 'utf8') |
| 343 | ) as ConfigurationData; |
| 344 | } catch (error) { |
| 345 | FileUtils.handleFileException( |
| 346 | Configuration.configurationFile, |
| 347 | FileType.Configuration, |
| 348 | error as NodeJS.ErrnoException, |
| 349 | Configuration.logPrefix(), |
| 350 | { consoleOut: true } |
| 351 | ); |
| 352 | } |
| 353 | if (!Configuration.configurationFileWatcher) { |
| 354 | Configuration.configurationFileWatcher = Configuration.getConfigurationFileWatcher(); |
| 355 | } |
| 356 | } |
| 357 | return Configuration.configuration; |
| 358 | } |
| 359 | |
| 360 | private static getConfigurationFileWatcher(): fs.FSWatcher | undefined { |
| 361 | try { |
| 362 | return fs.watch(Configuration.configurationFile, (event, filename): void => { |
| 363 | if (filename?.trim().length > 0 && event === 'change') { |
| 364 | // Nullify to force configuration file reading |
| 365 | Configuration.configuration = null; |
| 366 | if (!Utils.isUndefined(Configuration.configurationChangeCallback)) { |
| 367 | Configuration.configurationChangeCallback().catch((error) => { |
| 368 | throw typeof error === 'string' ? new Error(error) : error; |
| 369 | }); |
| 370 | } |
| 371 | } |
| 372 | }); |
| 373 | } catch (error) { |
| 374 | FileUtils.handleFileException( |
| 375 | Configuration.configurationFile, |
| 376 | FileType.Configuration, |
| 377 | error as NodeJS.ErrnoException, |
| 378 | Configuration.logPrefix(), |
| 379 | { consoleOut: true } |
| 380 | ); |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | private static getDefaultPerformanceStorageUri(storageType: StorageType) { |
| 385 | switch (storageType) { |
| 386 | case StorageType.JSON_FILE: |
| 387 | return `file://${path.join( |
| 388 | path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../'), |
| 389 | Constants.DEFAULT_PERFORMANCE_RECORDS_FILENAME |
| 390 | )}`; |
| 391 | case StorageType.SQLITE: |
| 392 | return `file://${path.join( |
| 393 | path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../'), |
| 394 | `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db` |
| 395 | )}`; |
| 396 | default: |
| 397 | throw new Error(`Performance storage URI is mandatory with storage type '${storageType}'`); |
| 398 | } |
| 399 | } |
| 400 | } |