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 { UIServerUtils
} from
'./UIServerUtils';
10 type ProtocolResponse
,
11 type UIServerConfiguration
,
12 WebSocketCloseEventStatusCode
,
14 import { logger
} from
'../../utils/Logger';
15 import { Utils
} from
'../../utils/Utils';
16 import { AbstractUIServer
} from
'../internal';
18 const moduleName
= 'UIWebSocketServer';
20 export class UIWebSocketServer
extends AbstractUIServer
{
21 private readonly webSocketServer
: WebSocketServer
;
23 public constructor(protected readonly uiServerConfiguration
: UIServerConfiguration
) {
24 super(uiServerConfiguration
);
25 this.webSocketServer
= new WebSocketServer({
26 handleProtocols
: UIServerUtils
.handleProtocols
,
31 public start(): void {
32 // eslint-disable-next-line @typescript-eslint/no-unused-vars
33 this.webSocketServer
.on('connection', (ws
: WebSocket
, req
: IncomingMessage
): void => {
34 if (UIServerUtils
.isProtocolAndVersionSupported(ws
.protocol
) === false) {
38 'start.server.onconnection'
39 )} Unsupported UI protocol version: '${ws.protocol}'`
41 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_PROTOCOL_ERROR
);
43 const [, version
] = UIServerUtils
.getProtocolAndVersion(ws
.protocol
);
44 this.registerProtocolVersionUIService(version
);
45 ws
.on('message', (rawData
) => {
46 const request
= this.validateRawDataRequest(rawData
);
47 if (request
=== false) {
48 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_INVALID_PAYLOAD
);
51 const [requestId
] = request
as ProtocolRequest
;
52 this.responseHandlers
.set(requestId
, ws
);
55 ?.requestHandler(request
)
57 /* Error caught by AbstractUIService */
60 ws
.on('error', (error
) => {
61 logger
.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error
);
63 ws
.on('close', (code
, reason
) => {
68 )} WebSocket closed: '${Utils.getWebSocketCloseEventStatusString(
70 )}' - '${reason.toString()}'`
74 // eslint-disable-next-line @typescript-eslint/no-unused-vars
75 this.httpServer
.on('connect', (req
: IncomingMessage
, socket
: internal
.Duplex
, head
: Buffer
) => {
76 if (req
.headers
?.connection
!== 'Upgrade' || req
.headers
?.upgrade
!== 'websocket') {
77 socket
.write(`HTTP/1.1 ${StatusCodes.BAD_REQUEST} Bad Request\r\n\r\n`);
83 (req
: IncomingMessage
, socket
: internal
.Duplex
, head
: Buffer
): void => {
84 this.authenticate(req
, (err
) => {
86 socket
.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`);
91 this.webSocketServer
.handleUpgrade(req
, socket
, head
, (ws
: WebSocket
) => {
92 this.webSocketServer
.emit('connection', ws
, req
);
98 'start.httpServer.on.upgrade'
99 )} Error at handling connection upgrade:`,
106 this.startHttpServer();
109 public sendRequest(request
: ProtocolRequest
): void {
110 this.broadcastToClients(JSON
.stringify(request
));
113 public sendResponse(response
: ProtocolResponse
): void {
114 const responseId
= response
[0];
116 if (this.responseHandlers
.has(responseId
)) {
117 const ws
= this.responseHandlers
.get(responseId
) as WebSocket
;
118 if (ws
?.readyState
=== WebSocket
.OPEN
) {
119 ws
.send(JSON
.stringify(response
));
125 )} Error at sending response id '${responseId}', WebSocket is not open: ${
135 )} Response for unknown request id: ${responseId}`
143 )} Error at sending response id '${responseId}':`,
147 this.responseHandlers
.delete(responseId
);
151 public logPrefix
= (modName
?: string, methodName
?: string, prefixSuffix
?: string): string => {
152 const logMsgPrefix
= prefixSuffix
153 ? `UI WebSocket Server ${prefixSuffix}`
154 : 'UI WebSocket Server';
156 Utils
.isNotEmptyString(modName
) && Utils
.isNotEmptyString(methodName
)
157 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
158 : ` ${logMsgPrefix} |`;
159 return Utils
.logPrefix(logMsg
);
162 private broadcastToClients(message
: string): void {
163 for (const client
of this.webSocketServer
.clients
) {
164 if (client
?.readyState
=== WebSocket
.OPEN
) {
165 client
.send(message
);
170 private validateRawDataRequest(rawData
: RawData
): ProtocolRequest
| false {
172 // `${this.logPrefix(
174 // 'validateRawDataRequest'
175 // )} Raw data received in string format: ${rawData.toString()}`
178 const request
= JSON
.parse(rawData
.toString()) as ProtocolRequest
;
180 if (Array.isArray(request
) === false) {
184 'validateRawDataRequest'
185 )} UI protocol request is not an array:`,
191 if (request
.length
!== 3) {
193 `${this.logPrefix(moduleName, 'validateRawDataRequest')} UI protocol request is malformed:`,
199 if (Utils
.validateUUID(request
[0]) === false) {
203 'validateRawDataRequest'
204 )} UI protocol request UUID field is invalid:`,