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'
11 isProtocolAndVersionSupported
12 } from
'./UIServerUtils.js'
15 type ProtocolResponse
,
16 type UIServerConfiguration
,
17 WebSocketCloseEventStatusCode
18 } from
'../../types/index.js'
21 JSONStringifyWithMapSupport
,
22 getWebSocketCloseEventStatusString
,
27 } from
'../../utils/index.js'
29 const moduleName
= 'UIWebSocketServer'
31 export class UIWebSocketServer
extends AbstractUIServer
{
32 private readonly webSocketServer
: WebSocketServer
34 public constructor (protected readonly uiServerConfiguration
: UIServerConfiguration
) {
35 super(uiServerConfiguration
)
36 this.webSocketServer
= new WebSocketServer({
42 public start (): void {
43 this.webSocketServer
.on('connection', (ws
: WebSocket
, _req
: IncomingMessage
): void => {
44 if (!isProtocolAndVersionSupported(ws
.protocol
)) {
48 'start.server.onconnection'
49 )} Unsupported UI protocol version: '${ws.protocol}'`
51 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_PROTOCOL_ERROR
)
53 const [, version
] = getProtocolAndVersion(ws
.protocol
)
54 this.registerProtocolVersionUIService(version
)
55 ws
.on('message', rawData
=> {
56 const request
= this.validateRawDataRequest(rawData
)
57 if (request
=== false) {
58 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_INVALID_PAYLOAD
)
61 const [requestId
] = request
62 this.responseHandlers
.set(requestId
, ws
)
65 ?.requestHandler(request
)
66 .then((protocolResponse
?: ProtocolResponse
) => {
67 if (protocolResponse
!= null) {
68 this.sendResponse(protocolResponse
)
71 .catch(Constants
.EMPTY_FUNCTION
)
73 ws
.on('error', error
=> {
74 logger
.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error
)
76 ws
.on('close', (code
, reason
) => {
81 )} WebSocket closed: '${getWebSocketCloseEventStatusString(
83 )}' - '${reason.toString()}'`
87 this.httpServer
.on('connect', (req
: IncomingMessage
, socket
: Duplex
, _head
: Buffer
) => {
88 if (req
.headers
.connection
!== 'Upgrade' || req
.headers
.upgrade
!== 'websocket') {
89 socket
.write(`HTTP/1.1 ${StatusCodes.BAD_REQUEST} Bad Request\r\n\r\n`)
93 this.httpServer
.on('upgrade', (req
: IncomingMessage
, socket
: Duplex
, head
: Buffer
): void => {
94 this.authenticate(req
, err
=> {
96 socket
.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`)
101 this.webSocketServer
.handleUpgrade(req
, socket
, head
, (ws
: WebSocket
) => {
102 this.webSocketServer
.emit('connection', ws
, req
)
108 'start.httpServer.on.upgrade'
109 )} Error at handling connection upgrade:`,
115 this.startHttpServer()
118 public sendRequest (request
: ProtocolRequest
): void {
119 this.broadcastToClients(JSON
.stringify(request
))
122 public sendResponse (response
: ProtocolResponse
): void {
123 const responseId
= response
[0]
125 if (this.hasResponseHandler(responseId
)) {
126 const ws
= this.responseHandlers
.get(responseId
) as WebSocket
127 if (ws
.readyState
=== WebSocket
.OPEN
) {
128 ws
.send(JSONStringifyWithMapSupport(response
))
134 )} Error at sending response id '${responseId}', WebSocket is not open: ${
144 )} Response for unknown request id: ${responseId}`
152 )} Error at sending response id '${responseId}':`,
156 this.responseHandlers
.delete(responseId
)
160 public logPrefix
= (modName
?: string, methodName
?: string, prefixSuffix
?: string): string => {
162 prefixSuffix
!= null ? `UI WebSocket Server ${prefixSuffix}` : 'UI WebSocket Server'
164 isNotEmptyString(modName
) && isNotEmptyString(methodName
)
165 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
166 : ` ${logMsgPrefix} |`
167 return logPrefix(logMsg
)
170 private broadcastToClients (message
: string): void {
171 for (const client
of this.webSocketServer
.clients
) {
172 if (client
.readyState
=== WebSocket
.OPEN
) {
178 private validateRawDataRequest (rawData
: RawData
): ProtocolRequest
| false {
180 // `${this.logPrefix(
182 // 'validateRawDataRequest'
183 // // eslint-disable-next-line @typescript-eslint/no-base-to-string
184 // )} Raw data received in string format: ${rawData.toString()}`
187 let request
: ProtocolRequest
189 // eslint-disable-next-line @typescript-eslint/no-base-to-string
190 request
= JSON
.parse(rawData
.toString()) as ProtocolRequest
195 'validateRawDataRequest'
196 // eslint-disable-next-line @typescript-eslint/no-base-to-string
197 )} UI protocol request is not valid JSON: ${rawData.toString()}`
202 if (!Array.isArray(request
)) {
206 'validateRawDataRequest'
207 )} UI protocol request is not an array:`,
213 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
214 if (request
.length
!== 3) {
216 `${this.logPrefix(moduleName, 'validateRawDataRequest')} UI protocol request is malformed:`,
222 if (!validateUUID(request
[0])) {
226 'validateRawDataRequest'
227 )} UI protocol request UUID field is invalid:`,