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 { UIServerUtils
} from
'./UIServerUtils';
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
: 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
);
53 .requestHandler(request
)
55 /* Error caught by AbstractUIService */
58 ws
.on('error', (error
) => {
59 logger
.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error
);
61 ws
.on('close', (code
, reason
) => {
66 )} WebSocket closed: '${Utils.getWebSocketCloseEventStatusString(
68 )}' - '${reason.toString()}'`
74 (req
: IncomingMessage
, socket
: internal
.Duplex
, head
: Buffer
): void => {
75 this.authenticate(req
, (err
) => {
77 socket
.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`);
81 this.webSocketServer
.handleUpgrade(req
, socket
, head
, (ws
: WebSocket
) => {
82 this.webSocketServer
.emit('connection', ws
, req
);
87 this.startHttpServer();
90 public sendRequest(request
: ProtocolRequest
): void {
91 this.broadcastToClients(JSON
.stringify(request
));
94 public sendResponse(response
: ProtocolResponse
): void {
95 const responseId
= response
[0];
97 if (this.responseHandlers
.has(responseId
)) {
98 const ws
= this.responseHandlers
.get(responseId
) as WebSocket
;
99 if (ws
?.readyState
=== WebSocket
.OPEN
) {
100 ws
.send(JSON
.stringify(response
));
106 )} Error at sending response id '${responseId}', WebSocket is not open: ${
116 )} Response for unknown request id: ${responseId}`
124 )} Error at sending response id '${responseId}':`,
128 this.responseHandlers
.delete(responseId
);
132 public logPrefix(modName
?: string, methodName
?: string, prefixSuffix
?: string): string {
133 const logMsgPrefix
= prefixSuffix
134 ? `UI WebSocket Server ${prefixSuffix}`
135 : 'UI WebSocket Server';
137 modName
&& methodName
? ` ${logMsgPrefix} | ${modName}.${methodName}:` : ` ${logMsgPrefix} |`;
138 return Utils
.logPrefix(logMsg
);
141 private broadcastToClients(message
: string): void {
142 for (const client
of this.webSocketServer
.clients
) {
143 if (client
?.readyState
=== WebSocket
.OPEN
) {
144 client
.send(message
);
149 private validateRawDataRequest(rawData
: RawData
): ProtocolRequest
| false {
151 // `${this.logPrefix(
153 // 'validateRawDataRequest'
154 // )} Raw data received in string format: ${rawData.toString()}`
157 const request
= JSON
.parse(rawData
.toString()) as ProtocolRequest
;
159 if (Array.isArray(request
) === false) {
163 'validateRawDataRequest'
164 )} UI protocol request is not an array:`,
170 if (request
.length
!== 3) {
172 `${this.logPrefix(moduleName, 'validateRawDataRequest')} UI protocol request is malformed:`,
178 if (uuid
.validate(request
[0]) === false) {
182 'validateRawDataRequest'
183 )} UI protocol request UUID field is invalid:`,