3x-ui/web/websocket/notifier.go
MHSanaei f4f0af576a
feat(ws): live updates on inbounds/xray/nodes pages, drop polling + manual refresh
Replaces the legacy polling + manual-refresh model with WebSocket pushes
across the three live-data pages. The hub already broadcast traffic /
client_stats / outbounds; this wires the frontend to consume them and
adds a new `nodes` channel for the heartbeat job's snapshot.

Frontend
- new useWebSocket composable: page-scoped singleton WebSocketClient,
  lifecycle-managed on/off, leaves disconnect to page-unload
- inbounds: useInbounds gains applyTrafficEvent / applyClientStatsEvent
  / applyInvalidate that merge counters and online/lastOnline in place;
  InboundsPage subscribes; InboundList drops the auto-refresh popover,
  the refresh button, and the now-unused refreshing prop
- xray outbounds: useXraySetting gains applyOutboundsEvent; XrayPage
  subscribes; OutboundsTab drops the refresh button + emit
- nodes: useNodes gains applyNodesEvent and stops the 5s
  setInterval/visibilitychange polling; NodesPage subscribes;
  NodeList drops the refresh button and ReloadOutlined import

Backend
- web/websocket: new MessageTypeNodes + BroadcastNodes notifier
- node_heartbeat_job: after wg.Wait(), reload the table once and
  BroadcastNodes(updated). Gated on websocket.HasClients() so a panel
  with no open browser doesn't spend the DB read

Bug fixes spotted in this pass
- websocket.js #buildUrl defaulted basePath to '' when the global was
  missing (dev mode), producing `ws://host:portws` and a SyntaxError
  on the WebSocket constructor. Fall back to '/' and ensure leading
  slash.
- vite.config.js: forward /ws to ws://localhost:2053 with ws:true so
  dev (5173) reaches the Go backend's WebSocket
- NodeFormModal: a-input-password's visibilityToggle is Boolean in
  AntD Vue 4; the v3-era object form (`{ visible, 'onUpdate:visible' }`)
  triggered a Vue prop-type warning. Drop the override (default true
  shows the eye icon and toggles internally) and remove the orphaned
  tokenVisible ref

Translations
- pages.inbounds.autoRefresh / autoRefreshInterval: removed from all
  13 locales (UI gone)
- pages.nodes.refresh: removed from all 13 locales (UI gone)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 17:30:31 +02:00

114 lines
3.3 KiB
Go

// Package websocket provides WebSocket hub for real-time updates and notifications.
package websocket
import (
"github.com/mhsanaei/3x-ui/v2/logger"
"github.com/mhsanaei/3x-ui/v2/web/global"
)
// GetHub returns the global WebSocket hub instance.
func GetHub() *Hub {
webServer := global.GetWebServer()
if webServer == nil {
return nil
}
hub := webServer.GetWSHub()
if hub == nil {
return nil
}
wsHub, ok := hub.(*Hub)
if !ok {
logger.Warning("WebSocket hub type assertion failed")
return nil
}
return wsHub
}
// HasClients returns true if any WebSocket client is connected.
// Use this to skip expensive work (DB queries, serialization) when no browser is open.
func HasClients() bool {
hub := GetHub()
return hub != nil && hub.GetClientCount() > 0
}
// BroadcastStatus broadcasts server status update to all connected clients.
func BroadcastStatus(status any) {
if hub := GetHub(); hub != nil {
hub.Broadcast(MessageTypeStatus, status)
}
}
// BroadcastTraffic broadcasts traffic statistics update to all connected clients.
func BroadcastTraffic(traffic any) {
if hub := GetHub(); hub != nil {
hub.Broadcast(MessageTypeTraffic, traffic)
}
}
// BroadcastClientStats broadcasts absolute per-client traffic counters for the
// clients that had activity in the latest collection window. Use this instead
// of re-broadcasting the full inbound list — it scales to 10k+ clients because
// the payload only includes active rows (typically a fraction of total).
func BroadcastClientStats(stats any) {
if hub := GetHub(); hub != nil {
hub.Broadcast(MessageTypeClientStats, stats)
}
}
// BroadcastInbounds broadcasts inbounds list update to all connected clients.
func BroadcastInbounds(inbounds any) {
if hub := GetHub(); hub != nil {
hub.Broadcast(MessageTypeInbounds, inbounds)
}
}
// BroadcastNodes broadcasts the fresh node list to all connected clients.
// Pushed by NodeHeartbeatJob at the end of each 10s tick so the Nodes page
// reflects status / latency / cpu / mem updates without polling.
func BroadcastNodes(nodes any) {
if hub := GetHub(); hub != nil {
hub.Broadcast(MessageTypeNodes, nodes)
}
}
// BroadcastOutbounds broadcasts outbounds list update to all connected clients.
func BroadcastOutbounds(outbounds any) {
if hub := GetHub(); hub != nil {
hub.Broadcast(MessageTypeOutbounds, outbounds)
}
}
// BroadcastNotification broadcasts a system notification to all connected clients.
func BroadcastNotification(title, message, level string) {
hub := GetHub()
if hub == nil {
return
}
hub.Broadcast(MessageTypeNotification, map[string]string{
"title": title,
"message": message,
"level": level,
})
}
// BroadcastXrayState broadcasts Xray state change to all connected clients.
func BroadcastXrayState(state string, errorMsg string) {
hub := GetHub()
if hub == nil {
return
}
hub.Broadcast(MessageTypeXrayState, map[string]string{
"state": state,
"errorMsg": errorMsg,
})
}
// BroadcastInvalidate sends a lightweight signal telling clients to re-fetch
// the named data type via REST. Use this when the caller already knows the
// payload is too large to push directly (e.g., 10k+ clients) to skip the
// JSON-marshal cost on the hot path.
func BroadcastInvalidate(dataType MessageType) {
if hub := GetHub(); hub != nil {
hub.broadcastInvalidate(dataType)
}
}