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