]> Piment Noir Git Repositories - e-mobility-charging-stations-simulator.git/commitdiff
fix(auth): remove unnecessary async from sync interface methods
authorJérôme Benoit <jerome.benoit@sap.com>
Mon, 30 Mar 2026 22:59:34 +0000 (00:59 +0200)
committerJérôme Benoit <jerome.benoit@sap.com>
Mon, 30 Mar 2026 22:59:34 +0000 (00:59 +0200)
isRemoteAvailable() was declared as boolean | Promise<boolean> in the
OCPPAuthAdapter interface while both implementations return boolean
synchronously. This forced unnecessary await, Promise.resolve() wrappers,
and async propagation through the call chain.

Fix the interface to boolean and cascade through:
- RemoteAuthStrategy: getStats(), testConnectivity(), checkRemoteAvailability()
  become synchronous
- AuthStrategy.getStats(): JsonObject | Promise<JsonObject> becomes JsonObject
- OCPPAuthService.getStats(): Promise<AuthStats> becomes AuthStats
- OCPPAuthServiceImpl.getStats() becomes synchronous

Update mocks and tests to match sync signatures.

src/charging-station/ocpp/auth/interfaces/OCPPAuthService.ts
src/charging-station/ocpp/auth/services/OCPPAuthServiceImpl.ts
src/charging-station/ocpp/auth/strategies/RemoteAuthStrategy.ts
tests/charging-station/ocpp/auth/helpers/MockFactories.ts
tests/charging-station/ocpp/auth/services/OCPPAuthServiceImpl.test.ts
tests/charging-station/ocpp/auth/strategies/RemoteAuthStrategy.test.ts
tests/helpers/OCPPAuthIntegrationTest.ts

index 35536482cbc9d6ba4e6a7f3dedabe0beb22619a2..d7782dfc46ca4855055e67a4aa5a6a87914384e6 100644 (file)
@@ -165,7 +165,7 @@ export interface AuthStrategy {
   /**
    * Get strategy-specific statistics
    */
-  getStats(): JsonObject | Promise<JsonObject>
+  getStats(): JsonObject
 
   /**
    * Initialize the strategy with configuration
@@ -370,7 +370,7 @@ export interface OCPPAuthAdapter<TVersionId = OCPP20IdTokenType | string> {
   /**
    * Check if remote authorization is available
    */
-  isRemoteAvailable(): boolean | Promise<boolean>
+  isRemoteAvailable(): boolean
 
   /**
    * The OCPP version this adapter handles
@@ -410,7 +410,7 @@ export interface OCPPAuthService {
   /**
    * Get authentication statistics
    */
-  getStats(): Promise<AuthStats>
+  getStats(): AuthStats
 
   /**
    * Invalidate cached authorization for an identifier
index 26672e0eeca48bf33a4cd9be80eda53b40d2db71..655e6c89c39e72e1fc980e8ff4e0e856499581ac 100644 (file)
@@ -350,7 +350,7 @@ export class OCPPAuthServiceImpl implements OCPPAuthService {
    * Get authentication statistics
    * @returns Authentication statistics including cache and rate limiting metrics
    */
-  public async getStats (): Promise<AuthStats> {
+  public getStats (): AuthStats {
     const avgResponseTime =
       this.metrics.totalRequests > 0
         ? this.metrics.totalResponseTime / this.metrics.totalRequests
@@ -373,7 +373,7 @@ export class OCPPAuthServiceImpl implements OCPPAuthService {
       | { blockedRequests: number; rateLimitedIdentifiers: number; totalChecks: number }
     const remoteStrategy = this.strategies.get('remote')
     if (remoteStrategy?.getStats) {
-      const strategyStatistics = await remoteStrategy.getStats()
+      const strategyStatistics = remoteStrategy.getStats()
       if ('cache' in strategyStatistics) {
         const cacheStatistics = strategyStatistics.cache as {
           rateLimit?: {
index 7a073503f9ea252ff9408cb7be526bc859490c07..acf185a62ea26eca66a8afbf717ee767989cdeea 100644 (file)
@@ -99,7 +99,7 @@ export class RemoteAuthStrategy implements AuthStrategy {
       }
 
       // Check if remote service is available
-      const isAvailable = await this.checkRemoteAvailability(adapter, config)
+      const isAvailable = this.checkRemoteAvailability(adapter, config)
       if (!isAvailable) {
         logger.debug(`${moduleName}: Remote service unavailable`)
         return undefined
@@ -223,13 +223,13 @@ export class RemoteAuthStrategy implements AuthStrategy {
    * Get strategy statistics
    * @returns Strategy statistics including success rates, response times, and error counts
    */
-  public async getStats (): Promise<JsonObject> {
+  public getStats (): JsonObject {
     const cacheStatistics = this.authCache ? this.authCache.getStats() : null
 
     let adapterAvailable = false
     if (this.adapter) {
       try {
-        adapterAvailable = await this.adapter.isRemoteAvailable()
+        adapterAvailable = this.adapter.isRemoteAvailable()
       } catch {
         adapterAvailable = false
       }
@@ -335,13 +335,13 @@ export class RemoteAuthStrategy implements AuthStrategy {
    * Test connectivity to remote authorization service
    * @returns True if the OCPP adapter can reach its remote service
    */
-  public async testConnectivity (): Promise<boolean> {
+  public testConnectivity (): boolean {
     if (!this.isInitialized || this.adapter == null) {
       return false
     }
 
     try {
-      return await this.adapter.isRemoteAvailable()
+      return this.adapter.isRemoteAvailable()
     } catch {
       return false
     }
@@ -391,20 +391,12 @@ export class RemoteAuthStrategy implements AuthStrategy {
   /**
    * Check if remote authorization service is available
    * @param adapter - OCPP adapter to check for remote service availability
-   * @param config - Authentication configuration with timeout settings
-   * @returns True if the remote service responds within timeout
+   * @param _config - Authentication configuration (unused)
+   * @returns True if the remote service responds
    */
-  private async checkRemoteAvailability (
-    adapter: OCPPAuthAdapter,
-    config: AuthConfiguration
-  ): Promise<boolean> {
+  private checkRemoteAvailability (adapter: OCPPAuthAdapter, _config: AuthConfiguration): boolean {
     try {
-      const timeout = (config.authorizationTimeout * 1000) / 2
-      return await promiseWithTimeout(
-        Promise.resolve(adapter.isRemoteAvailable()),
-        timeout,
-        new AuthenticationError('Availability check timeout', AuthErrorCode.TIMEOUT)
-      )
+      return adapter.isRemoteAvailable()
     } catch (error) {
       const errorMessage = getErrorMessage(error)
       logger.debug(`${moduleName}: Remote availability check failed: ${errorMessage}`)
index cfc863a2c772a51ddd7b5121149d08b49db3969a..b77b5d924046935e45c2c985428edc2e4960cc69 100644 (file)
@@ -121,19 +121,16 @@ export const createMockAuthService = (overrides?: Partial<OCPPAuthService>): OCP
       /* empty */
     },
     getConfiguration: () => ({}) as AuthConfiguration,
-    getStats: () =>
-      new Promise<Record<string, unknown>>(resolve => {
-        resolve({
-          avgResponseTime: 0,
-          cacheHitRate: 0,
-          failedAuth: 0,
-          lastUpdatedDate: new Date(),
-          localUsageRate: 1,
-          remoteSuccessRate: 0,
-          successfulAuth: 0,
-          totalRequests: 0,
-        })
-      }),
+    getStats: () => ({
+      avgResponseTime: 0,
+      cacheHitRate: 0,
+      failedAuth: 0,
+      lastUpdatedDate: new Date(),
+      localUsageRate: 1,
+      remoteSuccessRate: 0,
+      successfulAuth: 0,
+      totalRequests: 0,
+    }),
     invalidateCache: () => {
       /* empty */
     },
index 919ce6cd1b087581255ca003cb2ad9b132f1f1af..655b146ee92f63d90411b3aa65a8ffa9959426eb 100644 (file)
@@ -182,9 +182,9 @@ await describe('OCPPAuthServiceImpl', async () => {
       mockStation = createMockAuthServiceTestStation('getStats')
     })
 
-    await it('should return authentication statistics', async () => {
+    await it('should return authentication statistics', () => {
       const authService = new OCPPAuthServiceImpl(mockStation)
-      const stats = await authService.getStats()
+      const stats = authService.getStats()
 
       assert.notStrictEqual(stats, undefined)
       assert.notStrictEqual(stats.totalRequests, undefined)
index 0d34d37fe8b4cb7181f9de62042af3f861346935..f6fb2d6a5c1444baf4675c6e102bf37a1027c30d 100644 (file)
@@ -416,30 +416,30 @@ await describe('RemoteAuthStrategy', async () => {
   })
 
   await describe('testConnectivity', async () => {
-    await it('should test connectivity successfully', async () => {
+    await it('should test connectivity successfully', () => {
       strategy.initialize(createTestAuthConfig())
-      const result = await strategy.testConnectivity()
+      const result = strategy.testConnectivity()
       assert.strictEqual(result, true)
     })
 
-    await it('should return false when not initialized', async () => {
+    await it('should return false when not initialized', () => {
       const newStrategy = new RemoteAuthStrategy()
-      const result = await newStrategy.testConnectivity()
+      const result = newStrategy.testConnectivity()
       assert.strictEqual(result, false)
     })
 
-    await it('should return false when adapter unavailable', async () => {
+    await it('should return false when adapter unavailable', () => {
       mockOCPP16Adapter.isRemoteAvailable = () => false
 
       strategy.initialize(createTestAuthConfig())
-      const result = await strategy.testConnectivity()
+      const result = strategy.testConnectivity()
       assert.strictEqual(result, false)
     })
   })
 
   await describe('getStats', async () => {
-    await it('should return strategy statistics', async () => {
-      const stats = await strategy.getStats()
+    await it('should return strategy statistics', () => {
+      const stats = strategy.getStats()
       assert.strictEqual(stats.hasAdapter, true)
       assert.strictEqual(stats.failedRemoteAuth, 0)
       assert.strictEqual(stats.hasAuthCache, true)
@@ -448,9 +448,9 @@ await describe('RemoteAuthStrategy', async () => {
       assert.strictEqual(stats.totalRequests, 0)
     })
 
-    await it('should include adapter statistics', async () => {
+    await it('should include adapter statistics', () => {
       strategy.initialize(createTestAuthConfig())
-      const stats = await strategy.getStats()
+      const stats = strategy.getStats()
       assert.strictEqual(typeof stats.adapterAvailable, 'boolean')
     })
 
@@ -463,7 +463,7 @@ await describe('RemoteAuthStrategy', async () => {
       })
       await strategy.authenticate(successRequest, createTestAuthConfig())
 
-      const statsAfterSuccess = await strategy.getStats()
+      const statsAfterSuccess = strategy.getStats()
       assert.strictEqual(statsAfterSuccess.totalRequests, 1)
       assert.strictEqual(statsAfterSuccess.successfulRemoteAuth, 1)
       assert.strictEqual(statsAfterSuccess.failedRemoteAuth, 0)
@@ -477,7 +477,7 @@ await describe('RemoteAuthStrategy', async () => {
       })
       await strategy.authenticate(failRequest, createTestAuthConfig())
 
-      const statsAfterFailure = await strategy.getStats()
+      const statsAfterFailure = strategy.getStats()
       assert.strictEqual(statsAfterFailure.totalRequests, 2)
       assert.strictEqual(statsAfterFailure.successfulRemoteAuth, 1)
       assert.strictEqual(statsAfterFailure.failedRemoteAuth, 1)
@@ -485,9 +485,9 @@ await describe('RemoteAuthStrategy', async () => {
   })
 
   await describe('cleanup', async () => {
-    await it('should reset strategy state', async () => {
+    await it('should reset strategy state', () => {
       strategy.cleanup()
-      const stats = await strategy.getStats()
+      const stats = strategy.getStats()
       assert.strictEqual(stats.isInitialized, false)
       assert.strictEqual(stats.totalRequests, 0)
     })
index 499d7337ab35296d3a384a601fe570dc89f1e74e..ef0e5f2d07aa853a161efb65379b744a5b46decb 100644 (file)
@@ -251,7 +251,7 @@ export class OCPPAuthIntegrationTest {
       throw new Error('Invalid connectivity test result')
     }
 
-    const stats = await this.authService.getStats()
+    const stats = this.authService.getStats()
     if (typeof stats.totalRequests !== 'number') {
       throw new Error('Invalid statistics object')
     }