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