refactor: cleanup eslint configuration
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPIncomingRequestService.ts
index 06ccd312c0e970022c844f200fe3d0b631ef8c93..7c88547a6c63ce285e2009e6561b9d813fc99b53 100644 (file)
-import { AsyncResource } from 'async_hooks';
+import { EventEmitter } from 'node:events'
 
-import type { JSONSchemaType } from 'ajv';
-import Ajv from 'ajv-draft-04';
-import ajvFormats from 'ajv-formats';
+import _Ajv, { type ValidateFunction } from 'ajv'
+import _ajvFormats from 'ajv-formats'
 
-import OCPPError from '../../exception/OCPPError';
-import type { HandleErrorParams } from '../../types/Error';
-import type { JsonType } from '../../types/JsonType';
-import type { IncomingRequestCommand } from '../../types/ocpp/Requests';
-import logger from '../../utils/Logger';
-import type ChargingStation from '../ChargingStation';
-import { OCPPServiceUtils } from './OCPPServiceUtils';
+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'
+import { OCPPConstants } from './OCPPConstants.js'
+import { OCPPServiceUtils } from './OCPPServiceUtils.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;
-  protected asyncResource: AsyncResource;
-  private ajv: Ajv;
+export abstract class OCPPIncomingRequestService extends EventEmitter {
+  private static instance: OCPPIncomingRequestService | null = null
+  private readonly version: OCPPVersion
+  protected readonly ajv: Ajv
+  protected abstract payloadValidateFunctions: Map<
+  IncomingRequestCommand,
+  ValidateFunction<JsonType>
+  >
 
-  protected constructor() {
-    this.asyncResource = new AsyncResource(moduleName);
-    this.ajv = new Ajv();
-    ajvFormats(this.ajv);
-    this.incomingRequestHandler.bind(this);
-    this.validateIncomingRequestPayload.bind(this);
+  protected constructor (version: OCPPVersion) {
+    super()
+    this.version = version
+    this.ajv = new Ajv({
+      keywords: ['javaType'],
+      multipleOfPrecision: 2
+    })
+    ajvFormats(this.ajv)
+    this.incomingRequestHandler = this.incomingRequestHandler.bind(this)
+    this.validateIncomingRequestPayload = this.validateIncomingRequestPayload.bind(this)
   }
 
   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 '${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
     }
   }
 
   protected validateIncomingRequestPayload<T extends JsonType>(
     chargingStation: ChargingStation,
     commandName: IncomingRequestCommand,
-    schema: JSONSchemaType<T>,
     payload: T
   ): boolean {
-    if (chargingStation.getPayloadSchemaValidation() === false) {
-      return true;
+    if (chargingStation.stationInfo?.ocppStrictCompliance === false) {
+      return true
     }
-    const validate = this.ajv.compile(schema);
-    if (validate(payload)) {
-      return true;
+    const validate = this.payloadValidateFunctions.get(commandName)
+    if (validate?.(payload) === true) {
+      return true
     }
     logger.error(
-      `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestPayload: Incoming request PDU is invalid: %j`,
-      validate.errors
-    );
+      `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestPayload: Command '${commandName}' incoming request PDU is invalid: %j`,
+      validate?.errors
+    )
     throw new OCPPError(
-      OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
+      OCPPServiceUtils.ajvErrorsToErrorType(validate?.errors),
       'Incoming request PDU is invalid',
       commandName,
-      JSON.stringify(validate.errors, null, 2)
-    );
+      JSON.stringify(validate?.errors, undefined, 2)
+    )
   }
 
-  public abstract incomingRequestHandler(
+  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
+  }
+
+  // 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>
 }