From b1b03bf7a9ad234e00822950a791b1befd82ec0b Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Fri, 3 Apr 2026 17:42:38 +0200 Subject: [PATCH] refactor: use getErrorMessage helper and extract auth cache constant Replace 7 instanceof Error ternary patterns with getErrorMessage() for consistent error message extraction. Extract hardcoded maxEntries 1000 to Constants.DEFAULT_AUTH_CACHE_MAX_ENTRIES across InMemoryAuthCache, AuthComponentFactory, and OCPPAuthServiceImpl. --- .../ocpp/2.0/OCPP20CertificateManager.ts | 2 +- src/charging-station/ocpp/2.0/OCPP20RequestService.ts | 4 ++-- .../ocpp/auth/adapters/OCPP16AuthAdapter.ts | 4 ++-- .../ocpp/auth/adapters/OCPP20AuthAdapter.ts | 4 ++-- .../ocpp/auth/cache/InMemoryAuthCache.ts | 6 +++--- .../ocpp/auth/factories/AuthComponentFactory.ts | 3 ++- .../ocpp/auth/services/OCPPAuthServiceImpl.ts | 3 ++- src/charging-station/ui-server/UIMCPServer.ts | 11 +++-------- src/performance/PerformanceStatistics.ts | 3 ++- src/utils/Constants.ts | 2 ++ 10 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/charging-station/ocpp/2.0/OCPP20CertificateManager.ts b/src/charging-station/ocpp/2.0/OCPP20CertificateManager.ts index 9468f1b6..ea79c572 100644 --- a/src/charging-station/ocpp/2.0/OCPP20CertificateManager.ts +++ b/src/charging-station/ocpp/2.0/OCPP20CertificateManager.ts @@ -486,7 +486,7 @@ export class OCPP20CertificateManager { return { valid: true } } catch (error) { return { - reason: `Certificate parsing failed: ${error instanceof Error ? error.message : 'Unknown error'}`, + reason: `Certificate parsing failed: ${getErrorMessage(error)}`, valid: false, } } diff --git a/src/charging-station/ocpp/2.0/OCPP20RequestService.ts b/src/charging-station/ocpp/2.0/OCPP20RequestService.ts index 980aecb0..2e456a0b 100644 --- a/src/charging-station/ocpp/2.0/OCPP20RequestService.ts +++ b/src/charging-station/ocpp/2.0/OCPP20RequestService.ts @@ -19,7 +19,7 @@ import { OCPPVersion, type RequestParams, } from '../../../types/index.js' -import { generateUUID, logger } from '../../../utils/index.js' +import { generateUUID, getErrorMessage, logger } from '../../../utils/index.js' import { OCPPRequestService } from '../OCPPRequestService.js' import { createPayloadValidatorMap, isRequestCommandSupported } from '../OCPPServiceUtils.js' import { generatePkcs10Csr } from './Asn1DerUtils.js' @@ -179,7 +179,7 @@ export class OCPP20RequestService extends OCPPRequestService { csr = generatePkcs10Csr(stationId, orgName) } catch (error) { - const errorMsg = `Failed to generate CSR: ${error instanceof Error ? error.message : 'Unknown error'}` + const errorMsg = `Failed to generate CSR: ${getErrorMessage(error)}` logger.error( `${chargingStation.logPrefix()} ${moduleName}.buildRequestPayload: ${errorMsg}` ) diff --git a/src/charging-station/ocpp/auth/adapters/OCPP16AuthAdapter.ts b/src/charging-station/ocpp/auth/adapters/OCPP16AuthAdapter.ts index fb90d924..17d5d386 100644 --- a/src/charging-station/ocpp/auth/adapters/OCPP16AuthAdapter.ts +++ b/src/charging-station/ocpp/auth/adapters/OCPP16AuthAdapter.ts @@ -16,7 +16,7 @@ import { RequestCommand, StandardParametersKey, } from '../../../../types/index.js' -import { convertToBoolean, logger, truncateId } from '../../../../utils/index.js' +import { convertToBoolean, getErrorMessage, logger, truncateId } from '../../../../utils/index.js' import { AuthContext, AuthenticationMethod, @@ -105,7 +105,7 @@ export class OCPP16AuthAdapter implements OCPPAuthAdapter { return { additionalInfo: { connectorId, - error: error instanceof Error ? error.message : 'Unknown error', + error: getErrorMessage(error), transactionId, }, isOffline: false, diff --git a/src/charging-station/ocpp/auth/adapters/OCPP20AuthAdapter.ts b/src/charging-station/ocpp/auth/adapters/OCPP20AuthAdapter.ts index 937d3fcd..84634789 100644 --- a/src/charging-station/ocpp/auth/adapters/OCPP20AuthAdapter.ts +++ b/src/charging-station/ocpp/auth/adapters/OCPP20AuthAdapter.ts @@ -23,7 +23,7 @@ import { OCPP20RequiredVariableName, OCPPVersion, } from '../../../../types/index.js' -import { logger, truncateId } from '../../../../utils/index.js' +import { getErrorMessage, logger, truncateId } from '../../../../utils/index.js' import { AuthContext, AuthenticationMethod, @@ -142,7 +142,7 @@ export class OCPP20AuthAdapter implements OCPPAuthAdapter { return { additionalInfo: { connectorId, - error: error instanceof Error ? error.message : 'Unknown error', + error: getErrorMessage(error), transactionId, }, isOffline: false, diff --git a/src/charging-station/ocpp/auth/cache/InMemoryAuthCache.ts b/src/charging-station/ocpp/auth/cache/InMemoryAuthCache.ts index e46c10d2..4b46aac9 100644 --- a/src/charging-station/ocpp/auth/cache/InMemoryAuthCache.ts +++ b/src/charging-station/ocpp/auth/cache/InMemoryAuthCache.ts @@ -3,7 +3,7 @@ import { secondsToMilliseconds } from 'date-fns' import type { AuthCache, CacheStats } from '../interfaces/OCPPAuthService.js' import type { AuthorizationResult } from '../types/AuthTypes.js' -import { logger, truncateId } from '../../../../utils/index.js' +import { Constants, logger, truncateId } from '../../../../utils/index.js' import { AuthorizationStatus } from '../types/AuthTypes.js' const moduleName = 'InMemoryAuthCache' @@ -108,7 +108,7 @@ export class InMemoryAuthCache implements AuthCache { * @param options.cleanupIntervalSeconds - Periodic cleanup interval in seconds (default: 300, 0 to disable) * @param options.defaultTtl - Default TTL in seconds (default: 3600) * @param options.maxAbsoluteLifetimeMs - Absolute lifetime cap in milliseconds (default: 86400000) - * @param options.maxEntries - Maximum number of cache entries (default: 1000) + * @param options.maxEntries - Maximum number of cache entries (default: Constants.DEFAULT_AUTH_CACHE_MAX_ENTRIES) * @param options.rateLimit - Rate limiting configuration * @param options.rateLimit.enabled - Enable rate limiting (default: false) * @param options.rateLimit.maxRequests - Max requests per window (default: 10) @@ -124,7 +124,7 @@ export class InMemoryAuthCache implements AuthCache { this.defaultTtl = options?.defaultTtl ?? 3600 // 1 hour default this.maxAbsoluteLifetimeMs = options?.maxAbsoluteLifetimeMs ?? InMemoryAuthCache.DEFAULT_MAX_ABSOLUTE_LIFETIME_MS - this.maxEntries = Math.max(1, options?.maxEntries ?? 1000) + this.maxEntries = Math.max(1, options?.maxEntries ?? Constants.DEFAULT_AUTH_CACHE_MAX_ENTRIES) this.rateLimit = { enabled: options?.rateLimit?.enabled ?? false, maxRequests: options?.rateLimit?.maxRequests ?? 10, // 10 requests per window diff --git a/src/charging-station/ocpp/auth/factories/AuthComponentFactory.ts b/src/charging-station/ocpp/auth/factories/AuthComponentFactory.ts index a9242151..fa938a36 100644 --- a/src/charging-station/ocpp/auth/factories/AuthComponentFactory.ts +++ b/src/charging-station/ocpp/auth/factories/AuthComponentFactory.ts @@ -9,6 +9,7 @@ import type { AuthConfiguration } from '../types/AuthTypes.js' import { OCPPError } from '../../../../exception/index.js' import { ErrorType, OCPPVersion } from '../../../../types/index.js' +import { Constants } from '../../../../utils/index.js' import { OCPP16AuthAdapter } from '../adapters/OCPP16AuthAdapter.js' import { OCPP20AuthAdapter } from '../adapters/OCPP20AuthAdapter.js' import { InMemoryAuthCache } from '../cache/InMemoryAuthCache.js' @@ -70,7 +71,7 @@ export class AuthComponentFactory { static createAuthCache (config: AuthConfiguration): AuthCache { return new InMemoryAuthCache({ defaultTtl: config.authorizationCacheLifetime ?? 3600, - maxEntries: config.maxCacheEntries ?? 1000, + maxEntries: config.maxCacheEntries ?? Constants.DEFAULT_AUTH_CACHE_MAX_ENTRIES, }) } diff --git a/src/charging-station/ocpp/auth/services/OCPPAuthServiceImpl.ts b/src/charging-station/ocpp/auth/services/OCPPAuthServiceImpl.ts index e1958265..f320921b 100644 --- a/src/charging-station/ocpp/auth/services/OCPPAuthServiceImpl.ts +++ b/src/charging-station/ocpp/auth/services/OCPPAuthServiceImpl.ts @@ -5,6 +5,7 @@ import type { OCPPAuthAdapter } from '../interfaces/OCPPAuthService.js' import { OCPPError } from '../../../../exception/index.js' import { ErrorType, OCPPVersion } from '../../../../types/index.js' import { + Constants, convertToDate, ensureError, getErrorMessage, @@ -592,7 +593,7 @@ export class OCPPAuthServiceImpl implements OCPPAuthService { certificateValidationStrict: false, localAuthListEnabled: true, localPreAuthorize: false, - maxCacheEntries: 1000, + maxCacheEntries: Constants.DEFAULT_AUTH_CACHE_MAX_ENTRIES, ocppVersion: this.chargingStation.stationInfo?.ocppVersion, offlineAuthorizationEnabled: true, remoteAuthorization: true, diff --git a/src/charging-station/ui-server/UIMCPServer.ts b/src/charging-station/ui-server/UIMCPServer.ts index a7b384bd..38854dcd 100644 --- a/src/charging-station/ui-server/UIMCPServer.ts +++ b/src/charging-station/ui-server/UIMCPServer.ts @@ -22,7 +22,7 @@ import { type UIServerConfiguration, type UUIDv4, } from '../../types/index.js' -import { generateUUID, logger } from '../../utils/index.js' +import { generateUUID, getErrorMessage, logger } from '../../utils/index.js' import { AbstractUIServer } from './AbstractUIServer.js' import { mcpToolSchemas, @@ -278,8 +278,7 @@ export class UIMCPServer extends AbstractUIServer { } catch (error: unknown) { logger.error(`${this.logPrefix(moduleName, 'handleMcpRequest')} MCP transport error:`, error) const isBadRequest = - error instanceof SyntaxError || - (error instanceof Error && error.message.includes('Payload too large')) + error instanceof SyntaxError || getErrorMessage(error).includes('Payload too large') this.sendErrorResponse(res, isBadRequest ? 400 : 500) } } @@ -404,11 +403,7 @@ export class UIMCPServer extends AbstractUIServer { clearTimeout(pending.timeout) this.pendingMcpRequests.delete(uuid) } - resolve( - UIMCPServer.createToolErrorResponse( - error instanceof Error ? error.message : String(error) - ) - ) + resolve(UIMCPServer.createToolErrorResponse(getErrorMessage(error))) }) }) } diff --git a/src/performance/PerformanceStatistics.ts b/src/performance/PerformanceStatistics.ts index 07439a29..269fa58c 100644 --- a/src/performance/PerformanceStatistics.ts +++ b/src/performance/PerformanceStatistics.ts @@ -28,6 +28,7 @@ import { extractTimeSeriesValues, formatDurationSeconds, generateUUID, + getErrorMessage, JSONStringify, logger, logPrefix, @@ -82,7 +83,7 @@ export class PerformanceStatistics { try { performance.measure(name, markId) } catch (error) { - if (error instanceof Error && error.message.includes('performance mark has not been set')) { + if (getErrorMessage(error).includes('performance mark has not been set')) { /* Ignore */ } else { throw error diff --git a/src/utils/Constants.ts b/src/utils/Constants.ts index ed6e9a49..306ebcb5 100644 --- a/src/utils/Constants.ts +++ b/src/utils/Constants.ts @@ -22,6 +22,8 @@ export class Constants { static readonly DEFAULT_ATG_WAIT_TIME = 1000 // Ms + static readonly DEFAULT_AUTH_CACHE_MAX_ENTRIES = 1000 + static readonly DEFAULT_BOOT_NOTIFICATION_INTERVAL = 60000 // Ms static readonly DEFAULT_CIRCULAR_BUFFER_CAPACITY = 386 -- 2.43.0