mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 00:15:09 +03:00
9f483d9465
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
193 lines
6.3 KiB
Go
193 lines
6.3 KiB
Go
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")
|
|
}
|
|
})
|
|
}
|
|
}
|