16477146f0c638fbd1776213df0d336e3fa9f62d
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / UIWebSocketServer.ts
1 import type { IncomingMessage } from 'node:http'
2 import type { Duplex } from 'node:stream'
3
4 import { StatusCodes } from 'http-status-codes'
5 import { type RawData, WebSocket, WebSocketServer } from 'ws'
6
7 import { AbstractUIServer } from './AbstractUIServer.js'
8 import { UIServerUtils } from './UIServerUtils.js'
9 import {
10 type ProtocolRequest,
11 type ProtocolResponse,
12 type UIServerConfiguration,
13 WebSocketCloseEventStatusCode
14 } from '../../types/index.js'
15 import {
16 Constants,
17 JSONStringifyWithMapSupport,
18 getWebSocketCloseEventStatusString,
19 isNotEmptyString,
20 logPrefix,
21 logger,
22 validateUUID
23 } from '../../utils/index.js'
24
25 const moduleName = 'UIWebSocketServer'
26
27 export class UIWebSocketServer extends AbstractUIServer {
28 private readonly webSocketServer: WebSocketServer
29
30 public constructor (protected readonly uiServerConfiguration: UIServerConfiguration) {
31 super(uiServerConfiguration)
32 this.webSocketServer = new WebSocketServer({
33 handleProtocols: UIServerUtils.handleProtocols,
34 noServer: true
35 })
36 }
37
38 public start (): void {
39 this.webSocketServer.on('connection', (ws: WebSocket, _req: IncomingMessage): void => {
40 if (!UIServerUtils.isProtocolAndVersionSupported(ws.protocol)) {
41 logger.error(
42 `${this.logPrefix(
43 moduleName,
44 'start.server.onconnection'
45 )} Unsupported UI protocol version: '${ws.protocol}'`
46 )
47 ws.close(WebSocketCloseEventStatusCode.CLOSE_PROTOCOL_ERROR)
48 }
49 const [, version] = UIServerUtils.getProtocolAndVersion(ws.protocol)
50 this.registerProtocolVersionUIService(version)
51 ws.on('message', rawData => {
52 const request = this.validateRawDataRequest(rawData)
53 if (request === false) {
54 ws.close(WebSocketCloseEventStatusCode.CLOSE_INVALID_PAYLOAD)
55 return
56 }
57 const [requestId] = request
58 this.responseHandlers.set(requestId, ws)
59 this.uiServices
60 .get(version)
61 ?.requestHandler(request)
62 .then((protocolResponse?: ProtocolResponse) => {
63 if (protocolResponse != null) {
64 this.sendResponse(protocolResponse)
65 }
66 })
67 .catch(Constants.EMPTY_FUNCTION)
68 })
69 ws.on('error', error => {
70 logger.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error)
71 })
72 ws.on('close', (code, reason) => {
73 logger.debug(
74 `${this.logPrefix(
75 moduleName,
76 'start.ws.onclose'
77 )} WebSocket closed: '${getWebSocketCloseEventStatusString(
78 code
79 )}' - '${reason.toString()}'`
80 )
81 })
82 })
83 this.httpServer.on('connect', (req: IncomingMessage, socket: Duplex, _head: Buffer) => {
84 if (req.headers.connection !== 'Upgrade' || req.headers.upgrade !== 'websocket') {
85 socket.write(`HTTP/1.1 ${StatusCodes.BAD_REQUEST} Bad Request\r\n\r\n`)
86 socket.destroy()
87 }
88 })
89 this.httpServer.on('upgrade', (req: IncomingMessage, socket: Duplex, head: Buffer): void => {
90 this.authenticate(req, err => {
91 if (err != null) {
92 socket.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`)
93 socket.destroy()
94 return
95 }
96 try {
97 this.webSocketServer.handleUpgrade(req, socket, head, (ws: WebSocket) => {
98 this.webSocketServer.emit('connection', ws, req)
99 })
100 } catch (error) {
101 logger.error(
102 `${this.logPrefix(
103 moduleName,
104 'start.httpServer.on.upgrade'
105 )} Error at handling connection upgrade:`,
106 error
107 )
108 }
109 })
110 })
111 this.startHttpServer()
112 }
113
114 public sendRequest (request: ProtocolRequest): void {
115 this.broadcastToClients(JSON.stringify(request))
116 }
117
118 public sendResponse (response: ProtocolResponse): void {
119 const responseId = response[0]
120 try {
121 if (this.hasResponseHandler(responseId)) {
122 const ws = this.responseHandlers.get(responseId) as WebSocket
123 if (ws.readyState === WebSocket.OPEN) {
124 ws.send(JSONStringifyWithMapSupport(response))
125 } else {
126 logger.error(
127 `${this.logPrefix(
128 moduleName,
129 'sendResponse'
130 )} Error at sending response id '${responseId}', WebSocket is not open: ${
131 ws.readyState
132 }`
133 )
134 }
135 } else {
136 logger.error(
137 `${this.logPrefix(
138 moduleName,
139 'sendResponse'
140 )} Response for unknown request id: ${responseId}`
141 )
142 }
143 } catch (error) {
144 logger.error(
145 `${this.logPrefix(
146 moduleName,
147 'sendResponse'
148 )} Error at sending response id '${responseId}':`,
149 error
150 )
151 } finally {
152 this.responseHandlers.delete(responseId)
153 }
154 }
155
156 public logPrefix = (modName?: string, methodName?: string, prefixSuffix?: string): string => {
157 const logMsgPrefix =
158 prefixSuffix != null ? `UI WebSocket Server ${prefixSuffix}` : 'UI WebSocket Server'
159 const logMsg =
160 isNotEmptyString(modName) && isNotEmptyString(methodName)
161 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
162 : ` ${logMsgPrefix} |`
163 return logPrefix(logMsg)
164 }
165
166 private broadcastToClients (message: string): void {
167 for (const client of this.webSocketServer.clients) {
168 if (client.readyState === WebSocket.OPEN) {
169 client.send(message)
170 }
171 }
172 }
173
174 private validateRawDataRequest (rawData: RawData): ProtocolRequest | false {
175 // logger.debug(
176 // `${this.logPrefix(
177 // moduleName,
178 // 'validateRawDataRequest'
179 // // eslint-disable-next-line @typescript-eslint/no-base-to-string
180 // )} Raw data received in string format: ${rawData.toString()}`
181 // )
182
183 let request: ProtocolRequest
184 try {
185 // eslint-disable-next-line @typescript-eslint/no-base-to-string
186 request = JSON.parse(rawData.toString()) as ProtocolRequest
187 } catch (error) {
188 logger.error(
189 `${this.logPrefix(
190 moduleName,
191 'validateRawDataRequest'
192 // eslint-disable-next-line @typescript-eslint/no-base-to-string
193 )} UI protocol request is not valid JSON: ${rawData.toString()}`
194 )
195 return false
196 }
197
198 if (!Array.isArray(request)) {
199 logger.error(
200 `${this.logPrefix(
201 moduleName,
202 'validateRawDataRequest'
203 )} UI protocol request is not an array:`,
204 request
205 )
206 return false
207 }
208
209 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
210 if (request.length !== 3) {
211 logger.error(
212 `${this.logPrefix(moduleName, 'validateRawDataRequest')} UI protocol request is malformed:`,
213 request
214 )
215 return false
216 }
217
218 if (!validateUUID(request[0])) {
219 logger.error(
220 `${this.logPrefix(
221 moduleName,
222 'validateRawDataRequest'
223 )} UI protocol request UUID field is invalid:`,
224 request
225 )
226 return false
227 }
228
229 return request
230 }
231 }