refactor: switch eslint configuration to strict type checking
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPIncomingRequestService.ts
index 23d0ffdd6d377737fb771f89f001518e6447fe09..ea3e7b7312c03027dcae25c43a85b20a9cd42a7d 100644 (file)
@@ -1,52 +1,86 @@
-import { JSONSchemaType } from 'ajv';
-import Ajv from 'ajv-draft-04';
-import ajvFormats from 'ajv-formats';
+import _Ajv, { type JSONSchemaType, type ValidateFunction } from 'ajv'
+import _ajvFormats from 'ajv-formats'
 
-import OCPPError from '../../exception/OCPPError';
-import { HandleErrorParams } from '../../types/Error';
-import { JsonType } from '../../types/JsonType';
-import { IncomingRequestCommand } from '../../types/ocpp/Requests';
-import logger from '../../utils/Logger';
-import type ChargingStation from '../ChargingStation';
-import { OCPPServiceUtils } from './OCPPServiceUtils';
+import { OCPPConstants } from './OCPPConstants.js'
+import { OCPPServiceUtils } from './OCPPServiceUtils.js'
+import { type ChargingStation, getIdTagsFile } from '../../charging-station/index.js'
+import { OCPPError } from '../../exception/index.js'
+import type {
+  ClearCacheResponse,
+  HandleErrorParams,
+  IncomingRequestCommand,
+  JsonType,
+  OCPPVersion
+} from '../../types/index.js'
+import { logger, setDefaultErrorParams } from '../../utils/index.js'
+type Ajv = _Ajv.default
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+const Ajv = _Ajv.default
+const ajvFormats = _ajvFormats.default
 
-const moduleName = 'OCPPIncomingRequestService';
+const moduleName = 'OCPPIncomingRequestService'
 
-export default abstract class OCPPIncomingRequestService {
-  private static instance: OCPPIncomingRequestService | null = null;
-  private ajv: Ajv;
+export abstract class OCPPIncomingRequestService {
+  private static instance: OCPPIncomingRequestService | null = null
+  private readonly version: OCPPVersion
+  private readonly ajv: Ajv
+  private readonly jsonValidateFunctions: Map<IncomingRequestCommand, ValidateFunction<JsonType>>
+  protected abstract jsonSchemas: Map<IncomingRequestCommand, JSONSchemaType<JsonType>>
 
-  protected constructor() {
-    this.ajv = new Ajv();
-    ajvFormats(this.ajv);
+  protected constructor (version: OCPPVersion) {
+    this.version = version
+    this.ajv = new Ajv({
+      keywords: ['javaType'],
+      multipleOfPrecision: 2
+    })
+    ajvFormats(this.ajv)
+    this.jsonValidateFunctions = new Map<IncomingRequestCommand, ValidateFunction<JsonType>>()
+    this.incomingRequestHandler = this.incomingRequestHandler.bind(this) as <
+      ReqType extends JsonType,
+      // eslint-disable-next-line @typescript-eslint/no-unused-vars
+      ResType extends JsonType,
+    >(
+      chargingStation: ChargingStation,
+      messageId: string,
+      commandName: IncomingRequestCommand,
+      commandPayload: ReqType
+    ) => Promise<void>
+    this.validateIncomingRequestPayload = this.validateIncomingRequestPayload.bind(this) as <
+      T extends JsonType,
+    >(
+      chargingStation: ChargingStation,
+      commandName: IncomingRequestCommand,
+      schema: JSONSchemaType<T>,
+      payload: T
+    ) => boolean
   }
 
   public static getInstance<T extends OCPPIncomingRequestService>(this: new () => T): T {
     if (OCPPIncomingRequestService.instance === null) {
-      OCPPIncomingRequestService.instance = new this();
+      OCPPIncomingRequestService.instance = new this()
     }
-    return OCPPIncomingRequestService.instance as T;
+    return OCPPIncomingRequestService.instance as T
   }
 
-  protected handleIncomingRequestError<T>(
+  protected handleIncomingRequestError<T extends JsonType>(
     chargingStation: ChargingStation,
     commandName: IncomingRequestCommand,
     error: Error,
-    params: HandleErrorParams<T> = { throwError: true }
-  ): T {
+    params: HandleErrorParams<T> = { throwError: true, consoleOut: false }
+  ): T | undefined {
+    setDefaultErrorParams(params)
     logger.error(
-      `${chargingStation.logPrefix()} ${moduleName}.handleIncomingRequestError: Incoming request command %s error: %j`,
-      commandName,
+      `${chargingStation.logPrefix()} ${moduleName}.handleIncomingRequestError: Incoming request command '${commandName}' error:`,
       error
-    );
-    if (!params?.throwError && params?.errorResponse) {
-      return params?.errorResponse;
+    )
+    if (params.throwError === false && params.errorResponse != null) {
+      return params.errorResponse
     }
-    if (params?.throwError && !params?.errorResponse) {
-      throw error;
+    if (params.throwError === true && params.errorResponse == null) {
+      throw error
     }
-    if (params?.throwError && params?.errorResponse) {
-      return params?.errorResponse;
+    if (params.throwError === true && params.errorResponse != null) {
+      return params.errorResponse
     }
   }
 
@@ -56,29 +90,49 @@ export default abstract class OCPPIncomingRequestService {
     schema: JSONSchemaType<T>,
     payload: T
   ): boolean {
-    if (!chargingStation.getPayloadSchemaValidation()) {
-      return true;
+    if (chargingStation.stationInfo?.ocppStrictCompliance === false) {
+      return true
     }
-    const validate = this.ajv.compile(schema);
+    const validate = this.getJsonIncomingRequestValidateFunction<T>(commandName, schema)
     if (validate(payload)) {
-      return true;
+      return true
     }
     logger.error(
-      `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestPayload: Incoming request PDU is invalid: %j`,
+      `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestPayload: Command '${commandName}' incoming request PDU is invalid: %j`,
       validate.errors
-    );
+    )
     throw new OCPPError(
       OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
       'Incoming request PDU is invalid',
       commandName,
-      JSON.stringify(validate.errors, null, 2)
-    );
+      JSON.stringify(validate.errors, undefined, 2)
+    )
+  }
+
+  protected handleRequestClearCache (chargingStation: ChargingStation): ClearCacheResponse {
+    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+    if (chargingStation.idTagsCache.deleteIdTags(getIdTagsFile(chargingStation.stationInfo!)!)) {
+      return OCPPConstants.OCPP_RESPONSE_ACCEPTED
+    }
+    return OCPPConstants.OCPP_RESPONSE_REJECTED
+  }
+
+  private getJsonIncomingRequestValidateFunction<T extends JsonType>(
+    commandName: IncomingRequestCommand,
+    schema: JSONSchemaType<T>
+  ): ValidateFunction<JsonType> {
+    if (!this.jsonValidateFunctions.has(commandName)) {
+      this.jsonValidateFunctions.set(commandName, this.ajv.compile<T>(schema).bind(this))
+    }
+    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+    return this.jsonValidateFunctions.get(commandName)!
   }
 
-  public abstract incomingRequestHandler(
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  public abstract incomingRequestHandler<ReqType extends JsonType, ResType extends JsonType>(
     chargingStation: ChargingStation,
     messageId: string,
     commandName: IncomingRequestCommand,
-    commandPayload: JsonType
-  ): Promise<void>;
+    commandPayload: ReqType
+  ): Promise<void>
 }