From 864e5f8d63cb09c2f4d6ac46b80ea15e34cc9a04 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Mon, 17 Jul 2023 18:25:36 +0200 Subject: [PATCH] refactor: cleanup configuration class usage MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/charging-station/Bootstrap.ts | 76 +++++++------------ .../ui-server/UIServerFactory.ts | 27 ++----- src/performance/PerformanceStatistics.ts | 28 +++---- src/utils/Logger.ts | 62 ++++----------- 4 files changed, 59 insertions(+), 134 deletions(-) diff --git a/src/charging-station/Bootstrap.ts b/src/charging-station/Bootstrap.ts index 2c5d6a7d..957a2f6f 100644 --- a/src/charging-station/Bootstrap.ts +++ b/src/charging-station/Bootstrap.ts @@ -82,21 +82,19 @@ export class Bootstrap extends EventEmitter { dirname(fileURLToPath(import.meta.url)), `ChargingStationWorker${extname(fileURLToPath(import.meta.url))}`, ); - Configuration.getConfigurationSection(ConfigurationSection.uiServer) - .enabled === true && - (this.uiServer = UIServerFactory.getUIServerImplementation( - Configuration.getConfigurationSection(ConfigurationSection.uiServer), - )); - Configuration.getConfigurationSection( - ConfigurationSection.performanceStorage, - ).enabled === true && + const uiServerConfiguration = Configuration.getConfigurationSection( + ConfigurationSection.uiServer, + ); + uiServerConfiguration.enabled === true && + (this.uiServer = UIServerFactory.getUIServerImplementation(uiServerConfiguration)); + const performanceStorageConfiguration = + Configuration.getConfigurationSection( + ConfigurationSection.performanceStorage, + ); + performanceStorageConfiguration.enabled === true && (this.storage = StorageFactory.getStorage( - Configuration.getConfigurationSection( - ConfigurationSection.performanceStorage, - ).type!, - Configuration.getConfigurationSection( - ConfigurationSection.performanceStorage, - ).uri!, + performanceStorageConfiguration.type!, + performanceStorageConfiguration.uri!, this.logPrefix(), )); Configuration.setConfigurationChangeCallback(async () => Bootstrap.getInstance().restart()); @@ -117,7 +115,10 @@ export class Bootstrap extends EventEmitter { if (this.starting === false) { this.starting = true; this.initializeCounters(); - this.initializeWorkerImplementation(); + const workerConfiguration = Configuration.getConfigurationSection( + ConfigurationSection.worker, + ); + this.initializeWorkerImplementation(workerConfiguration); await this.workerImplementation?.start(); await this.storage?.open(); this.uiServer?.start(); @@ -143,21 +144,13 @@ export class Bootstrap extends EventEmitter { this.version } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${ Configuration.workerDynamicPoolInUse() - ? `${Configuration.getConfigurationSection( - ConfigurationSection.worker, - ).poolMinSize?.toString()}/` + ? `${workerConfiguration.poolMinSize?.toString()}/` : '' }${this.workerImplementation?.size}${ Configuration.workerPoolInUse() - ? `/${Configuration.getConfigurationSection( - ConfigurationSection.worker, - ).poolMaxSize?.toString()}` + ? `/${workerConfiguration.poolMaxSize?.toString()}` : '' - } worker(s) concurrently running in '${ - Configuration.getConfigurationSection( - ConfigurationSection.worker, - ).processType - }' mode${ + } worker(s) concurrently running in '${workerConfiguration.processType}' mode${ !isNullOrUndefined(this.workerImplementation?.maxElementsPerWorker) ? ` (${this.workerImplementation?.maxElementsPerWorker} charging station(s) per worker)` : '' @@ -232,12 +225,9 @@ export class Bootstrap extends EventEmitter { await this.start(); } - private initializeWorkerImplementation(): void { + private initializeWorkerImplementation(workerConfiguration: WorkerConfiguration): void { let elementsPerWorker: number | undefined; - if ( - Configuration.getConfigurationSection(ConfigurationSection.worker) - ?.elementsPerWorker === 'auto' - ) { + if (workerConfiguration?.elementsPerWorker === 'auto') { elementsPerWorker = this.numberOfChargingStations > availableParallelism() ? Math.round(this.numberOfChargingStations / availableParallelism()) @@ -246,25 +236,13 @@ export class Bootstrap extends EventEmitter { this.workerImplementation === null && (this.workerImplementation = WorkerFactory.getWorkerImplementation( this.workerScript, - Configuration.getConfigurationSection(ConfigurationSection.worker) - .processType!, + workerConfiguration.processType!, { - workerStartDelay: Configuration.getConfigurationSection( - ConfigurationSection.worker, - ).startDelay, - elementStartDelay: Configuration.getConfigurationSection( - ConfigurationSection.worker, - ).elementStartDelay, - poolMaxSize: Configuration.getConfigurationSection( - ConfigurationSection.worker, - ).poolMaxSize!, - poolMinSize: Configuration.getConfigurationSection( - ConfigurationSection.worker, - ).poolMinSize!, - elementsPerWorker: - elementsPerWorker ?? - (Configuration.getConfigurationSection(ConfigurationSection.worker) - .elementsPerWorker as number), + workerStartDelay: workerConfiguration.startDelay, + elementStartDelay: workerConfiguration.elementStartDelay, + poolMaxSize: workerConfiguration.poolMaxSize!, + poolMinSize: workerConfiguration.poolMinSize!, + elementsPerWorker: elementsPerWorker ?? (workerConfiguration.elementsPerWorker as number), poolOptions: { messageHandler: this.messageHandler.bind(this) as (message: unknown) => void, }, diff --git a/src/charging-station/ui-server/UIServerFactory.ts b/src/charging-station/ui-server/UIServerFactory.ts index 2a6b521e..c4006b03 100644 --- a/src/charging-station/ui-server/UIServerFactory.ts +++ b/src/charging-station/ui-server/UIServerFactory.ts @@ -4,8 +4,7 @@ import type { AbstractUIServer } from './AbstractUIServer'; import { UIHttpServer } from './UIHttpServer'; import { UIServerUtils } from './UIServerUtils'; import { UIWebSocketServer } from './UIWebSocketServer'; -import { ApplicationProtocol, ConfigurationSection, type UIServerConfiguration } from '../../types'; -import { Configuration } from '../../utils'; +import { ApplicationProtocol, type UIServerConfiguration } from '../../types'; export class UIServerFactory { private constructor() { @@ -13,34 +12,20 @@ export class UIServerFactory { } public static getUIServerImplementation( - uiServerConfiguration?: UIServerConfiguration, + uiServerConfiguration: UIServerConfiguration, ): AbstractUIServer | null { - if (UIServerUtils.isLoopback(uiServerConfiguration!.options!.host!) === false) { + if (UIServerUtils.isLoopback(uiServerConfiguration.options!.host!) === false) { console.warn( chalk.yellow( 'Loopback address not detected in UI server configuration. This is not recommended.', ), ); } - switch ( - uiServerConfiguration?.type ?? - Configuration.getConfigurationSection(ConfigurationSection.uiServer) - .type - ) { + switch (uiServerConfiguration.type) { case ApplicationProtocol.WS: - return new UIWebSocketServer( - uiServerConfiguration ?? - Configuration.getConfigurationSection( - ConfigurationSection.uiServer, - ), - ); + return new UIWebSocketServer(uiServerConfiguration); case ApplicationProtocol.HTTP: - return new UIHttpServer( - uiServerConfiguration ?? - Configuration.getConfigurationSection( - ConfigurationSection.uiServer, - ), - ); + return new UIHttpServer(uiServerConfiguration); default: return null; } diff --git a/src/performance/PerformanceStatistics.ts b/src/performance/PerformanceStatistics.ts index 6471265e..479fe071 100644 --- a/src/performance/PerformanceStatistics.ts +++ b/src/performance/PerformanceStatistics.ts @@ -131,20 +131,14 @@ export class PerformanceStatistics { public start(): void { this.startLogStatisticsInterval(); - if ( + const performanceStorageConfiguration = Configuration.getConfigurationSection( ConfigurationSection.performanceStorage, - ).enabled - ) { + ); + if (performanceStorageConfiguration.enabled) { logger.info( - `${this.logPrefix()} storage enabled: type ${ - Configuration.getConfigurationSection( - ConfigurationSection.performanceStorage, - ).type - }, uri: ${ - Configuration.getConfigurationSection( - ConfigurationSection.performanceStorage, - ).uri + `${this.logPrefix()} storage enabled: type ${performanceStorageConfiguration.type}, uri: ${ + performanceStorageConfiguration.uri }`, ); } @@ -182,11 +176,11 @@ export class PerformanceStatistics { } private startLogStatisticsInterval(): void { - const logStatisticsInterval = Configuration.getConfigurationSection( + const logConfiguration = Configuration.getConfigurationSection( ConfigurationSection.log, - ).enabled - ? Configuration.getConfigurationSection(ConfigurationSection.log) - .statisticsInterval! + ); + const logStatisticsInterval = logConfiguration.enabled + ? logConfiguration.statisticsInterval! : 0; if (logStatisticsInterval > 0 && !this.displayInterval) { this.displayInterval = setInterval(() => { @@ -199,9 +193,7 @@ export class PerformanceStatistics { logger.info( `${this.logPrefix()} already logged every ${formatDurationSeconds(logStatisticsInterval)}`, ); - } else if ( - Configuration.getConfigurationSection(ConfigurationSection.log).enabled - ) { + } else if (logConfiguration.enabled) { logger.info( `${this.logPrefix()} log interval is set to ${logStatisticsInterval?.toString()}. Not logging statistics`, ); diff --git a/src/utils/Logger.ts b/src/utils/Logger.ts index 1e22e405..6ea286b2 100644 --- a/src/utils/Logger.ts +++ b/src/utils/Logger.ts @@ -7,38 +7,26 @@ import { Configuration } from './Configuration'; import { insertAt } from './Utils'; import { ConfigurationSection, type LogConfiguration } from '../types'; +const logConfiguration = Configuration.getConfigurationSection( + ConfigurationSection.log, +); let transports: transport[]; -if ( - Configuration.getConfigurationSection(ConfigurationSection.log).rotate === true -) { - const logMaxFiles = Configuration.getConfigurationSection( - ConfigurationSection.log, - ).maxFiles; - const logMaxSize = Configuration.getConfigurationSection( - ConfigurationSection.log, - ).maxSize; +if (logConfiguration.rotate === true) { + const logMaxFiles = logConfiguration.maxFiles; + const logMaxSize = logConfiguration.maxSize; transports = [ new DailyRotateFile({ filename: insertAt( - Configuration.getConfigurationSection(ConfigurationSection.log) - .errorFile!, + logConfiguration.errorFile!, '-%DATE%', - Configuration.getConfigurationSection( - ConfigurationSection.log, - ).errorFile!.indexOf('.log'), + logConfiguration.errorFile!.indexOf('.log'), ), level: 'error', ...(logMaxFiles && { maxFiles: logMaxFiles }), ...(logMaxSize && { maxSize: logMaxSize }), }), new DailyRotateFile({ - filename: insertAt( - Configuration.getConfigurationSection(ConfigurationSection.log).file!, - '-%DATE%', - Configuration.getConfigurationSection( - ConfigurationSection.log, - ).file!.indexOf('.log'), - ), + filename: insertAt(logConfiguration.file!, '-%DATE%', logConfiguration.file!.indexOf('.log')), ...(logMaxFiles && { maxFiles: logMaxFiles }), ...(logMaxSize && { maxSize: logMaxSize }), }), @@ -46,29 +34,19 @@ if ( } else { transports = [ new TransportType.File({ - filename: Configuration.getConfigurationSection(ConfigurationSection.log) - .errorFile, + filename: logConfiguration.errorFile, level: 'error', }), new TransportType.File({ - filename: Configuration.getConfigurationSection(ConfigurationSection.log) - .file, + filename: logConfiguration.file, }), ]; } export const logger = createLogger({ - silent: !Configuration.getConfigurationSection(ConfigurationSection.log) - .enabled, - level: Configuration.getConfigurationSection(ConfigurationSection.log).level, - format: format.combine( - format.splat(), - ( - format[ - Configuration.getConfigurationSection(ConfigurationSection.log).format! - ] as FormatWrap - )(), - ), + silent: !logConfiguration.enabled, + level: logConfiguration.level, + format: format.combine(format.splat(), (format[logConfiguration.format!] as FormatWrap)()), transports, }); @@ -76,18 +54,10 @@ export const logger = createLogger({ // If enabled, log to the `console` with the format: // `${info.level}: ${info.message} JSON.stringify({ ...rest }) ` // -if (Configuration.getConfigurationSection(ConfigurationSection.log).console) { +if (logConfiguration.console) { logger.add( new TransportType.Console({ - format: format.combine( - format.splat(), - ( - format[ - Configuration.getConfigurationSection(ConfigurationSection.log) - .format! - ] as FormatWrap - )(), - ), + format: format.combine(format.splat(), (format[logConfiguration.format!] as FormatWrap)()), }), ); } -- 2.34.1