Commit | Line | Data |
---|---|---|
daa6505e | 1 | import type { IncomingMessage } from 'http'; |
eb3abc4f | 2 | import type internal from 'stream'; |
8114d10e | 3 | |
eb3abc4f | 4 | import { StatusCodes } from 'http-status-codes'; |
976d11ec | 5 | import WebSocket, { type RawData, WebSocketServer } from 'ws'; |
8114d10e | 6 | |
eb3abc4f | 7 | import type { UIServerConfiguration } from '../../types/ConfigurationData'; |
5e3cb728 | 8 | import type { ProtocolRequest, ProtocolResponse } from '../../types/UIProtocol'; |
8b0088bb | 9 | import { WebSocketCloseEventStatusCode } from '../../types/WebSocket'; |
675fa8e3 | 10 | import logger from '../../utils/Logger'; |
8114d10e JB |
11 | import Utils from '../../utils/Utils'; |
12 | import { AbstractUIServer } from './AbstractUIServer'; | |
ed3d2808 | 13 | import { UIServerUtils } from './UIServerUtils'; |
4198ad5c | 14 | |
32de5a57 LM |
15 | const moduleName = 'UIWebSocketServer'; |
16 | ||
fe94fce0 | 17 | export default class UIWebSocketServer extends AbstractUIServer { |
eb3abc4f JB |
18 | private readonly webSocketServer: WebSocketServer; |
19 | ||
20 | public constructor(protected readonly uiServerConfiguration: UIServerConfiguration) { | |
21 | super(uiServerConfiguration); | |
eb3abc4f | 22 | this.webSocketServer = new WebSocketServer({ |
ed3d2808 | 23 | handleProtocols: UIServerUtils.handleProtocols, |
eb3abc4f JB |
24 | noServer: true, |
25 | }); | |
4198ad5c JB |
26 | } |
27 | ||
28 | public start(): void { | |
fd3c56d1 | 29 | // eslint-disable-next-line @typescript-eslint/no-unused-vars |
eb3abc4f | 30 | this.webSocketServer.on('connection', (ws: WebSocket, req: IncomingMessage): void => { |
ed3d2808 | 31 | if (UIServerUtils.isProtocolAndVersionSupported(ws.protocol) === false) { |
a92929f1 JB |
32 | logger.error( |
33 | `${this.logPrefix( | |
34 | moduleName, | |
35 | 'start.server.onconnection' | |
7cb5b17f | 36 | )} Unsupported UI protocol version: '${ws.protocol}'` |
a92929f1 | 37 | ); |
5e3cb728 | 38 | ws.close(WebSocketCloseEventStatusCode.CLOSE_PROTOCOL_ERROR); |
a92929f1 | 39 | } |
ed3d2808 | 40 | const [, version] = UIServerUtils.getProtocolAndVersion(ws.protocol); |
143498c8 | 41 | this.registerProtocolVersionUIService(version); |
5e3cb728 | 42 | ws.on('message', (rawData) => { |
5dea4c94 JB |
43 | const request = this.validateRawDataRequest(rawData); |
44 | if (request === false) { | |
45 | ws.close(WebSocketCloseEventStatusCode.CLOSE_INVALID_PAYLOAD); | |
46 | return; | |
47 | } | |
94dc3080 JB |
48 | const [requestId] = request as ProtocolRequest; |
49 | this.responseHandlers.set(requestId, ws); | |
e7aeea18 JB |
50 | this.uiServices |
51 | .get(version) | |
94dc3080 | 52 | .requestHandler(request) |
6c8f5d90 JB |
53 | .catch(() => { |
54 | /* Error caught by AbstractUIService */ | |
e7aeea18 | 55 | }); |
4198ad5c | 56 | }); |
5e3cb728 JB |
57 | ws.on('error', (error) => { |
58 | logger.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error); | |
59 | }); | |
60 | ws.on('close', (code, reason) => { | |
61 | logger.debug( | |
62 | `${this.logPrefix( | |
63 | moduleName, | |
64 | 'start.ws.onclose' | |
65 | )} WebSocket closed: '${Utils.getWebSocketCloseEventStatusString( | |
66 | code | |
67 | )}' - '${reason.toString()}'` | |
32de5a57 | 68 | ); |
4198ad5c JB |
69 | }); |
70 | }); | |
cbf9b878 JB |
71 | // eslint-disable-next-line @typescript-eslint/no-unused-vars |
72 | this.httpServer.on('connect', (req: IncomingMessage, socket: internal.Duplex, head: Buffer) => { | |
73 | if (req.headers?.connection !== 'Upgrade' || req.headers?.upgrade !== 'websocket') { | |
74 | socket.write(`HTTP/1.1 ${StatusCodes.BAD_REQUEST} Bad Request\r\n\r\n`); | |
75 | socket.destroy(); | |
76 | } | |
77 | }); | |
eb3abc4f JB |
78 | this.httpServer.on( |
79 | 'upgrade', | |
80 | (req: IncomingMessage, socket: internal.Duplex, head: Buffer): void => { | |
81 | this.authenticate(req, (err) => { | |
cbf9b878 JB |
82 | if (err) { |
83 | socket.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`); | |
4055bcb9 | 84 | socket.destroy(); |
cbf9b878 JB |
85 | return; |
86 | } | |
87 | try { | |
88 | this.webSocketServer.handleUpgrade(req, socket, head, (ws: WebSocket) => { | |
89 | this.webSocketServer.emit('connection', ws, req); | |
90 | }); | |
91 | } catch (error) { | |
92 | logger.error( | |
93 | `${this.logPrefix( | |
94 | moduleName, | |
95 | 'start.httpServer.on.upgrade' | |
96 | )} Error at handling connection upgrade:`, | |
97 | error | |
98 | ); | |
eb3abc4f | 99 | } |
eb3abc4f JB |
100 | }); |
101 | } | |
102 | ); | |
a307349b | 103 | this.startHttpServer(); |
4198ad5c JB |
104 | } |
105 | ||
5e3cb728 JB |
106 | public sendRequest(request: ProtocolRequest): void { |
107 | this.broadcastToClients(JSON.stringify(request)); | |
02a6943a JB |
108 | } |
109 | ||
5e3cb728 | 110 | public sendResponse(response: ProtocolResponse): void { |
94dc3080 | 111 | const responseId = response[0]; |
976d11ec JB |
112 | try { |
113 | if (this.responseHandlers.has(responseId)) { | |
114 | const ws = this.responseHandlers.get(responseId) as WebSocket; | |
115 | if (ws?.readyState === WebSocket.OPEN) { | |
116 | ws.send(JSON.stringify(response)); | |
e2c77f10 JB |
117 | } else { |
118 | logger.error( | |
119 | `${this.logPrefix( | |
120 | moduleName, | |
121 | 'sendResponse' | |
122 | )} Error at sending response id '${responseId}', WebSocket is not open: ${ | |
123 | ws?.readyState | |
124 | }` | |
125 | ); | |
976d11ec | 126 | } |
976d11ec JB |
127 | } else { |
128 | logger.error( | |
129 | `${this.logPrefix( | |
130 | moduleName, | |
131 | 'sendResponse' | |
132 | )} Response for unknown request id: ${responseId}` | |
133 | ); | |
94dc3080 | 134 | } |
976d11ec | 135 | } catch (error) { |
94dc3080 JB |
136 | logger.error( |
137 | `${this.logPrefix( | |
138 | moduleName, | |
139 | 'sendResponse' | |
976d11ec JB |
140 | )} Error at sending response id '${responseId}':`, |
141 | error | |
94dc3080 | 142 | ); |
e2c77f10 JB |
143 | } finally { |
144 | this.responseHandlers.delete(responseId); | |
94dc3080 | 145 | } |
178ac666 JB |
146 | } |
147 | ||
0d2cec76 JB |
148 | public logPrefix(modName?: string, methodName?: string, prefixSuffix?: string): string { |
149 | const logMsgPrefix = prefixSuffix | |
150 | ? `UI WebSocket Server ${prefixSuffix}` | |
151 | : 'UI WebSocket Server'; | |
32de5a57 | 152 | const logMsg = |
0d2cec76 | 153 | modName && methodName ? ` ${logMsgPrefix} | ${modName}.${methodName}:` : ` ${logMsgPrefix} |`; |
32de5a57 | 154 | return Utils.logPrefix(logMsg); |
4198ad5c | 155 | } |
178ac666 JB |
156 | |
157 | private broadcastToClients(message: string): void { | |
eb3abc4f | 158 | for (const client of this.webSocketServer.clients) { |
0d8140bd | 159 | if (client?.readyState === WebSocket.OPEN) { |
178ac666 JB |
160 | client.send(message); |
161 | } | |
162 | } | |
163 | } | |
5e3cb728 | 164 | |
5dea4c94 | 165 | private validateRawDataRequest(rawData: RawData): ProtocolRequest | false { |
5e3cb728 JB |
166 | // logger.debug( |
167 | // `${this.logPrefix( | |
168 | // moduleName, | |
169 | // 'validateRawDataRequest' | |
170 | // )} Raw data received in string format: ${rawData.toString()}` | |
171 | // ); | |
172 | ||
173 | const request = JSON.parse(rawData.toString()) as ProtocolRequest; | |
174 | ||
175 | if (Array.isArray(request) === false) { | |
5dea4c94 JB |
176 | logger.error( |
177 | `${this.logPrefix( | |
178 | moduleName, | |
179 | 'validateRawDataRequest' | |
180 | )} UI protocol request is not an array:`, | |
181 | request | |
182 | ); | |
183 | return false; | |
5e3cb728 JB |
184 | } |
185 | ||
186 | if (request.length !== 3) { | |
5dea4c94 JB |
187 | logger.error( |
188 | `${this.logPrefix(moduleName, 'validateRawDataRequest')} UI protocol request is malformed:`, | |
189 | request | |
190 | ); | |
191 | return false; | |
192 | } | |
193 | ||
03eacbe5 | 194 | if (Utils.validateUUID(request[0]) === false) { |
5dea4c94 JB |
195 | logger.error( |
196 | `${this.logPrefix( | |
197 | moduleName, | |
198 | 'validateRawDataRequest' | |
199 | )} UI protocol request UUID field is invalid:`, | |
200 | request | |
201 | ); | |
202 | return false; | |
5e3cb728 JB |
203 | } |
204 | ||
205 | return request; | |
206 | } | |
4198ad5c | 207 | } |