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';
10 type UIServerConfiguration
,
11 WebSocketCloseEventStatusCode
,
13 import { Constants
, Utils
, logger
} from
'../../utils';
14 import { AbstractUIServer
, UIServerUtils
} from
'../internal';
16 const moduleName
= 'UIWebSocketServer';
18 export class UIWebSocketServer
extends AbstractUIServer
{
19 private readonly webSocketServer
: WebSocketServer
;
21 public constructor(protected readonly uiServerConfiguration
: UIServerConfiguration
) {
22 super(uiServerConfiguration
);
23 this.webSocketServer
= new WebSocketServer({
24 handleProtocols
: UIServerUtils
.handleProtocols
,
29 public start(): void {
30 // eslint-disable-next-line @typescript-eslint/no-unused-vars
31 this.webSocketServer
.on('connection', (ws
: WebSocket
, req
: IncomingMessage
): void => {
32 if (UIServerUtils
.isProtocolAndVersionSupported(ws
.protocol
) === false) {
36 'start.server.onconnection'
37 )} Unsupported UI protocol version: '${ws.protocol}'`
39 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_PROTOCOL_ERROR
);
41 const [, version
] = UIServerUtils
.getProtocolAndVersion(ws
.protocol
);
42 this.registerProtocolVersionUIService(version
);
43 ws
.on('message', (rawData
) => {
44 const request
= this.validateRawDataRequest(rawData
);
45 if (request
=== false) {
46 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_INVALID_PAYLOAD
);
49 const [requestId
] = request
as ProtocolRequest
;
50 this.responseHandlers
.set(requestId
, ws
);
51 this.uiServices
.get(version
)?.requestHandler(request
).catch(Constants
.EMPTY_FUNCTION
);
53 ws
.on('error', (error
) => {
54 logger
.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error
);
56 ws
.on('close', (code
, reason
) => {
61 )} WebSocket closed: '${Utils.getWebSocketCloseEventStatusString(
63 )}' - '${reason.toString()}'`
67 // eslint-disable-next-line @typescript-eslint/no-unused-vars
68 this.httpServer
.on('connect', (req
: IncomingMessage
, socket
: Duplex
, head
: Buffer
) => {
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`);
74 this.httpServer
.on('upgrade', (req
: IncomingMessage
, socket
: Duplex
, head
: Buffer
): void => {
75 this.authenticate(req
, (err
) => {
77 socket
.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`);
82 this.webSocketServer
.handleUpgrade(req
, socket
, head
, (ws
: WebSocket
) => {
83 this.webSocketServer
.emit('connection', ws
, req
);
89 'start.httpServer.on.upgrade'
90 )} Error at handling connection upgrade:`,
96 this.startHttpServer();
99 public sendRequest(request
: ProtocolRequest
): void {
100 this.broadcastToClients(JSON
.stringify(request
));
103 public sendResponse(response
: ProtocolResponse
): void {
104 const responseId
= response
[0];
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
));
115 )} Error at sending response id '${responseId}', WebSocket is not open: ${
125 )} Response for unknown request id: ${responseId}`
133 )} Error at sending response id '${responseId}':`,
137 this.responseHandlers
.delete(responseId
);
141 public logPrefix
= (modName
?: string, methodName
?: string, prefixSuffix
?: string): string => {
142 const logMsgPrefix
= prefixSuffix
143 ? `UI WebSocket Server ${prefixSuffix}`
144 : 'UI WebSocket Server';
146 Utils
.isNotEmptyString(modName
) && Utils
.isNotEmptyString(methodName
)
147 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
148 : ` ${logMsgPrefix} |`;
149 return Utils
.logPrefix(logMsg
);
152 private broadcastToClients(message
: string): void {
153 for (const client
of this.webSocketServer
.clients
) {
154 if (client
?.readyState
=== WebSocket
.OPEN
) {
155 client
.send(message
);
160 private validateRawDataRequest(rawData
: RawData
): ProtocolRequest
| false {
162 // `${this.logPrefix(
164 // 'validateRawDataRequest'
165 // )} Raw data received in string format: ${rawData.toString()}`
168 const request
= JSON
.parse(rawData
.toString()) as ProtocolRequest
;
170 if (Array.isArray(request
) === false) {
174 'validateRawDataRequest'
175 )} UI protocol request is not an array:`,
181 if (request
.length
!== 3) {
183 `${this.logPrefix(moduleName, 'validateRawDataRequest')} UI protocol request is malformed:`,
189 if (Utils
.validateUUID(request
[0]) === false) {
193 'validateRawDataRequest'
194 )} UI protocol request UUID field is invalid:`,