1 import type { IncomingMessage
} from
'http';
2 import type internal from
'stream';
4 import { StatusCodes
} from
'http-status-codes';
5 import WebSocket
, { type RawData
, WebSocketServer
} from
'ws';
7 import type { UIServerConfiguration
} from
'../../types/ConfigurationData';
8 import type { ProtocolRequest
, ProtocolResponse
} from
'../../types/UIProtocol';
9 import { WebSocketCloseEventStatusCode
} from
'../../types/WebSocket';
10 import logger from
'../../utils/Logger';
11 import Utils from
'../../utils/Utils';
12 import { AbstractUIServer
} from
'./AbstractUIServer';
13 import { UIServerUtils
} from
'./UIServerUtils';
15 const moduleName
= 'UIWebSocketServer';
17 export default class UIWebSocketServer
extends AbstractUIServer
{
18 private readonly webSocketServer
: WebSocketServer
;
20 public constructor(protected readonly uiServerConfiguration
: UIServerConfiguration
) {
21 super(uiServerConfiguration
);
22 this.webSocketServer
= new WebSocketServer({
23 handleProtocols
: UIServerUtils
.handleProtocols
,
28 public start(): void {
29 // eslint-disable-next-line @typescript-eslint/no-unused-vars
30 this.webSocketServer
.on('connection', (ws
: WebSocket
, req
: IncomingMessage
): void => {
31 if (UIServerUtils
.isProtocolAndVersionSupported(ws
.protocol
) === false) {
35 'start.server.onconnection'
36 )} Unsupported UI protocol version: '${ws.protocol}'`
38 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_PROTOCOL_ERROR
);
40 const [, version
] = UIServerUtils
.getProtocolAndVersion(ws
.protocol
);
41 this.registerProtocolVersionUIService(version
);
42 ws
.on('message', (rawData
) => {
43 const request
= this.validateRawDataRequest(rawData
);
44 if (request
=== false) {
45 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_INVALID_PAYLOAD
);
48 const [requestId
] = request
as ProtocolRequest
;
49 this.responseHandlers
.set(requestId
, ws
);
52 .requestHandler(request
)
54 /* Error caught by AbstractUIService */
57 ws
.on('error', (error
) => {
58 logger
.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error
);
60 ws
.on('close', (code
, reason
) => {
65 )} WebSocket closed: '${Utils.getWebSocketCloseEventStatusString(
67 )}' - '${reason.toString()}'`
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`);
80 (req
: IncomingMessage
, socket
: internal
.Duplex
, head
: Buffer
): void => {
81 this.authenticate(req
, (err
) => {
83 socket
.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`);
88 this.webSocketServer
.handleUpgrade(req
, socket
, head
, (ws
: WebSocket
) => {
89 this.webSocketServer
.emit('connection', ws
, req
);
95 'start.httpServer.on.upgrade'
96 )} Error at handling connection upgrade:`,
103 this.startHttpServer();
106 public sendRequest(request
: ProtocolRequest
): void {
107 this.broadcastToClients(JSON
.stringify(request
));
110 public sendResponse(response
: ProtocolResponse
): void {
111 const responseId
= response
[0];
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
));
122 )} Error at sending response id '${responseId}', WebSocket is not open: ${
132 )} Response for unknown request id: ${responseId}`
140 )} Error at sending response id '${responseId}':`,
144 this.responseHandlers
.delete(responseId
);
148 public logPrefix(modName
?: string, methodName
?: string, prefixSuffix
?: string): string {
149 const logMsgPrefix
= prefixSuffix
150 ? `UI WebSocket Server ${prefixSuffix}`
151 : 'UI WebSocket Server';
153 modName
&& methodName
? ` ${logMsgPrefix} | ${modName}.${methodName}:` : ` ${logMsgPrefix} |`;
154 return Utils
.logPrefix(logMsg
);
157 private broadcastToClients(message
: string): void {
158 for (const client
of this.webSocketServer
.clients
) {
159 if (client
?.readyState
=== WebSocket
.OPEN
) {
160 client
.send(message
);
165 private validateRawDataRequest(rawData
: RawData
): ProtocolRequest
| false {
167 // `${this.logPrefix(
169 // 'validateRawDataRequest'
170 // )} Raw data received in string format: ${rawData.toString()}`
173 const request
= JSON
.parse(rawData
.toString()) as ProtocolRequest
;
175 if (Array.isArray(request
) === false) {
179 'validateRawDataRequest'
180 )} UI protocol request is not an array:`,
186 if (request
.length
!== 3) {
188 `${this.logPrefix(moduleName, 'validateRawDataRequest')} UI protocol request is malformed:`,
194 if (Utils
.validateUUID(request
[0]) === false) {
198 'validateRawDataRequest'
199 )} UI protocol request UUID field is invalid:`,