Buffer OCPP message when an error occur at sending it
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPRequestService.ts
1 import Ajv, { type JSONSchemaType } from 'ajv';
2 import ajvFormats from 'ajv-formats';
3
4 import OCPPError from '../../exception/OCPPError';
5 import PerformanceStatistics from '../../performance/PerformanceStatistics';
6 import type { EmptyObject } from '../../types/EmptyObject';
7 import type { HandleErrorParams } from '../../types/Error';
8 import type { JsonObject, JsonType } from '../../types/JsonType';
9 import { ErrorType } from '../../types/ocpp/ErrorType';
10 import { MessageType } from '../../types/ocpp/MessageType';
11 import type { OCPPVersion } from '../../types/ocpp/OCPPVersion';
12 import {
13 type ErrorCallback,
14 type IncomingRequestCommand,
15 type OutgoingRequest,
16 RequestCommand,
17 type RequestParams,
18 type ResponseCallback,
19 type ResponseType,
20 } from '../../types/ocpp/Requests';
21 import type { ErrorResponse, Response } from '../../types/ocpp/Responses';
22 import Constants from '../../utils/Constants';
23 import logger from '../../utils/Logger';
24 import Utils from '../../utils/Utils';
25 import type ChargingStation from '../ChargingStation';
26 import type OCPPResponseService from './OCPPResponseService';
27 import { OCPPServiceUtils } from './OCPPServiceUtils';
28
29 const moduleName = 'OCPPRequestService';
30
31 export default abstract class OCPPRequestService {
32 private static instance: OCPPRequestService | null = null;
33 private readonly version: OCPPVersion;
34 private readonly ajv: Ajv;
35 private readonly ocppResponseService: OCPPResponseService;
36 protected abstract jsonSchemas: Map<RequestCommand, JSONSchemaType<JsonObject>>;
37
38 protected constructor(version: OCPPVersion, ocppResponseService: OCPPResponseService) {
39 this.version = version;
40 this.ajv = new Ajv({
41 keywords: ['javaType'],
42 multipleOfPrecision: 2,
43 });
44 ajvFormats(this.ajv);
45 this.ocppResponseService = ocppResponseService;
46 this.requestHandler.bind(this);
47 this.sendMessage.bind(this);
48 this.sendResponse.bind(this);
49 this.sendError.bind(this);
50 this.internalSendMessage.bind(this);
51 this.buildMessageToSend.bind(this);
52 this.validateRequestPayload.bind(this);
53 this.validateIncomingRequestResponsePayload.bind(this);
54 }
55
56 public static getInstance<T extends OCPPRequestService>(
57 this: new (ocppResponseService: OCPPResponseService) => T,
58 ocppResponseService: OCPPResponseService
59 ): T {
60 if (OCPPRequestService.instance === null) {
61 OCPPRequestService.instance = new this(ocppResponseService);
62 }
63 return OCPPRequestService.instance as T;
64 }
65
66 public async sendResponse(
67 chargingStation: ChargingStation,
68 messageId: string,
69 messagePayload: JsonType,
70 commandName: IncomingRequestCommand
71 ): Promise<ResponseType> {
72 try {
73 // Send response message
74 return await this.internalSendMessage(
75 chargingStation,
76 messageId,
77 messagePayload,
78 MessageType.CALL_RESULT_MESSAGE,
79 commandName
80 );
81 } catch (error) {
82 this.handleSendMessageError(chargingStation, commandName, error as Error, {
83 throwError: true,
84 });
85 }
86 }
87
88 public async sendError(
89 chargingStation: ChargingStation,
90 messageId: string,
91 ocppError: OCPPError,
92 commandName: RequestCommand | IncomingRequestCommand
93 ): Promise<ResponseType> {
94 try {
95 // Send error message
96 return await this.internalSendMessage(
97 chargingStation,
98 messageId,
99 ocppError,
100 MessageType.CALL_ERROR_MESSAGE,
101 commandName
102 );
103 } catch (error) {
104 this.handleSendMessageError(chargingStation, commandName, error as Error);
105 }
106 }
107
108 protected async sendMessage(
109 chargingStation: ChargingStation,
110 messageId: string,
111 messagePayload: JsonType,
112 commandName: RequestCommand,
113 params: RequestParams = {
114 skipBufferingOnError: false,
115 triggerMessage: false,
116 }
117 ): Promise<ResponseType> {
118 try {
119 return await this.internalSendMessage(
120 chargingStation,
121 messageId,
122 messagePayload,
123 MessageType.CALL_MESSAGE,
124 commandName,
125 params
126 );
127 } catch (error) {
128 this.handleSendMessageError(chargingStation, commandName, error as Error);
129 }
130 }
131
132 private validateRequestPayload<T extends JsonObject>(
133 chargingStation: ChargingStation,
134 commandName: RequestCommand | IncomingRequestCommand,
135 payload: T
136 ): boolean {
137 if (chargingStation.getPayloadSchemaValidation() === false) {
138 return true;
139 }
140 if (this.jsonSchemas.has(commandName as RequestCommand) === false) {
141 logger.warn(
142 `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: No JSON schema found for command '${commandName}' PDU validation`
143 );
144 return true;
145 }
146 const validate = this.ajv.compile(this.jsonSchemas.get(commandName as RequestCommand));
147 payload = Utils.cloneObject<T>(payload);
148 OCPPServiceUtils.convertDateToISOString<T>(payload);
149 if (validate(payload)) {
150 return true;
151 }
152 logger.error(
153 `${chargingStation.logPrefix()} ${moduleName}.validateRequestPayload: Command '${commandName}' request PDU is invalid: %j`,
154 validate.errors
155 );
156 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
157 throw new OCPPError(
158 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
159 'Request PDU is invalid',
160 commandName,
161 JSON.stringify(validate.errors, null, 2)
162 );
163 }
164
165 private validateIncomingRequestResponsePayload<T extends JsonObject>(
166 chargingStation: ChargingStation,
167 commandName: RequestCommand | IncomingRequestCommand,
168 payload: T
169 ): boolean {
170 if (chargingStation.getPayloadSchemaValidation() === false) {
171 return true;
172 }
173 if (
174 this.ocppResponseService.jsonIncomingRequestResponseSchemas.has(
175 commandName as IncomingRequestCommand
176 ) === false
177 ) {
178 logger.warn(
179 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: No JSON schema found for command '${commandName}' PDU validation`
180 );
181 return true;
182 }
183 const validate = this.ajv.compile(
184 this.ocppResponseService.jsonIncomingRequestResponseSchemas.get(
185 commandName as IncomingRequestCommand
186 )
187 );
188 payload = Utils.cloneObject<T>(payload);
189 OCPPServiceUtils.convertDateToISOString<T>(payload);
190 if (validate(payload)) {
191 return true;
192 }
193 logger.error(
194 `${chargingStation.logPrefix()} ${moduleName}.validateIncomingRequestResponsePayload: Command '${commandName}' reponse PDU is invalid: %j`,
195 validate.errors
196 );
197 // OCPPError usage here is debatable: it's an error in the OCPP stack but not targeted to sendError().
198 throw new OCPPError(
199 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
200 'Response PDU is invalid',
201 commandName,
202 JSON.stringify(validate.errors, null, 2)
203 );
204 }
205
206 private async internalSendMessage(
207 chargingStation: ChargingStation,
208 messageId: string,
209 messagePayload: JsonType | OCPPError,
210 messageType: MessageType,
211 commandName?: RequestCommand | IncomingRequestCommand,
212 params: RequestParams = {
213 skipBufferingOnError: false,
214 triggerMessage: false,
215 }
216 ): Promise<ResponseType> {
217 if (
218 (chargingStation.isInUnknownState() === true &&
219 commandName === RequestCommand.BOOT_NOTIFICATION) ||
220 (chargingStation.getOcppStrictCompliance() === false &&
221 chargingStation.isInUnknownState() === true) ||
222 chargingStation.isInAcceptedState() === true ||
223 (chargingStation.isInPendingState() === true &&
224 (params.triggerMessage === true || messageType === MessageType.CALL_RESULT_MESSAGE))
225 ) {
226 // eslint-disable-next-line @typescript-eslint/no-this-alias
227 const self = this;
228 // Send a message through wsConnection
229 return Utils.promiseWithTimeout(
230 new Promise((resolve, reject) => {
231 const messageToSend = this.buildMessageToSend(
232 chargingStation,
233 messageId,
234 messagePayload,
235 messageType,
236 commandName,
237 responseCallback,
238 errorCallback
239 );
240 if (chargingStation.getEnableStatistics() === true) {
241 chargingStation.performanceStatistics.addRequestStatistic(commandName, messageType);
242 }
243 let sendError = false;
244 // Check if wsConnection opened
245 if (chargingStation.isWebSocketConnectionOpened() === true) {
246 const beginId = PerformanceStatistics.beginMeasure(commandName as string);
247 try {
248 chargingStation.wsConnection.send(messageToSend);
249 } catch (error) {
250 sendError = true;
251 }
252 PerformanceStatistics.endMeasure(commandName as string, beginId);
253 logger.debug(
254 `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${this.getMessageTypeString(
255 messageType
256 )} payload: ${messageToSend}`
257 );
258 }
259 const wsClosedOrErrored =
260 chargingStation.isWebSocketConnectionOpened() === false || sendError === true;
261 if (wsClosedOrErrored && params.skipBufferingOnError === false) {
262 // Buffer
263 chargingStation.bufferMessage(messageToSend);
264 // Reject and keep request in the cache
265 return reject(
266 new OCPPError(
267 ErrorType.GENERIC_ERROR,
268 `WebSocket closed or errored for buffered message id '${messageId}' with content '${messageToSend}'`,
269 commandName,
270 (messagePayload as JsonObject)?.details ?? {}
271 )
272 );
273 } else if (wsClosedOrErrored) {
274 const ocppError = new OCPPError(
275 ErrorType.GENERIC_ERROR,
276 `WebSocket closed or errored for non buffered message id '${messageId}' with content '${messageToSend}'`,
277 commandName,
278 (messagePayload as JsonObject)?.details ?? {}
279 );
280 // Reject response
281 if (messageType !== MessageType.CALL_MESSAGE) {
282 return reject(ocppError);
283 }
284 // Reject and remove request from the cache
285 return errorCallback(ocppError, false);
286 }
287 // Resolve response
288 if (messageType !== MessageType.CALL_MESSAGE) {
289 return resolve(messagePayload);
290 }
291
292 /**
293 * Function that will receive the request's response
294 *
295 * @param payload -
296 * @param requestPayload -
297 */
298 function responseCallback(payload: JsonType, requestPayload: JsonType): void {
299 if (chargingStation.getEnableStatistics() === true) {
300 chargingStation.performanceStatistics.addRequestStatistic(
301 commandName,
302 MessageType.CALL_RESULT_MESSAGE
303 );
304 }
305 // Handle the request's response
306 self.ocppResponseService
307 .responseHandler(
308 chargingStation,
309 commandName as RequestCommand,
310 payload,
311 requestPayload
312 )
313 .then(() => {
314 resolve(payload);
315 })
316 .catch((error) => {
317 reject(error);
318 })
319 .finally(() => {
320 chargingStation.requests.delete(messageId);
321 });
322 }
323
324 /**
325 * Function that will receive the request's error response
326 *
327 * @param error -
328 * @param requestStatistic -
329 */
330 function errorCallback(error: OCPPError, requestStatistic = true): void {
331 if (requestStatistic === true && chargingStation.getEnableStatistics() === true) {
332 chargingStation.performanceStatistics.addRequestStatistic(
333 commandName,
334 MessageType.CALL_ERROR_MESSAGE
335 );
336 }
337 logger.error(
338 `${chargingStation.logPrefix()} Error occurred at ${self.getMessageTypeString(
339 messageType
340 )} command ${commandName} with PDU %j:`,
341 messagePayload,
342 error
343 );
344 chargingStation.requests.delete(messageId);
345 reject(error);
346 }
347 }),
348 Constants.OCPP_WEBSOCKET_TIMEOUT,
349 new OCPPError(
350 ErrorType.GENERIC_ERROR,
351 `Timeout for message id '${messageId}'`,
352 commandName,
353 (messagePayload as JsonObject)?.details ?? {}
354 ),
355 () => {
356 messageType === MessageType.CALL_MESSAGE && chargingStation.requests.delete(messageId);
357 }
358 );
359 }
360 throw new OCPPError(
361 ErrorType.SECURITY_ERROR,
362 `Cannot send command ${commandName} PDU when the charging station is in ${chargingStation.getRegistrationStatus()} state on the central server`,
363 commandName
364 );
365 }
366
367 private buildMessageToSend(
368 chargingStation: ChargingStation,
369 messageId: string,
370 messagePayload: JsonType | OCPPError,
371 messageType: MessageType,
372 commandName?: RequestCommand | IncomingRequestCommand,
373 responseCallback?: ResponseCallback,
374 errorCallback?: ErrorCallback
375 ): string {
376 let messageToSend: string;
377 // Type of message
378 switch (messageType) {
379 // Request
380 case MessageType.CALL_MESSAGE:
381 // Build request
382 chargingStation.requests.set(messageId, [
383 responseCallback,
384 errorCallback,
385 commandName,
386 messagePayload as JsonType,
387 ]);
388 this.validateRequestPayload(chargingStation, commandName, messagePayload as JsonObject);
389 messageToSend = JSON.stringify([
390 messageType,
391 messageId,
392 commandName,
393 messagePayload,
394 ] as OutgoingRequest);
395 break;
396 // Response
397 case MessageType.CALL_RESULT_MESSAGE:
398 // Build response
399 this.validateIncomingRequestResponsePayload(
400 chargingStation,
401 commandName,
402 messagePayload as JsonObject
403 );
404 messageToSend = JSON.stringify([messageType, messageId, messagePayload] as Response);
405 break;
406 // Error Message
407 case MessageType.CALL_ERROR_MESSAGE:
408 // Build Error Message
409 messageToSend = JSON.stringify([
410 messageType,
411 messageId,
412 (messagePayload as OCPPError)?.code ?? ErrorType.GENERIC_ERROR,
413 (messagePayload as OCPPError)?.message ?? '',
414 (messagePayload as OCPPError)?.details ?? { commandName },
415 ] as ErrorResponse);
416 break;
417 }
418 return messageToSend;
419 }
420
421 private getMessageTypeString(messageType: MessageType): string {
422 switch (messageType) {
423 case MessageType.CALL_MESSAGE:
424 return 'request';
425 case MessageType.CALL_RESULT_MESSAGE:
426 return 'response';
427 case MessageType.CALL_ERROR_MESSAGE:
428 return 'error';
429 }
430 }
431
432 private handleSendMessageError(
433 chargingStation: ChargingStation,
434 commandName: RequestCommand | IncomingRequestCommand,
435 error: Error,
436 params: HandleErrorParams<EmptyObject> = { throwError: false }
437 ): void {
438 logger.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error);
439 if (params?.throwError === true) {
440 throw error;
441 }
442 }
443
444 // eslint-disable-next-line @typescript-eslint/no-unused-vars
445 public abstract requestHandler<ReqType extends JsonType, ResType extends JsonType>(
446 chargingStation: ChargingStation,
447 commandName: RequestCommand,
448 commandParams?: JsonType,
449 params?: RequestParams
450 ): Promise<ResType>;
451 }