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 getWebSocketCloseEventStatusString
,
22 } from
'../../utils/index.js'
24 const moduleName
= 'UIWebSocketServer'
26 export class UIWebSocketServer
extends AbstractUIServer
{
27 private readonly webSocketServer
: WebSocketServer
29 public constructor (protected readonly uiServerConfiguration
: UIServerConfiguration
) {
30 super(uiServerConfiguration
)
31 this.webSocketServer
= new WebSocketServer({
32 handleProtocols
: UIServerUtils
.handleProtocols
,
37 public start (): void {
38 this.webSocketServer
.on('connection', (ws
: WebSocket
, _req
: IncomingMessage
): void => {
39 if (!UIServerUtils
.isProtocolAndVersionSupported(ws
.protocol
)) {
43 'start.server.onconnection'
44 )} Unsupported UI protocol version: '${ws.protocol}'`
46 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_PROTOCOL_ERROR
)
48 const [, version
] = UIServerUtils
.getProtocolAndVersion(ws
.protocol
)
49 this.registerProtocolVersionUIService(version
)
50 ws
.on('message', (rawData
) => {
51 const request
= this.validateRawDataRequest(rawData
)
52 if (request
=== false) {
53 ws
.close(WebSocketCloseEventStatusCode
.CLOSE_INVALID_PAYLOAD
)
56 const [requestId
] = request
57 this.responseHandlers
.set(requestId
, ws
)
60 ?.requestHandler(request
)
61 .then((protocolResponse
?: ProtocolResponse
) => {
62 if (protocolResponse
!= null) {
63 this.sendResponse(protocolResponse
)
66 .catch(Constants
.EMPTY_FUNCTION
)
68 ws
.on('error', (error
) => {
69 logger
.error(`${this.logPrefix(moduleName, 'start.ws.onerror')} WebSocket error:`, error
)
71 ws
.on('close', (code
, reason
) => {
76 )} WebSocket closed: '${getWebSocketCloseEventStatusString(
78 )}' - '${reason.toString()}'`
82 this.httpServer
.on('connect', (req
: IncomingMessage
, socket
: Duplex
, _head
: Buffer
) => {
83 if (req
.headers
.connection
!== 'Upgrade' || req
.headers
.upgrade
!== 'websocket') {
84 socket
.write(`HTTP/1.1 ${StatusCodes.BAD_REQUEST} Bad Request\r\n\r\n`)
88 this.httpServer
.on('upgrade', (req
: IncomingMessage
, socket
: Duplex
, head
: Buffer
): void => {
89 this.authenticate(req
, (err
) => {
91 socket
.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`)
96 this.webSocketServer
.handleUpgrade(req
, socket
, head
, (ws
: WebSocket
) => {
97 this.webSocketServer
.emit('connection', ws
, req
)
103 'start.httpServer.on.upgrade'
104 )} Error at handling connection upgrade:`,
110 this.startHttpServer()
113 public sendRequest (request
: ProtocolRequest
): void {
114 this.broadcastToClients(JSON
.stringify(request
))
117 public sendResponse (response
: ProtocolResponse
): void {
118 const responseId
= response
[0]
120 if (this.hasResponseHandler(responseId
)) {
121 const ws
= this.responseHandlers
.get(responseId
) as WebSocket
122 if (ws
.readyState
=== WebSocket
.OPEN
) {
123 ws
.send(JSON
.stringify(response
))
129 )} Error at sending response id '${responseId}', WebSocket is not open: ${
139 )} Response for unknown request id: ${responseId}`
147 )} Error at sending response id '${responseId}':`,
151 this.responseHandlers
.delete(responseId
)
155 public logPrefix
= (modName
?: string, methodName
?: string, prefixSuffix
?: string): string => {
157 prefixSuffix
!= null ? `UI WebSocket Server ${prefixSuffix}` : 'UI WebSocket Server'
159 isNotEmptyString(modName
) && isNotEmptyString(methodName
)
160 ? ` ${logMsgPrefix} | ${modName}.${methodName}:`
161 : ` ${logMsgPrefix} |`
162 return logPrefix(logMsg
)
165 private broadcastToClients (message
: string): void {
166 for (const client
of this.webSocketServer
.clients
) {
167 if (client
.readyState
=== WebSocket
.OPEN
) {
173 private validateRawDataRequest (rawData
: RawData
): ProtocolRequest
| false {
175 // `${this.logPrefix(
177 // 'validateRawDataRequest'
178 // // eslint-disable-next-line @typescript-eslint/no-base-to-string
179 // )} Raw data received in string format: ${rawData.toString()}`
182 // eslint-disable-next-line @typescript-eslint/no-base-to-string
183 const request
= JSON
.parse(rawData
.toString()) as ProtocolRequest
185 if (!Array.isArray(request
)) {
189 'validateRawDataRequest'
190 )} UI protocol request is not an array:`,
196 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
197 if (request
.length
!== 3) {
199 `${this.logPrefix(moduleName, 'validateRawDataRequest')} UI protocol request is malformed:`,
205 if (!validateUUID(request
[0])) {
209 'validateRawDataRequest'
210 )} UI protocol request UUID field is invalid:`,