1 import type { IncomingMessage
} from
'http';
2 import type internal from
'stream';
4 import { StatusCodes
} from
'http-status-codes';
5 import * as uuid from
'uuid';
6 import WebSocket
, { type RawData
, WebSocketServer
} from
'ws';
8 import type { UIServerConfiguration
} from
'../../types/ConfigurationData';
9 import type { ProtocolRequest
, ProtocolResponse
} from
'../../types/UIProtocol';
10 import { WebSocketCloseEventStatusCode
} from
'../../types/WebSocket';
11 import logger from
'../../utils/Logger';
12 import Utils from
'../../utils/Utils';
13 import { AbstractUIServer
} from
'./AbstractUIServer';
14 import { UIServiceUtils
} from
'./ui-services/UIServiceUtils';
16 const moduleName
= 'UIWebSocketServer';
18 export default 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
: UIServiceUtils
.handleProtocols
,
29 public start(): void {
30 this.webSocketServer
.on('connection', (ws
: WebSocket
, req
: IncomingMessage
): void => {
31 const [protocol
, version
] = UIServiceUtils
.getProtocolAndVersion(ws
.protocol
);
32 if (UIServiceUtils
.isProtocolAndVersionSupported(protocol
, version
) === false) {
36 'start.server.onconnection'
37 )} Unsupported UI protocol version: '${protocol}${version}'`
39 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_PROTOCOL_ERROR
);
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()}'`
73 (req
: IncomingMessage
, socket
: internal
.Duplex
, head
: Buffer
): void => {
74 this.authenticate(req
, (err
) => {
76 socket
.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`);
80 this.webSocketServer
.handleUpgrade(req
, socket
, head
, (ws
: WebSocket
) => {
81 this.webSocketServer
.emit('connection', ws
, req
);
86 if (this.httpServer
.listening
=== false) {
87 this.httpServer
.listen(this.uiServerConfiguration
.options
);
91 public sendRequest(request
: ProtocolRequest
): void {
92 this.broadcastToClients(JSON
.stringify(request
));
95 public sendResponse(response
: ProtocolResponse
): void {
96 const responseId
= response
[0];
98 if (this.responseHandlers
.has(responseId
)) {
99 const ws
= this.responseHandlers
.get(responseId
) as WebSocket
;
100 if (ws
?.readyState
=== WebSocket
.OPEN
) {
101 ws
.send(JSON
.stringify(response
));
107 )} Error at sending response id '${responseId}', WebSocket is not open: ${
117 )} Response for unknown request id: ${responseId}`
125 )} Error at sending response id '${responseId}':`,
129 this.responseHandlers
.delete(responseId
);
133 public logPrefix(modName
?: string, methodName
?: string, prefixSuffix
?: string): string {
134 const logMsgPrefix
= prefixSuffix
135 ? `UI WebSocket Server ${prefixSuffix}`
136 : 'UI WebSocket Server';
138 modName
&& methodName
? ` ${logMsgPrefix} | ${modName}.${methodName}:` : ` ${logMsgPrefix} |`;
139 return Utils
.logPrefix(logMsg
);
142 private broadcastToClients(message
: string): void {
143 for (const client
of this.webSocketServer
.clients
) {
144 if (client
?.readyState
=== WebSocket
.OPEN
) {
145 client
.send(message
);
150 private validateRawDataRequest(rawData
: RawData
): ProtocolRequest
| false {
152 // `${this.logPrefix(
154 // 'validateRawDataRequest'
155 // )} Raw data received in string format: ${rawData.toString()}`
158 const request
= JSON
.parse(rawData
.toString()) as ProtocolRequest
;
160 if (Array.isArray(request
) === false) {
164 'validateRawDataRequest'
165 )} UI protocol request is not an array:`,
171 if (request
.length
!== 3) {
173 `${this.logPrefix(moduleName, 'validateRawDataRequest')} UI protocol request is malformed:`,
179 if (uuid
.validate(request
[0]) === false) {
183 'validateRawDataRequest'
184 )} UI protocol request UUID field is invalid:`,