feat!: handle Set at JSON serialization to string
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / UIWebSocketServer.ts
index 42162d16556c47cec0c0b7805f77fc36d3ac7f99..bf0a6c444749201fe06d2cdcc6f24b10fa09582a 100644 (file)
@@ -4,9 +4,8 @@ import type { Duplex } from 'node:stream'
 import { StatusCodes } from 'http-status-codes'
 import { type RawData, WebSocket, WebSocketServer } from 'ws'
 
-import { AbstractUIServer } from './AbstractUIServer.js'
-import { UIServerUtils } from './UIServerUtils.js'
 import {
+  MapStringifyFormat,
   type ProtocolRequest,
   type ProtocolResponse,
   type UIServerConfiguration,
@@ -16,10 +15,17 @@ import {
   Constants,
   getWebSocketCloseEventStatusString,
   isNotEmptyString,
-  logPrefix,
+  JSONStringify,
   logger,
+  logPrefix,
   validateUUID
 } from '../../utils/index.js'
+import { AbstractUIServer } from './AbstractUIServer.js'
+import {
+  getProtocolAndVersion,
+  handleProtocols,
+  isProtocolAndVersionSupported
+} from './UIServerUtils.js'
 
 const moduleName = 'UIWebSocketServer'
 
@@ -29,14 +35,14 @@ export class UIWebSocketServer extends AbstractUIServer {
   public constructor (protected readonly uiServerConfiguration: UIServerConfiguration) {
     super(uiServerConfiguration)
     this.webSocketServer = new WebSocketServer({
-      handleProtocols: UIServerUtils.handleProtocols,
+      handleProtocols,
       noServer: true
     })
   }
 
   public start (): void {
     this.webSocketServer.on('connection', (ws: WebSocket, _req: IncomingMessage): void => {
-      if (!UIServerUtils.isProtocolAndVersionSupported(ws.protocol)) {
+      if (!isProtocolAndVersionSupported(ws.protocol)) {
         logger.error(
           `${this.logPrefix(
             moduleName,
@@ -45,7 +51,7 @@ export class UIWebSocketServer extends AbstractUIServer {
         )
         ws.close(WebSocketCloseEventStatusCode.CLOSE_PROTOCOL_ERROR)
       }
-      const [, version] = UIServerUtils.getProtocolAndVersion(ws.protocol)
+      const [, version] = getProtocolAndVersion(ws.protocol)
       this.registerProtocolVersionUIService(version)
       ws.on('message', rawData => {
         const request = this.validateRawDataRequest(rawData)
@@ -86,6 +92,16 @@ export class UIWebSocketServer extends AbstractUIServer {
       }
     })
     this.httpServer.on('upgrade', (req: IncomingMessage, socket: Duplex, head: Buffer): void => {
+      const onSocketError = (error: Error): void => {
+        logger.error(
+          `${this.logPrefix(
+            moduleName,
+            'start.httpServer.on.upgrade'
+          )} Socket error at connection upgrade event handling:`,
+          error
+        )
+      }
+      socket.on('error', onSocketError)
       this.authenticate(req, err => {
         if (err != null) {
           socket.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`)
@@ -101,11 +117,12 @@ export class UIWebSocketServer extends AbstractUIServer {
             `${this.logPrefix(
               moduleName,
               'start.httpServer.on.upgrade'
-            )} Error at handling connection upgrade:`,
+            )} Error at connection upgrade event handling:`,
             error
           )
         }
       })
+      socket.removeListener('error', onSocketError)
     })
     this.startHttpServer()
   }
@@ -120,7 +137,7 @@ export class UIWebSocketServer extends AbstractUIServer {
       if (this.hasResponseHandler(responseId)) {
         const ws = this.responseHandlers.get(responseId) as WebSocket
         if (ws.readyState === WebSocket.OPEN) {
-          ws.send(JSON.stringify(response))
+          ws.send(JSONStringify(response, undefined, MapStringifyFormat.object))
         } else {
           logger.error(
             `${this.logPrefix(
@@ -179,8 +196,20 @@ export class UIWebSocketServer extends AbstractUIServer {
     //   )} Raw data received in string format: ${rawData.toString()}`
     // )
 
-    // eslint-disable-next-line @typescript-eslint/no-base-to-string
-    const request = JSON.parse(rawData.toString()) as ProtocolRequest
+    let request: ProtocolRequest
+    try {
+      // eslint-disable-next-line @typescript-eslint/no-base-to-string
+      request = JSON.parse(rawData.toString()) as ProtocolRequest
+    } catch (error) {
+      logger.error(
+        `${this.logPrefix(
+          moduleName,
+          'validateRawDataRequest'
+          // eslint-disable-next-line @typescript-eslint/no-base-to-string
+        )} UI protocol request is not valid JSON: ${rawData.toString()}`
+      )
+      return false
+    }
 
     if (!Array.isArray(request)) {
       logger.error(