fix(inbounds): check WebSocket snapshot size before loading (#7309)

Avoid materializing full inbound settings and client statistics only to discard the snapshot above the existing 5,000-row WebSocket cutoff. Probe user-scoped direct and sibling-backed traffic rows with bounded SQL before loading the snapshot; skip work without subscribers, fall back to invalidation on probe failure, and retain the post-read guard for concurrent growth.

Coalesce WebSocket invalidations by resource in a 200 ms window so paired Inbounds and Clients events refresh both query roots without duplicate same-resource refetches.

Regression coverage exercises the real inbound mutation route and WebSocket hub at and above the cutoff, shared traffic, user scoping, no subscribers, and frontend paired invalidations. All 12 CI jobs passed on the reviewed PR head. The author also reports SQLite/PostgreSQL 16 validation and make verify. Static review of the current merge candidate found no overlapping file changes with main; CI on that exact combined revision was not independently run before merge.

The reported synthetic SQLite notification benchmark (30 inbounds, 7,101 clients, 115,041 associations) improved from 323.87 ms to 0.24 ms and from 324,751,126 to 5,393 allocated bytes per operation. These figures do not establish production HTTP or browser latency improvements.

Fixes #7297
This commit is contained in:
Hamed
2026-12-02 12:30:15 +03:30
committed by GitHub
parent b2d7a9bb08
commit 9f483d9465
5 changed files with 300 additions and 17 deletions
+11 -13
View File
@@ -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]);
}
@@ -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 }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
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();
}
});
+8 -4
View File
@@ -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)
@@ -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")
}
})
}
}
+26
View File
@@ -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