1 import type { IncomingMessage
} from
'node:http';
2 import type { Duplex
} from
'node:stream';
4 import { StatusCodes
} from
'http-status-codes';
5 import WebSocket
, { type RawData
, WebSocketServer
} from
'ws';
7 import { AbstractUIServer
} from
'./AbstractUIServer';
8 import { UIServerUtils
} from
'./UIServerUtils';
11 type ProtocolResponse
,
12 type UIServerConfiguration
,
13 WebSocketCloseEventStatusCode
,
15 import { Constants
, Utils
, logger
} from
'../../utils';
17 const moduleName
= 'UIWebSocketServer';
19 export class UIWebSocketServer
extends AbstractUIServer
{
20 private readonly webSocketServer
: WebSocketServer
;
22 public constructor(protected readonly uiServerConfiguration
: UIServerConfiguration
) {
23 super(uiServerConfiguration
);
24 this.webSocketServer
= new WebSocketServer({
25 handleProtocols
: UIServerUtils
.handleProtocols
,
30 public start(): void {
31 // eslint-disable-next-line @typescript-eslint/no-unused-vars
32 this.webSocketServer
.on('connection', (ws
: WebSocket
, req
: IncomingMessage
): void => {
33 if (UIServerUtils
.isProtocolAndVersionSupported(ws
.protocol
) === false) {
37 'start.server.onconnection'
38 )} Unsupported UI protocol version: '${ws.protocol}'`
40 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_PROTOCOL_ERROR
);
42 const [, version
] = UIServerUtils
.getProtocolAndVersion(ws
.protocol
);
43 this.registerProtocolVersionUIService(version
);
44 ws
.on('message', (rawData
) => {
45 const request
= this.validateRawDataRequest(rawData
);
46 if (request
=== false) {
47 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_INVALID_PAYLOAD
);
50 const [requestId
] = request
as ProtocolRequest
;
51 this.responseHandlers
.set(requestId
, ws
);
52 this.uiServices
.get(version
)?.requestHandler(request
).catch(Constants
.EMPTY_FUNCTION
);
54 ws
.on('error', (error
) => {
55 logger
.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error
);
57 ws
.on('close', (code
, reason
) => {
62 )} WebSocket closed: '${Utils.getWebSocketCloseEventStatusString(
64 )}' - '${reason.toString()}'`
68 // eslint-disable-next-line @typescript-eslint/no-unused-vars
69 this.httpServer
.on('connect', (req
: IncomingMessage
, socket
: Duplex
, head
: Buffer
) => {
70 if (req
.headers
?.connection
!== 'Upgrade' || req
.headers
?.upgrade
!== 'websocket') {
71 socket
.write(`HTTP/1.1 ${StatusCodes.BAD_REQUEST} Bad Request\r\n\r\n`);
75 this.httpServer
.on('upgrade', (req
: IncomingMessage
, socket
: Duplex
, head
: Buffer
): void => {
76 this.authenticate(req
, (err
) => {
78 socket
.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`);
83 this.webSocketServer
.handleUpgrade(req
, socket
, head
, (ws
: WebSocket
) => {
84 this.webSocketServer
.emit('connection', ws
, req
);
90 'start.httpServer.on.upgrade'
91 )} Error at handling connection upgrade:`,
97 this.startHttpServer();
100 public sendRequest(request
: ProtocolRequest
): void {
101 this.broadcastToClients(JSON
.stringify(request
));
104 public sendResponse(response
: ProtocolResponse
): void {
105 const responseId
= response
[0];
107 if (this.responseHandlers
.has(responseId
)) {
108 const ws
= this.responseHandlers
.get(responseId
) as WebSocket
;
109 if (ws
?.readyState
=== WebSocket
.OPEN
) {
110 ws
.send(JSON
.stringify(response
));
116 )} Error at sending response id '${responseId}', WebSocket is not open: ${
126 )} Response for unknown request id: ${responseId}`
134 )} Error at sending response id '${responseId}':`,
138 this.responseHandlers
.delete(responseId
);
142 public logPrefix
= (modName
?: string, methodName
?: string, prefixSuffix
?: string): string => {
143 const logMsgPrefix
= prefixSuffix
144 ? `UI WebSocket Server ${prefixSuffix}`
145 : 'UI WebSocket Server';
147 Utils
.isNotEmptyString(modName
) && Utils
.isNotEmptyString(methodName
)
148 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
149 : ` ${logMsgPrefix} |`;
150 return Utils
.logPrefix(logMsg
);
153 private broadcastToClients(message
: string): void {
154 for (const client
of this.webSocketServer
.clients
) {
155 if (client
?.readyState
=== WebSocket
.OPEN
) {
156 client
.send(message
);
161 private validateRawDataRequest(rawData
: RawData
): ProtocolRequest
| false {
163 // `${this.logPrefix(
165 // 'validateRawDataRequest'
166 // )} Raw data received in string format: ${rawData.toString()}`
169 const request
= JSON
.parse(rawData
.toString()) as ProtocolRequest
;
171 if (Array.isArray(request
) === false) {
175 'validateRawDataRequest'
176 )} UI protocol request is not an array:`,
182 if (request
.length
!== 3) {
184 `${this.logPrefix(moduleName, 'validateRawDataRequest')} UI protocol request is malformed:`,
190 if (Utils
.validateUUID(request
[0]) === false) {
194 'validateRawDataRequest'
195 )} UI protocol request UUID field is invalid:`,