1 import type { IncomingMessage
} from
'node:http'
2 import type { Duplex
} from
'node:stream'
4 import { StatusCodes
} from
'http-status-codes'
5 import { type RawData
, WebSocket
, WebSocketServer
} from
'ws'
7 import { AbstractUIServer
} from
'./AbstractUIServer.js'
8 import { UIServerUtils
} from
'./UIServerUtils.js'
11 type ProtocolResponse
,
12 type UIServerConfiguration
,
13 WebSocketCloseEventStatusCode
14 } from
'../../types/index.js'
17 JSONStringifyWithMapSupport
,
18 getWebSocketCloseEventStatusString
,
23 } from
'../../utils/index.js'
25 const moduleName
= 'UIWebSocketServer'
27 export class UIWebSocketServer
extends AbstractUIServer
{
28 private readonly webSocketServer
: WebSocketServer
30 public constructor (protected readonly uiServerConfiguration
: UIServerConfiguration
) {
31 super(uiServerConfiguration
)
32 this.webSocketServer
= new WebSocketServer({
33 handleProtocols
: UIServerUtils
.handleProtocols
,
38 public start (): void {
39 this.webSocketServer
.on('connection', (ws
: WebSocket
, _req
: IncomingMessage
): void => {
40 if (!UIServerUtils
.isProtocolAndVersionSupported(ws
.protocol
)) {
44 'start.server.onconnection'
45 )} Unsupported UI protocol version: '${ws.protocol}'`
47 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_PROTOCOL_ERROR
)
49 const [, version
] = UIServerUtils
.getProtocolAndVersion(ws
.protocol
)
50 this.registerProtocolVersionUIService(version
)
51 ws
.on('message', rawData
=> {
52 const request
= this.validateRawDataRequest(rawData
)
53 if (request
=== false) {
54 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_INVALID_PAYLOAD
)
57 const [requestId
] = request
58 this.responseHandlers
.set(requestId
, ws
)
61 ?.requestHandler(request
)
62 .then((protocolResponse
?: ProtocolResponse
) => {
63 if (protocolResponse
!= null) {
64 this.sendResponse(protocolResponse
)
67 .catch(Constants
.EMPTY_FUNCTION
)
69 ws
.on('error', error
=> {
70 logger
.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error
)
72 ws
.on('close', (code
, reason
) => {
77 )} WebSocket closed: '${getWebSocketCloseEventStatusString(
79 )}' - '${reason.toString()}'`
83 this.httpServer
.on('connect', (req
: IncomingMessage
, socket
: Duplex
, _head
: Buffer
) => {
84 if (req
.headers
.connection
!== 'Upgrade' || req
.headers
.upgrade
!== 'websocket') {
85 socket
.write(`HTTP/1.1 ${StatusCodes.BAD_REQUEST} Bad Request\r\n\r\n`)
89 this.httpServer
.on('upgrade', (req
: IncomingMessage
, socket
: Duplex
, head
: Buffer
): void => {
90 this.authenticate(req
, err
=> {
92 socket
.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`)
97 this.webSocketServer
.handleUpgrade(req
, socket
, head
, (ws
: WebSocket
) => {
98 this.webSocketServer
.emit('connection', ws
, req
)
104 'start.httpServer.on.upgrade'
105 )} Error at handling connection upgrade:`,
111 this.startHttpServer()
114 public sendRequest (request
: ProtocolRequest
): void {
115 this.broadcastToClients(JSON
.stringify(request
))
118 public sendResponse (response
: ProtocolResponse
): void {
119 const responseId
= response
[0]
121 if (this.hasResponseHandler(responseId
)) {
122 const ws
= this.responseHandlers
.get(responseId
) as WebSocket
123 if (ws
.readyState
=== WebSocket
.OPEN
) {
124 ws
.send(JSONStringifyWithMapSupport(response
))
130 )} Error at sending response id '${responseId}', WebSocket is not open: ${
140 )} Response for unknown request id: ${responseId}`
148 )} Error at sending response id '${responseId}':`,
152 this.responseHandlers
.delete(responseId
)
156 public logPrefix
= (modName
?: string, methodName
?: string, prefixSuffix
?: string): string => {
158 prefixSuffix
!= null ? `UI WebSocket Server ${prefixSuffix}` : 'UI WebSocket Server'
160 isNotEmptyString(modName
) && isNotEmptyString(methodName
)
161 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
162 : ` ${logMsgPrefix} |`
163 return logPrefix(logMsg
)
166 private broadcastToClients (message
: string): void {
167 for (const client
of this.webSocketServer
.clients
) {
168 if (client
.readyState
=== WebSocket
.OPEN
) {
174 private validateRawDataRequest (rawData
: RawData
): ProtocolRequest
| false {
176 // `${this.logPrefix(
178 // 'validateRawDataRequest'
179 // // eslint-disable-next-line @typescript-eslint/no-base-to-string
180 // )} Raw data received in string format: ${rawData.toString()}`
183 let request
: ProtocolRequest
185 // eslint-disable-next-line @typescript-eslint/no-base-to-string
186 request
= JSON
.parse(rawData
.toString()) as ProtocolRequest
191 'validateRawDataRequest'
192 // eslint-disable-next-line @typescript-eslint/no-base-to-string
193 )} UI protocol request is not valid JSON: ${rawData.toString()}`
198 if (!Array.isArray(request
)) {
202 'validateRawDataRequest'
203 )} UI protocol request is not an array:`,
209 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
210 if (request
.length
!== 3) {
212 `${this.logPrefix(moduleName, 'validateRawDataRequest')} UI protocol request is malformed:`,
218 if (!validateUUID(request
[0])) {
222 'validateRawDataRequest'
223 )} UI protocol request UUID field is invalid:`,