Incoming requests payload validation with JSON schemas (#135)
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPRequestService.ts
1 import OCPPError from '../../exception/OCPPError';
2 import PerformanceStatistics from '../../performance/PerformanceStatistics';
3 import { EmptyObject } from '../../types/EmptyObject';
4 import { HandleErrorParams } from '../../types/Error';
5 import { JsonObject, JsonType } from '../../types/JsonType';
6 import { ErrorType } from '../../types/ocpp/ErrorType';
7 import { MessageType } from '../../types/ocpp/MessageType';
8 import {
9 IncomingRequestCommand,
10 OutgoingRequest,
11 RequestCommand,
12 RequestParams,
13 ResponseType,
14 } from '../../types/ocpp/Requests';
15 import { ErrorResponse, Response } from '../../types/ocpp/Responses';
16 import Constants from '../../utils/Constants';
17 import logger from '../../utils/Logger';
18 import Utils from '../../utils/Utils';
19 import type ChargingStation from '../ChargingStation';
20 import type OCPPResponseService from './OCPPResponseService';
21
22 const moduleName = 'OCPPRequestService';
23
24 export default abstract class OCPPRequestService {
25 private static instance: OCPPRequestService | null = null;
26
27 private readonly ocppResponseService: OCPPResponseService;
28
29 protected constructor(ocppResponseService: OCPPResponseService) {
30 this.ocppResponseService = ocppResponseService;
31 this.requestHandler.bind(this);
32 this.sendResponse.bind(this);
33 this.sendError.bind(this);
34 }
35
36 public static getInstance<T extends OCPPRequestService>(
37 this: new (ocppResponseService: OCPPResponseService) => T,
38 ocppResponseService: OCPPResponseService
39 ): T {
40 if (!OCPPRequestService.instance) {
41 OCPPRequestService.instance = new this(ocppResponseService);
42 }
43 return OCPPRequestService.instance as T;
44 }
45
46 public async sendResponse(
47 chargingStation: ChargingStation,
48 messageId: string,
49 messagePayload: JsonType,
50 commandName: IncomingRequestCommand
51 ): Promise<ResponseType> {
52 try {
53 // Send response message
54 return await this.internalSendMessage(
55 chargingStation,
56 messageId,
57 messagePayload,
58 MessageType.CALL_RESULT_MESSAGE,
59 commandName
60 );
61 } catch (error) {
62 this.handleRequestError(chargingStation, commandName, error as Error);
63 }
64 }
65
66 public async sendError(
67 chargingStation: ChargingStation,
68 messageId: string,
69 ocppError: OCPPError,
70 commandName: RequestCommand | IncomingRequestCommand
71 ): Promise<ResponseType> {
72 try {
73 // Send error message
74 return await this.internalSendMessage(
75 chargingStation,
76 messageId,
77 ocppError,
78 MessageType.CALL_ERROR_MESSAGE,
79 commandName
80 );
81 } catch (error) {
82 this.handleRequestError(chargingStation, commandName, error as Error);
83 }
84 }
85
86 protected async sendMessage(
87 chargingStation: ChargingStation,
88 messageId: string,
89 messagePayload: JsonType,
90 commandName: RequestCommand,
91 params: RequestParams = {
92 skipBufferingOnError: false,
93 triggerMessage: false,
94 }
95 ): Promise<ResponseType> {
96 try {
97 return await this.internalSendMessage(
98 chargingStation,
99 messageId,
100 messagePayload,
101 MessageType.CALL_MESSAGE,
102 commandName,
103 params
104 );
105 } catch (error) {
106 this.handleRequestError(chargingStation, commandName, error as Error, { throwError: false });
107 }
108 }
109
110 private async internalSendMessage(
111 chargingStation: ChargingStation,
112 messageId: string,
113 messagePayload: JsonType | OCPPError,
114 messageType: MessageType,
115 commandName?: RequestCommand | IncomingRequestCommand,
116 params: RequestParams = {
117 skipBufferingOnError: false,
118 triggerMessage: false,
119 }
120 ): Promise<ResponseType> {
121 if (
122 (chargingStation.isInUnknownState() && commandName === RequestCommand.BOOT_NOTIFICATION) ||
123 (!chargingStation.getOcppStrictCompliance() && chargingStation.isInUnknownState()) ||
124 chargingStation.isInAcceptedState() ||
125 (chargingStation.isInPendingState() &&
126 (params.triggerMessage || messageType === MessageType.CALL_RESULT_MESSAGE))
127 ) {
128 // eslint-disable-next-line @typescript-eslint/no-this-alias
129 const self = this;
130 // Send a message through wsConnection
131 return Utils.promiseWithTimeout(
132 new Promise((resolve, reject) => {
133 const messageToSend = this.buildMessageToSend(
134 chargingStation,
135 messageId,
136 messagePayload,
137 messageType,
138 commandName,
139 responseCallback,
140 errorCallback
141 );
142 if (chargingStation.getEnableStatistics()) {
143 chargingStation.performanceStatistics.addRequestStatistic(commandName, messageType);
144 }
145 // Check if wsConnection opened
146 if (chargingStation.isWebSocketConnectionOpened()) {
147 // Yes: Send Message
148 const beginId = PerformanceStatistics.beginMeasure(commandName);
149 // FIXME: Handle sending error
150 chargingStation.wsConnection.send(messageToSend);
151 PerformanceStatistics.endMeasure(commandName, beginId);
152 logger.debug(
153 `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString(
154 messageType
155 )} payload: ${messageToSend}`
156 );
157 } else if (!params.skipBufferingOnError) {
158 // Buffer it
159 chargingStation.bufferMessage(messageToSend);
160 const ocppError = new OCPPError(
161 ErrorType.GENERIC_ERROR,
162 `WebSocket closed for buffered message id '${messageId}' with content '${messageToSend}'`,
163 commandName,
164 (messagePayload as JsonObject)?.details ?? {}
165 );
166 if (messageType === MessageType.CALL_MESSAGE) {
167 // Reject it but keep the request in the cache
168 return reject(ocppError);
169 }
170 return errorCallback(ocppError, false);
171 } else {
172 // Reject it
173 return errorCallback(
174 new OCPPError(
175 ErrorType.GENERIC_ERROR,
176 `WebSocket closed for non buffered message id '${messageId}' with content '${messageToSend}'`,
177 commandName,
178 (messagePayload as JsonObject)?.details ?? {}
179 ),
180 false
181 );
182 }
183 // Response?
184 if (messageType !== MessageType.CALL_MESSAGE) {
185 // Yes: send Ok
186 return resolve(messagePayload);
187 }
188
189 /**
190 * Function that will receive the request's response
191 *
192 * @param payload
193 * @param requestPayload
194 */
195 async function responseCallback(
196 payload: JsonType,
197 requestPayload: JsonType
198 ): Promise<void> {
199 if (chargingStation.getEnableStatistics()) {
200 chargingStation.performanceStatistics.addRequestStatistic(
201 commandName,
202 MessageType.CALL_RESULT_MESSAGE
203 );
204 }
205 // Handle the request's response
206 try {
207 await self.ocppResponseService.responseHandler(
208 chargingStation,
209 commandName as RequestCommand,
210 payload,
211 requestPayload
212 );
213 resolve(payload);
214 } catch (error) {
215 reject(error);
216 } finally {
217 chargingStation.requests.delete(messageId);
218 }
219 }
220
221 /**
222 * Function that will receive the request's error response
223 *
224 * @param error
225 * @param requestStatistic
226 */
227 function errorCallback(error: OCPPError, requestStatistic = true): void {
228 if (requestStatistic && chargingStation.getEnableStatistics()) {
229 chargingStation.performanceStatistics.addRequestStatistic(
230 commandName,
231 MessageType.CALL_ERROR_MESSAGE
232 );
233 }
234 logger.error(
235 `${chargingStation.logPrefix()} Error %j occurred when calling command %s with message data %j`,
236 error,
237 commandName,
238 messagePayload
239 );
240 chargingStation.requests.delete(messageId);
241 reject(error);
242 }
243 }),
244 Constants.OCPP_WEBSOCKET_TIMEOUT,
245 new OCPPError(
246 ErrorType.GENERIC_ERROR,
247 `Timeout for message id '${messageId}'`,
248 commandName,
249 (messagePayload as JsonObject)?.details ?? {}
250 ),
251 () => {
252 messageType === MessageType.CALL_MESSAGE && chargingStation.requests.delete(messageId);
253 }
254 );
255 }
256 throw new OCPPError(
257 ErrorType.SECURITY_ERROR,
258 `Cannot send command ${commandName} PDU when the charging station is in ${chargingStation.getRegistrationStatus()} state on the central server`,
259 commandName
260 );
261 }
262
263 private buildMessageToSend(
264 chargingStation: ChargingStation,
265 messageId: string,
266 messagePayload: JsonType | OCPPError,
267 messageType: MessageType,
268 commandName?: RequestCommand | IncomingRequestCommand,
269 responseCallback?: (payload: JsonType, requestPayload: JsonType) => Promise<void>,
270 errorCallback?: (error: OCPPError, requestStatistic?: boolean) => void
271 ): string {
272 let messageToSend: string;
273 // Type of message
274 switch (messageType) {
275 // Request
276 case MessageType.CALL_MESSAGE:
277 // Build request
278 chargingStation.requests.set(messageId, [
279 responseCallback,
280 errorCallback,
281 commandName,
282 messagePayload as JsonType,
283 ]);
284 messageToSend = JSON.stringify([
285 messageType,
286 messageId,
287 commandName,
288 messagePayload,
289 ] as OutgoingRequest);
290 break;
291 // Response
292 case MessageType.CALL_RESULT_MESSAGE:
293 // Build response
294 messageToSend = JSON.stringify([messageType, messageId, messagePayload] as Response);
295 break;
296 // Error Message
297 case MessageType.CALL_ERROR_MESSAGE:
298 // Build Error Message
299 messageToSend = JSON.stringify([
300 messageType,
301 messageId,
302 (messagePayload as OCPPError)?.code ?? ErrorType.GENERIC_ERROR,
303 (messagePayload as OCPPError)?.message ?? '',
304 (messagePayload as OCPPError)?.details ?? { commandName },
305 ] as ErrorResponse);
306 break;
307 }
308 return messageToSend;
309 }
310
311 private getMessageTypeString(messageType: MessageType): string {
312 switch (messageType) {
313 case MessageType.CALL_MESSAGE:
314 return 'request';
315 case MessageType.CALL_RESULT_MESSAGE:
316 return 'response';
317 case MessageType.CALL_ERROR_MESSAGE:
318 return 'error';
319 }
320 }
321
322 private handleRequestError(
323 chargingStation: ChargingStation,
324 commandName: RequestCommand | IncomingRequestCommand,
325 error: Error,
326 params: HandleErrorParams<EmptyObject> = { throwError: true }
327 ): void {
328 logger.error(chargingStation.logPrefix() + ' Request command %s error: %j', commandName, error);
329 if (params?.throwError) {
330 throw error;
331 }
332 }
333
334 // eslint-disable-next-line @typescript-eslint/no-unused-vars
335 public abstract requestHandler<Request extends JsonType, Response extends JsonType>(
336 chargingStation: ChargingStation,
337 commandName: RequestCommand,
338 commandParams?: JsonType,
339 params?: RequestParams
340 ): Promise<Response>;
341 }