62e58661054f973028b9fae1f1713cac5a99db27
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPIncomingRequestService.ts
1 import _Ajv, { type JSONSchemaType, type ValidateFunction } from 'ajv'
2 import _ajvFormats from 'ajv-formats'
3
4 import { OCPPConstants } from './OCPPConstants.js'
5 import { OCPPServiceUtils } from './OCPPServiceUtils.js'
6 import { type ChargingStation, getIdTagsFile } from '../../charging-station/index.js'
7 import { OCPPError } from '../../exception/index.js'
8 import type {
9 ClearCacheResponse,
10 HandleErrorParams,
11 IncomingRequestCommand,
12 JsonType,
13 OCPPVersion
14 } from '../../types/index.js'
15 import { logger, setDefaultErrorParams } from '../../utils/index.js'
16 type Ajv = _Ajv.default
17 // eslint-disable-next-line @typescript-eslint/no-redeclare
18 const Ajv = _Ajv.default
19 const ajvFormats = _ajvFormats.default
20
21 const moduleName = 'OCPPIncomingRequestService'
22
23 export abstract class OCPPIncomingRequestService {
24 private static instance: OCPPIncomingRequestService | null = null
25 private readonly version: OCPPVersion
26 private readonly ajv: Ajv
27 private readonly jsonValidateFunctions: Map<IncomingRequestCommand, ValidateFunction<JsonType>>
28 protected abstract jsonSchemas: Map<IncomingRequestCommand, JSONSchemaType<JsonType>>
29
30 protected constructor (version: OCPPVersion) {
31 this.version = version
32 this.ajv = new Ajv({
33 keywords: ['javaType'],
34 multipleOfPrecision: 2
35 })
36 ajvFormats(this.ajv)
37 this.jsonValidateFunctions = new Map<IncomingRequestCommand, ValidateFunction<JsonType>>()
38 this.incomingRequestHandler = this.incomingRequestHandler.bind(this) as <
39 ReqType extends JsonType,
40 // eslint-disable-next-line @typescript-eslint/no-unused-vars
41 ResType extends JsonType,
42 >(
43 chargingStation: ChargingStation,
44 messageId: string,
45 commandName: IncomingRequestCommand,
46 commandPayload: ReqType
47 ) => Promise<void>
48 this.validateIncomingRequestPayload = this.validateIncomingRequestPayload.bind(this) as <
49 T extends JsonType,
50 >(
51 chargingStation: ChargingStation,
52 commandName: IncomingRequestCommand,
53 schema: JSONSchemaType<T>,
54 payload: T
55 ) => boolean
56 }
57
58 public static getInstance<T extends OCPPIncomingRequestService>(this: new () => T): T {
59 if (OCPPIncomingRequestService.instance === null) {
60 OCPPIncomingRequestService.instance = new this()
61 }
62 return OCPPIncomingRequestService.instance as T
63 }
64
65 protected handleIncomingRequestError<T extends JsonType>(
66 chargingStation: ChargingStation,
67 commandName: IncomingRequestCommand,
68 error: Error,
69 params: HandleErrorParams<T> = { throwError: true, consoleOut: false }
70 ): T | undefined {
71 setDefaultErrorParams(params)
72 logger.error(
73 `${chargingStation.logPrefix()} ${moduleName}.handleIncomingRequestError: Incoming request command '${commandName}' error:`,
74 error
75 )
76 if (params?.throwError === false && params?.errorResponse != null) {
77 return params?.errorResponse
78 }
79 if (params?.throwError === true && params?.errorResponse == null) {
80 throw error
81 }
82 if (params?.throwError === true && params?.errorResponse != null) {
83 return params?.errorResponse
84 }
85 }
86
87 protected validateIncomingRequestPayload<T extends JsonType>(
88 chargingStation: ChargingStation,
89 commandName: IncomingRequestCommand,
90 schema: JSONSchemaType<T>,
91 payload: T
92 ): boolean {
93 if (chargingStation.stationInfo?.ocppStrictCompliance === false) {
94 return true
95 }
96 const validate = this.getJsonIncomingRequestValidateFunction<T>(commandName, schema)
97 if (validate(payload)) {
98 return true
99 }
100 logger.error(
101 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestPayload: Command '${commandName}' incoming request PDU is invalid: %j`,
102 validate.errors
103 )
104 throw new OCPPError(
105 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
106 'Incoming request PDU is invalid',
107 commandName,
108 JSON.stringify(validate.errors, undefined, 2)
109 )
110 }
111
112 protected handleRequestClearCache (chargingStation: ChargingStation): ClearCacheResponse {
113 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
114 if (chargingStation.idTagsCache.deleteIdTags(getIdTagsFile(chargingStation.stationInfo)!)) {
115 return OCPPConstants.OCPP_RESPONSE_ACCEPTED
116 }
117 return OCPPConstants.OCPP_RESPONSE_REJECTED
118 }
119
120 private getJsonIncomingRequestValidateFunction<T extends JsonType>(
121 commandName: IncomingRequestCommand,
122 schema: JSONSchemaType<T>
123 ): ValidateFunction<JsonType> {
124 if (!this.jsonValidateFunctions.has(commandName)) {
125 this.jsonValidateFunctions.set(commandName, this.ajv.compile<T>(schema).bind(this))
126 }
127 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
128 return this.jsonValidateFunctions.get(commandName)!
129 }
130
131 // eslint-disable-next-line @typescript-eslint/no-unused-vars
132 public abstract incomingRequestHandler<ReqType extends JsonType, ResType extends JsonType>(
133 chargingStation: ChargingStation,
134 messageId: string,
135 commandName: IncomingRequestCommand,
136 commandPayload: ReqType
137 ): Promise<void>
138 }