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