diff --git a/frontend/src/api/websocketBridge.ts b/frontend/src/api/websocketBridge.ts index 9394398c8..b475a20a0 100644 --- a/frontend/src/api/websocketBridge.ts +++ b/frontend/src/api/websocketBridge.ts @@ -7,26 +7,27 @@ import { isRecentLocalInvalidate } from '@/api/invalidationTracker'; type Handler = (payload: unknown) => void; -let invalidateTimer: number | null = null; - export function useWebSocketBridge() { const queryClient = useQueryClient(); useEffect(() => { const client = getSharedWebSocketClient(); + const pendingInvalidations = new Set<'inbounds' | 'clients'>(); + let invalidateTimer: number | undefined; const onInvalidate: Handler = (payload) => { const p = payload as { type?: string } | undefined; if (!p || (p.type !== 'inbounds' && p.type !== 'clients')) return; - if (invalidateTimer != null) clearTimeout(invalidateTimer); + pendingInvalidations.add(p.type); + if (invalidateTimer !== undefined) return; invalidateTimer = window.setTimeout(() => { - invalidateTimer = null; - if (isRecentLocalInvalidate()) return; - if (p.type === 'inbounds') { - queryClient.invalidateQueries({ queryKey: ['inbounds'] }); - } else { - queryClient.invalidateQueries({ queryKey: ['clients'] }); + invalidateTimer = undefined; + if (!isRecentLocalInvalidate()) { + for (const type of pendingInvalidations) { + queryClient.invalidateQueries({ queryKey: keys[type].root() }); + } } + pendingInvalidations.clear(); }, 200); }; @@ -56,10 +57,7 @@ export function useWebSocketBridge() { client.off('outbounds', onOutbounds); client.off('nodes', onNodes); client.off('inbounds', onInbounds); - if (invalidateTimer != null) { - clearTimeout(invalidateTimer); - invalidateTimer = null; - } + clearTimeout(invalidateTimer); }; }, [queryClient]); } diff --git a/frontend/src/test/websocket-bridge-inbounds.test.tsx b/frontend/src/test/websocket-bridge-inbounds.test.tsx new file mode 100644 index 000000000..2849f27af --- /dev/null +++ b/frontend/src/test/websocket-bridge-inbounds.test.tsx @@ -0,0 +1,63 @@ +import { act, renderHook, waitFor } from '@testing-library/react'; +import { QueryClientProvider, useQuery } from '@tanstack/react-query'; +import type { ReactNode } from 'react'; +import { expect, it, vi } from 'vitest'; + +import { keys } from '@/api/queryKeys'; +import { getSharedWebSocketClient } from '@/api/websocket'; +import { useWebSocketBridge } from '@/api/websocketBridge'; + +import { makeTestQueryClient } from './test-utils'; + +it('refreshes inbounds and clients when a mutation invalidates both resources', async () => { + const sockets: EventTarget[] = []; + class FixtureSocket extends EventTarget { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + readyState = FixtureSocket.CONNECTING; + constructor() { + super(); + sockets.push(this); + } + close() {} + } + vi.stubGlobal('WebSocket', FixtureSocket); + const queryClient = makeTestQueryClient(); + let rows = [{ id: 1, remark: 'Before update' }]; + const fetchInbounds = vi.fn(async () => rows); + const fetchClients = vi.fn(async () => []); + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ); + const { result, unmount } = renderHook( + () => { + useWebSocketBridge(); + useQuery({ queryKey: keys.clients.all(), queryFn: fetchClients }); + return useQuery({ queryKey: keys.inbounds.slim(), queryFn: fetchInbounds }); + }, + { wrapper }, + ); + + try { + await waitFor(() => expect(result.current.data).toEqual(rows)); + const [connected] = sockets; + if (!connected) throw new Error('WebSocket was not connected'); + rows = [{ id: 1, remark: 'After update' }]; + act(() => { + for (const type of ['inbounds', 'inbounds', 'clients']) { + connected.dispatchEvent( + new MessageEvent('message', { + data: JSON.stringify({ type: 'invalidate', payload: { type } }), + }), + ); + } + }); + await waitFor(() => expect(result.current.data).toEqual(rows)); + expect(fetchInbounds).toHaveBeenCalledTimes(2); + expect(fetchClients).toHaveBeenCalledTimes(2); + } finally { + unmount(); + getSharedWebSocketClient().disconnect(); + vi.unstubAllGlobals(); + } +}); diff --git a/internal/web/controller/inbound.go b/internal/web/controller/inbound.go index ad4020ddf..f89aea5bb 100644 --- a/internal/web/controller/inbound.go +++ b/internal/web/controller/inbound.go @@ -39,18 +39,22 @@ func NewInboundController(g *gin.RouterGroup) *InboundController { // Mirrors the same heuristic used by the periodic traffic job. const broadcastInboundsUpdateClientLimit = 5000 -// broadcastInboundsUpdate fetches and broadcasts the inbound list for userId. -// At scale (10k+ clients) the marshaled JSON exceeds the WS payload ceiling, -// so we send an invalidate signal instead — frontend re-fetches via REST. -// Skipped entirely when no WebSocket clients are connected. +// broadcastInboundsUpdate sends either a small snapshot or an invalidate. +// Skip all snapshot work when no WebSocket clients are connected. func (a *InboundController) broadcastInboundsUpdate(userId int) { if !websocket.HasClients() { return } + overLimit, err := a.inboundService.InboundClientStatsOverLimit(userId, broadcastInboundsUpdateClientLimit) + if err != nil || overLimit { + websocket.BroadcastInvalidate(websocket.MessageTypeInbounds) + return + } inbounds, err := a.inboundService.GetInbounds(userId) if err != nil { return } + // Stats can grow between the probe and the snapshot read. totalClients := 0 for _, ib := range inbounds { totalClients += len(ib.ClientStats) diff --git a/internal/web/controller/inbound_broadcast_test.go b/internal/web/controller/inbound_broadcast_test.go new file mode 100644 index 000000000..9587de484 --- /dev/null +++ b/internal/web/controller/inbound_broadcast_test.go @@ -0,0 +1,192 @@ +package controller + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/robfig/cron/v3" + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/entity" + "github.com/mhsanaei/3x-ui/v3/internal/web/global" + "github.com/mhsanaei/3x-ui/v3/internal/web/session" + "github.com/mhsanaei/3x-ui/v3/internal/web/websocket" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +type inboundBroadcastServer struct{ hub *websocket.Hub } + +func (s inboundBroadcastServer) GetWSHub() any { return s.hub } +func (inboundBroadcastServer) GetCtx() context.Context { return context.Background() } +func (inboundBroadcastServer) GetCron() *cron.Cron { return nil } + +func TestInboundMutationSkipsSnapshotReadsAboveWebSocketCutoff(t *testing.T) { + dbtest.InitDB(t, filepath.Join(t.TempDir(), "panel.db")) + db := database.GetDB() + seed := func(userID, port, count int) model.Inbound { + t.Helper() + row := model.Inbound{UserId: userID, Port: port, Tag: fmt.Sprintf("in-%d", port), Protocol: model.VLESS, Settings: `{"clients":[],"decryption":"none"}`} + if err := db.Create(&row).Error; err != nil { + t.Fatal(err) + } + stats := make([]xray.ClientTraffic, count) + for i := range stats { + stats[i] = xray.ClientTraffic{InboundId: row.Id, Email: fmt.Sprintf("client-%d-%d", port, i)} + } + if count > 0 { + if err := db.CreateInBatches(&stats, 100).Error; err != nil { + t.Fatal(err) + } + } + return row + } + const limit = broadcastInboundsUpdateClientLimit + owned := seed(1, 29100, limit-1) + sibling := seed(1, 29101, 0) + seed(2, 29102, limit+1) + attach := func(inbound model.Inbound, statsIndex int) { + t.Helper() + row := model.ClientRecord{Email: fmt.Sprintf("client-%d-%d", owned.Port, statsIndex)} + if err := db.Create(&row).Error; err != nil { + t.Fatal(err) + } + link := model.ClientInbound{ClientId: row.Id, InboundId: inbound.Id} + if err := db.Create(&link).Error; err != nil { + t.Fatal(err) + } + } + attach(sibling, 0) + attach(owned, 1) + + snapshotReads, probes := 0, 0 + if err := db.Callback().Query().After("gorm:query").Register("test:inbound_snapshot", func(tx *gorm.DB) { + sql := tx.Statement.SQL.String() + if _, ok := tx.Statement.Dest.(*[]*model.Inbound); ok && + strings.Contains(sql, "WHERE user_id =") && strings.HasSuffix(sql, "ORDER BY id ASC") { + snapshotReads++ + } + }); err != nil { + t.Fatal(err) + } + if err := db.Callback().Row().After("gorm:row").Register("test:inbound_stats_probe", func(tx *gorm.DB) { + if strings.Contains(tx.Statement.SQL.String(), "AS candidate_stats") { + probes++ + } + }); err != nil { + t.Fatal(err) + } + + router := gin.New() + group := router.Group("/panel/api/inbounds", func(c *gin.Context) { + session.SetAPIAuthUser(c, &model.User{Id: 1}) + }) + NewInboundController(group) + previous := global.GetWebServer() + t.Cleanup(func() { global.SetWebServer(previous) }) + + for i, tc := range []struct { + name string + ws bool + wantType websocket.MessageType + reads int + prepare func() + }{ + {name: "no subscribers"}, + {name: "at cutoff with shared traffic and unrelated user", ws: true, wantType: websocket.MessageTypeInbounds, reads: 1}, + {name: "above cutoff from sibling counter", ws: true, wantType: websocket.MessageTypeInvalidate, prepare: func() { attach(sibling, 2) }}, + {name: "above cutoff from direct traffic", ws: true, wantType: websocket.MessageTypeInvalidate, prepare: func() { seed(1, 29110, 2) }}, + } { + t.Run(tc.name, func(t *testing.T) { + var subscriber *websocket.Client + if tc.ws { + hub := websocket.NewHub() + done := make(chan struct{}) + go func() { + defer close(done) + hub.Run() + }() + t.Cleanup(func() { hub.Stop(); <-done }) + global.SetWebServer(inboundBroadcastServer{hub}) + subscriber = websocket.NewClient("test") + hub.Register(subscriber) + for deadline := time.Now().Add(2 * time.Second); hub.GetClientCount() == 0; { + if time.Now().After(deadline) { + t.Fatal("subscriber did not register") + } + time.Sleep(time.Millisecond) + } + } else { + global.SetWebServer(nil) + } + if tc.prepare != nil { + tc.prepare() + } + snapshotReads, probes = 0, 0 + port := 29103 + i + body := fmt.Sprintf(`{"protocol":"vless","enable":false,"remark":"created","port":%d,"settings":"{\"clients\":[],\"decryption\":\"none\"}","streamSettings":"{\"network\":\"tcp\",\"security\":\"none\"}"}`, port) + req := httptest.NewRequest(http.MethodPost, "/panel/api/inbounds/add", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + var response entity.Msg + if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil || !response.Success { + t.Fatalf("add failed: %s (%v)", rec.Body, err) + } + if snapshotReads != tc.reads { + t.Errorf("full inbound snapshot reads = %d, want %d", snapshotReads, tc.reads) + } + wantProbes := 0 + if tc.ws { + wantProbes = 1 + } + if probes != wantProbes { + t.Errorf("snapshot size probes = %d, want %d", probes, wantProbes) + } + if subscriber == nil { + return + } + select { + case data := <-subscriber.Send: + var event struct { + Type websocket.MessageType + Payload json.RawMessage + } + if err := json.Unmarshal(data, &event); err != nil || event.Type != tc.wantType { + t.Fatalf("unexpected WebSocket type %q: %v, want %q", event.Type, err, tc.wantType) + } + if tc.wantType == websocket.MessageTypeInbounds { + var rows []model.Inbound + if err := json.Unmarshal(event.Payload, &rows); err != nil { + t.Fatal(err) + } + total, created := 0, false + for _, row := range rows { + if row.Port == 29102 { + t.Fatal("snapshot contains another user's inbound") + } + total += len(row.ClientStats) + created = created || row.Port == port + } + if !created || total != limit { + t.Fatalf("snapshot missing updated state: created=%t client stats=%d", created, total) + } + } else if string(event.Payload) != `{"type":"inbounds"}` { + t.Fatalf("unexpected invalidation payload %s", event.Payload) + } + case <-time.After(2 * time.Second): + t.Fatal("mutation did not publish an inbound event") + } + }) + } +} diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index 4761e279d..1d9c194db 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -199,6 +199,32 @@ func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) { return inbounds, nil } +// InboundClientStatsOverLimit probes direct stats and eligible sibling counters +// without fetching inbound settings or materializing stats. +func (s *InboundService) InboundClientStatsOverLimit(userID, limit int) (bool, error) { + var count int + // Exact email matches include every row eligible for backfill. Case folding + // can only reduce the number actually appended by backfillClientStats. + err := database.GetDB().Raw(` + SELECT COUNT(*) FROM ( + SELECT 1 + FROM inbounds AS ib + JOIN client_traffics AS stats ON stats.inbound_id = ib.id + WHERE ib.user_id = ? + UNION ALL + SELECT 1 + FROM inbounds AS ib + JOIN client_inbounds AS link ON link.inbound_id = ib.id + JOIN clients AS client ON client.id = link.client_id + JOIN client_traffics AS stats ON stats.email = client.email + WHERE ib.user_id = ? AND client.email <> '' + AND (stats.inbound_id <> ib.id OR stats.inbound_id IS NULL) + LIMIT ? + ) AS candidate_stats + `, userID, userID, limit+1).Row().Scan(&count) + return count > limit, err +} + func (s *InboundService) getInboundsFromDB(db *gorm.DB, userId int) ([]*model.Inbound, error) { var inbounds []*model.Inbound err := db.Model(model.Inbound{}).Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error