fix: ensure OCPP request timeouting cancel it
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPIncomingRequestService.ts
index 66dd198d0620f16261e7784ab6075c99822ae8d0..4b27f9d82f8de91b38bd1a19c4a826ebe6800d6b 100644 (file)
@@ -1,6 +1,6 @@
 import { AsyncResource } from 'node:async_hooks';
 
-import Ajv, { type JSONSchemaType } from 'ajv';
+import Ajv, { type JSONSchemaType, type ValidateFunction } from 'ajv';
 import ajvFormats from 'ajv-formats';
 
 import { OCPPConstants } from './OCPPConstants';
@@ -11,7 +11,6 @@ import type {
   ClearCacheResponse,
   HandleErrorParams,
   IncomingRequestCommand,
-  JsonObject,
   JsonType,
   OCPPVersion,
 } from '../../types';
@@ -23,7 +22,8 @@ export abstract class OCPPIncomingRequestService extends AsyncResource {
   private static instance: OCPPIncomingRequestService | null = null;
   private readonly version: OCPPVersion;
   private readonly ajv: Ajv;
-  protected abstract jsonSchemas: Map<IncomingRequestCommand, JSONSchemaType<JsonObject>>;
+  private jsonValidateFunctions: Map<IncomingRequestCommand, ValidateFunction<JsonType>>;
+  protected abstract jsonSchemas: Map<IncomingRequestCommand, JSONSchemaType<JsonType>>;
 
   protected constructor(version: OCPPVersion) {
     super(moduleName);
@@ -33,19 +33,24 @@ export abstract class OCPPIncomingRequestService extends AsyncResource {
       multipleOfPrecision: 2,
     });
     ajvFormats(this.ajv);
-    this.incomingRequestHandler = this.incomingRequestHandler.bind(this) as (
+    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: JsonType
+      commandPayload: ReqType,
     ) => Promise<void>;
     this.validateIncomingRequestPayload = this.validateIncomingRequestPayload.bind(this) as <
-      T extends JsonType
+      T extends JsonType,
     >(
       chargingStation: ChargingStation,
       commandName: IncomingRequestCommand,
       schema: JSONSchemaType<T>,
-      payload: T
+      payload: T,
     ) => boolean;
   }
 
@@ -60,12 +65,12 @@ export abstract class OCPPIncomingRequestService extends AsyncResource {
     chargingStation: ChargingStation,
     commandName: IncomingRequestCommand,
     error: Error,
-    params: HandleErrorParams<T> = { throwError: true, consoleOut: false }
+    params: HandleErrorParams<T> = { throwError: true, consoleOut: false },
   ): T | undefined {
     setDefaultErrorParams(params);
     logger.error(
       `${chargingStation.logPrefix()} ${moduleName}.handleIncomingRequestError: Incoming request command '${commandName}' error:`,
-      error
+      error,
     );
     if (!params?.throwError && params?.errorResponse) {
       return params?.errorResponse;
@@ -82,38 +87,49 @@ export abstract class OCPPIncomingRequestService extends AsyncResource {
     chargingStation: ChargingStation,
     commandName: IncomingRequestCommand,
     schema: JSONSchemaType<T>,
-    payload: T
+    payload: T,
   ): boolean {
-    if (chargingStation.getPayloadSchemaValidation() === false) {
+    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;
     }
     logger.error(
       `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestPayload: Command '${commandName}' incoming request PDU is invalid: %j`,
-      validate.errors
+      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 {
-    if (chargingStation.idTagsCache.deleteIdTags(getIdTagsFile(chargingStation.stationInfo))) {
+    if (chargingStation.idTagsCache.deleteIdTags(getIdTagsFile(chargingStation.stationInfo)!)) {
       return OCPPConstants.OCPP_RESPONSE_ACCEPTED;
     }
     return OCPPConstants.OCPP_RESPONSE_REJECTED;
   }
 
-  public abstract incomingRequestHandler(
+  private getJsonIncomingRequestValidateFunction<T extends JsonType>(
+    commandName: IncomingRequestCommand,
+    schema: JSONSchemaType<T>,
+  ) {
+    if (this.jsonValidateFunctions.has(commandName) === false) {
+      this.jsonValidateFunctions.set(commandName, this.ajv.compile<T>(schema).bind(this));
+    }
+    return this.jsonValidateFunctions.get(commandName)!;
+  }
+
+  // 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
+    commandPayload: ReqType,
   ): Promise<void>;
 }