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'
10 type ProtocolResponse
,
11 type UIServerConfiguration
,
12 WebSocketCloseEventStatusCode
13 } from
'../../types/index.js'
16 getWebSocketCloseEventStatusString
,
22 } from
'../../utils/index.js'
23 import { AbstractUIServer
} from
'./AbstractUIServer.js'
25 getProtocolAndVersion
,
27 isProtocolAndVersionSupported
28 } from
'./UIServerUtils.js'
30 const moduleName
= 'UIWebSocketServer'
32 export class UIWebSocketServer
extends AbstractUIServer
{
33 private readonly webSocketServer
: WebSocketServer
35 public constructor (protected readonly uiServerConfiguration
: UIServerConfiguration
) {
36 super(uiServerConfiguration
)
37 this.webSocketServer
= new WebSocketServer({
43 public start (): void {
44 this.webSocketServer
.on('connection', (ws
: WebSocket
, _req
: IncomingMessage
): void => {
45 if (!isProtocolAndVersionSupported(ws
.protocol
)) {
49 'start.server.onconnection'
50 )} Unsupported UI protocol version: '${ws.protocol}'`
52 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_PROTOCOL_ERROR
)
54 const [, version
] = getProtocolAndVersion(ws
.protocol
)
55 this.registerProtocolVersionUIService(version
)
56 ws
.on('message', rawData
=> {
57 const request
= this.validateRawDataRequest(rawData
)
58 if (request
=== false) {
59 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_INVALID_PAYLOAD
)
62 const [requestId
] = request
63 this.responseHandlers
.set(requestId
, ws
)
66 ?.requestHandler(request
)
67 .then((protocolResponse
?: ProtocolResponse
) => {
68 if (protocolResponse
!= null) {
69 this.sendResponse(protocolResponse
)
72 .catch(Constants
.EMPTY_FUNCTION
)
74 ws
.on('error', error
=> {
75 logger
.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error
)
77 ws
.on('close', (code
, reason
) => {
82 )} WebSocket closed: '${getWebSocketCloseEventStatusString(
84 )}' - '${reason.toString()}'`
88 this.httpServer
.on('connect', (req
: IncomingMessage
, socket
: Duplex
, _head
: Buffer
) => {
89 if (req
.headers
.connection
!== 'Upgrade' || req
.headers
.upgrade
!== 'websocket') {
90 socket
.write(`HTTP/1.1 ${StatusCodes.BAD_REQUEST} Bad Request\r\n\r\n`)
94 this.httpServer
.on('upgrade', (req
: IncomingMessage
, socket
: Duplex
, head
: Buffer
): void => {
95 const onSocketError
= (error
: Error): void => {
99 'start.httpServer.on.upgrade'
100 )} Socket error at connection upgrade event handling:`,
104 socket
.on('error', onSocketError
)
105 this.authenticate(req
, err
=> {
107 socket
.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`)
112 this.webSocketServer
.handleUpgrade(req
, socket
, head
, (ws
: WebSocket
) => {
113 this.webSocketServer
.emit('connection', ws
, req
)
119 'start.httpServer.on.upgrade'
120 )} Error at connection upgrade event handling:`,
125 socket
.removeListener('error', onSocketError
)
127 this.startHttpServer()
130 public sendRequest (request
: ProtocolRequest
): void {
131 this.broadcastToClients(JSON
.stringify(request
))
134 public sendResponse (response
: ProtocolResponse
): void {
135 const responseId
= response
[0]
137 if (this.hasResponseHandler(responseId
)) {
138 const ws
= this.responseHandlers
.get(responseId
) as WebSocket
139 if (ws
.readyState
=== WebSocket
.OPEN
) {
140 ws
.send(JSONStringify(response
, undefined, MapStringifyFormat
.object
))
146 )} Error at sending response id '${responseId}', WebSocket is not open: ${
156 )} Response for unknown request id: ${responseId}`
164 )} Error at sending response id '${responseId}':`,
168 this.responseHandlers
.delete(responseId
)
172 public logPrefix
= (modName
?: string, methodName
?: string, prefixSuffix
?: string): string => {
174 prefixSuffix
!= null ? `UI WebSocket Server ${prefixSuffix}` : 'UI WebSocket Server'
176 isNotEmptyString(modName
) && isNotEmptyString(methodName
)
177 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
178 : ` ${logMsgPrefix} |`
179 return logPrefix(logMsg
)
182 private broadcastToClients (message
: string): void {
183 for (const client
of this.webSocketServer
.clients
) {
184 if (client
.readyState
=== WebSocket
.OPEN
) {
190 private validateRawDataRequest (rawData
: RawData
): ProtocolRequest
| false {
192 // `${this.logPrefix(
194 // 'validateRawDataRequest'
195 // // eslint-disable-next-line @typescript-eslint/no-base-to-string
196 // )} Raw data received in string format: ${rawData.toString()}`
199 let request
: ProtocolRequest
201 // eslint-disable-next-line @typescript-eslint/no-base-to-string
202 request
= JSON
.parse(rawData
.toString()) as ProtocolRequest
207 'validateRawDataRequest'
208 // eslint-disable-next-line @typescript-eslint/no-base-to-string
209 )} UI protocol request is not valid JSON: ${rawData.toString()}`
214 if (!Array.isArray(request
)) {
218 'validateRawDataRequest'
219 )} UI protocol request is not an array:`,
225 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
226 if (request
.length
!== 3) {
228 `${this.logPrefix(moduleName, 'validateRawDataRequest')} UI protocol request is malformed:`,
234 if (!validateUUID(request
[0])) {
238 'validateRawDataRequest'
239 )} UI protocol request UUID field is invalid:`,