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 const onSocketError
= (error
: Error): void => {
98 'start.httpServer.on.upgrade'
99 )} Socket error at connection upgrade event handling:`,
103 socket
.on('error', onSocketError
)
104 this.authenticate(req
, err
=> {
106 socket
.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`)
111 this.webSocketServer
.handleUpgrade(req
, socket
, head
, (ws
: WebSocket
) => {
112 this.webSocketServer
.emit('connection', ws
, req
)
118 'start.httpServer.on.upgrade'
119 )} Error at connection upgrade event handling:`,
124 socket
.removeListener('error', onSocketError
)
126 this.startHttpServer()
129 public sendRequest (request
: ProtocolRequest
): void {
130 this.broadcastToClients(JSON
.stringify(request
))
133 public sendResponse (response
: ProtocolResponse
): void {
134 const responseId
= response
[0]
136 if (this.hasResponseHandler(responseId
)) {
137 const ws
= this.responseHandlers
.get(responseId
) as WebSocket
138 if (ws
.readyState
=== WebSocket
.OPEN
) {
139 ws
.send(JSONStringifyWithMapSupport(response
))
145 )} Error at sending response id '${responseId}', WebSocket is not open: ${
155 )} Response for unknown request id: ${responseId}`
163 )} Error at sending response id '${responseId}':`,
167 this.responseHandlers
.delete(responseId
)
171 public logPrefix
= (modName
?: string, methodName
?: string, prefixSuffix
?: string): string => {
173 prefixSuffix
!= null ? `UI WebSocket Server ${prefixSuffix}` : 'UI WebSocket Server'
175 isNotEmptyString(modName
) && isNotEmptyString(methodName
)
176 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
177 : ` ${logMsgPrefix} |`
178 return logPrefix(logMsg
)
181 private broadcastToClients (message
: string): void {
182 for (const client
of this.webSocketServer
.clients
) {
183 if (client
.readyState
=== WebSocket
.OPEN
) {
189 private validateRawDataRequest (rawData
: RawData
): ProtocolRequest
| false {
191 // `${this.logPrefix(
193 // 'validateRawDataRequest'
194 // // eslint-disable-next-line @typescript-eslint/no-base-to-string
195 // )} Raw data received in string format: ${rawData.toString()}`
198 let request
: ProtocolRequest
200 // eslint-disable-next-line @typescript-eslint/no-base-to-string
201 request
= JSON
.parse(rawData
.toString()) as ProtocolRequest
206 'validateRawDataRequest'
207 // eslint-disable-next-line @typescript-eslint/no-base-to-string
208 )} UI protocol request is not valid JSON: ${rawData.toString()}`
213 if (!Array.isArray(request
)) {
217 'validateRawDataRequest'
218 )} UI protocol request is not an array:`,
224 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
225 if (request
.length
!== 3) {
227 `${this.logPrefix(moduleName, 'validateRawDataRequest')} UI protocol request is malformed:`,
233 if (!validateUUID(request
[0])) {
237 'validateRawDataRequest'
238 )} UI protocol request UUID field is invalid:`,