perf: cache only JSON payload validation functions
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 2.0 / OCPP20IncomingRequestService.ts
1 // Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
2
3 import type { ValidateFunction } from 'ajv'
4
5 import { OCPP20ServiceUtils } from './OCPP20ServiceUtils.js'
6 import type { ChargingStation } from '../../../charging-station/index.js'
7 import { OCPPError } from '../../../exception/index.js'
8 import {
9 ErrorType,
10 type IncomingRequestHandler,
11 type JsonType,
12 type OCPP20ClearCacheRequest,
13 OCPP20IncomingRequestCommand,
14 OCPPVersion
15 } from '../../../types/index.js'
16 import { logger } from '../../../utils/index.js'
17 import { OCPPIncomingRequestService } from '../OCPPIncomingRequestService.js'
18
19 const moduleName = 'OCPP20IncomingRequestService'
20
21 export class OCPP20IncomingRequestService extends OCPPIncomingRequestService {
22 protected jsonSchemasValidateFunction: Map<
23 OCPP20IncomingRequestCommand,
24 ValidateFunction<JsonType>
25 >
26
27 private readonly incomingRequestHandlers: Map<
28 OCPP20IncomingRequestCommand,
29 IncomingRequestHandler
30 >
31
32 public constructor () {
33 // if (new.target.name === moduleName) {
34 // throw new TypeError(`Cannot construct ${new.target.name} instances directly`)
35 // }
36 super(OCPPVersion.VERSION_20)
37 this.incomingRequestHandlers = new Map<OCPP20IncomingRequestCommand, IncomingRequestHandler>([
38 [OCPP20IncomingRequestCommand.CLEAR_CACHE, this.handleRequestClearCache.bind(this)]
39 ])
40 this.jsonSchemasValidateFunction = new Map<
41 OCPP20IncomingRequestCommand,
42 ValidateFunction<JsonType>
43 >([
44 [
45 OCPP20IncomingRequestCommand.CLEAR_CACHE,
46 this.ajv
47 .compile(
48 OCPP20ServiceUtils.parseJsonSchemaFile<OCPP20ClearCacheRequest>(
49 'assets/json-schemas/ocpp/2.0/ClearCacheRequest.json',
50 moduleName,
51 'constructor'
52 )
53 )
54 .bind(this)
55 ]
56 ])
57 this.validatePayload = this.validatePayload.bind(this)
58 }
59
60 public async incomingRequestHandler<ReqType extends JsonType, ResType extends JsonType>(
61 chargingStation: ChargingStation,
62 messageId: string,
63 commandName: OCPP20IncomingRequestCommand,
64 commandPayload: ReqType
65 ): Promise<void> {
66 let response: ResType
67 if (
68 chargingStation.stationInfo?.ocppStrictCompliance === true &&
69 chargingStation.inPendingState() &&
70 (commandName === OCPP20IncomingRequestCommand.REQUEST_START_TRANSACTION ||
71 commandName === OCPP20IncomingRequestCommand.REQUEST_STOP_TRANSACTION)
72 ) {
73 throw new OCPPError(
74 ErrorType.SECURITY_ERROR,
75 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
76 commandPayload,
77 undefined,
78 2
79 )} while the charging station is in pending state on the central server`,
80 commandName,
81 commandPayload
82 )
83 }
84 if (
85 chargingStation.isRegistered() ||
86 (chargingStation.stationInfo?.ocppStrictCompliance === false &&
87 chargingStation.inUnknownState())
88 ) {
89 if (
90 this.incomingRequestHandlers.has(commandName) &&
91 OCPP20ServiceUtils.isIncomingRequestCommandSupported(chargingStation, commandName)
92 ) {
93 try {
94 this.validatePayload(chargingStation, commandName, commandPayload)
95 // Call the method to build the response
96 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
97 response = (await this.incomingRequestHandlers.get(commandName)!(
98 chargingStation,
99 commandPayload
100 )) as ResType
101 } catch (error) {
102 // Log
103 logger.error(
104 `${chargingStation.logPrefix()} ${moduleName}.incomingRequestHandler: Handle incoming request error:`,
105 error
106 )
107 throw error
108 }
109 } else {
110 // Throw exception
111 throw new OCPPError(
112 ErrorType.NOT_IMPLEMENTED,
113 `${commandName} is not implemented to handle request PDU ${JSON.stringify(
114 commandPayload,
115 undefined,
116 2
117 )}`,
118 commandName,
119 commandPayload
120 )
121 }
122 } else {
123 throw new OCPPError(
124 ErrorType.SECURITY_ERROR,
125 `${commandName} cannot be issued to handle request PDU ${JSON.stringify(
126 commandPayload,
127 undefined,
128 2
129 )} while the charging station is not registered on the central server.`,
130 commandName,
131 commandPayload
132 )
133 }
134 // Send the built response
135 await chargingStation.ocppRequestService.sendResponse(
136 chargingStation,
137 messageId,
138 response,
139 commandName
140 )
141 }
142
143 private validatePayload (
144 chargingStation: ChargingStation,
145 commandName: OCPP20IncomingRequestCommand,
146 commandPayload: JsonType
147 ): boolean {
148 if (this.jsonSchemasValidateFunction.has(commandName)) {
149 return this.validateIncomingRequestPayload(chargingStation, commandName, commandPayload)
150 }
151 logger.warn(
152 `${chargingStation.logPrefix()} ${moduleName}.validatePayload: No JSON schema validation function found for command '${commandName}' PDU validation`
153 )
154 return false
155 }
156 }