From e1d30ce5dc76eebbb48fcf051f3ac2a2e3aefb15 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Wed, 25 Nov 2026 22:00:56 +0330 Subject: [PATCH] fix(traffic): keep counting past the SQL bind-variable limit Xray creates a client's counters on its first connection and reports every one of them on each poll, whether it moved bytes or not. The poll looked them all up in one IN list, so once more clients had connected since the core started than a statement can bind (32,766 on SQLite, 65,535 on PostgreSQL) every poll failed: no client was counted and no quota or expiry was enforced until Xray restarted and its counters started over. Two more statements bound one variable per client of an inbound. The TUIC traffic-id lookup failed the runtime build of a large TUIC inbound. The node sync's comment lookup failed silently, so a node's snapshot blanked the hub's comment on every client of a large inbound. All three read in chunks now. Refs #7207 --- internal/web/service/global_traffic_test.go | 107 ++++++++++++++++++++ internal/web/service/inbound.go | 14 +-- internal/web/service/inbound_node.go | 25 ++--- internal/web/service/inbound_traffic.go | 15 +-- 4 files changed, 137 insertions(+), 24 deletions(-) diff --git a/internal/web/service/global_traffic_test.go b/internal/web/service/global_traffic_test.go index b195f7cdd..39da57c28 100644 --- a/internal/web/service/global_traffic_test.go +++ b/internal/web/service/global_traffic_test.go @@ -1,6 +1,8 @@ package service import ( + "encoding/json" + "fmt" "strings" "testing" "time" @@ -355,3 +357,108 @@ func TestDisableInvalidClientsSurvivesAnInboundWithBrokenSettings(t *testing.T) t.Fatalf("local inbound settings = %s, want bob disabled", bob.Settings) } } + +// Xray reports every email that ever connected, moved bytes or not; one IN list over all +// of them overran the bind limit and no client was counted until the core restarted. +func TestAddTrafficPastTheSQLVariableLimit(t *testing.T) { + db := initTrafficTestDB(t) + seedClientRow(t, "alice", 1, 10, 20, 0) + const n = 33000 + report := make([]*xray.ClientTraffic, 0, n+1) + for i := range n { + report = append(report, &xray.ClientTraffic{Email: fmt.Sprintf("idle-%d", i)}) + } + report = append(report, &xray.ClientTraffic{Email: "alice", Up: 5, Down: 7}) + if _, _, err := (&InboundService{}).AddTraffic(nil, report); err != nil { + t.Fatalf("AddTraffic with %d reported emails: %v", len(report), err) + } + assertUpDown(t, readTraffic(t, db, "alice"), 15, 27, "after a poll reporting more emails than one statement binds") +} + +// The TUIC sidecar meters by traffic_id; one IN list over a large inbound's emails +// overran the bind limit and the inbound could no longer be built for the runtime. +func TestTuicRuntimeInboundPastTheSQLVariableLimit(t *testing.T) { + db := initTrafficTestDB(t) + const n = 33000 + var settings strings.Builder + settings.WriteString(`{"clients":[`) + for i := 1; i <= n; i++ { + if i > 1 { + settings.WriteByte(',') + } + fmt.Fprintf(&settings, `{"email":"c%d","id":"00000000-0000-4000-8000-%012d","password":"p","enable":true}`, i, i) + } + settings.WriteString(`]}`) + inbound := &model.Inbound{UserId: 1, Tag: "tuic-big", Port: 41300, Protocol: model.TUIC, Enable: true, Settings: settings.String()} + if err := db.Create(inbound).Error; err != nil { + t.Fatalf("seed inbound: %v", err) + } + if err := db.Exec(`WITH RECURSIVE seq(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM seq WHERE i < ?) + INSERT INTO client_traffics (inbound_id, email, enable) SELECT 1, 'c' || i, true FROM seq`, n).Error; err != nil { + t.Fatalf("seed traffic rows: %v", err) + } + built, err := (&InboundService{}).buildInboundForLocalRuntime(db, inbound) + if err != nil { + t.Fatalf("buildInboundForLocalRuntime: %v", err) + } + var runtimeSettings struct { + Clients []struct { + Email string `json:"email"` + TrafficID int `json:"traffic_id"` + } `json:"clients"` + } + if err := json.Unmarshal([]byte(built.Settings), &runtimeSettings); err != nil { + t.Fatalf("decode runtime settings: %v", err) + } + if len(runtimeSettings.Clients) != n { + t.Fatalf("runtime inbound has %d clients, want %d", len(runtimeSettings.Clients), n) + } + last := runtimeSettings.Clients[n-1] + if want := readTraffic(t, db, last.Email).Id; last.TrafficID != want { + t.Fatalf("%s traffic_id = %d, want its stats row id %d", last.Email, last.TrafficID, want) + } +} + +// A node's snapshot carries no comments; one IN list over a large inbound's emails +// overran the bind limit and the lookup that keeps the hub's comments was skipped. +func TestNodeSnapshotKeepsCommentsPastTheSQLVariableLimit(t *testing.T) { + db := initTrafficTestDB(t) + seedNodeRow(t, db, &model.Node{Id: 1, Name: "n1", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true}) + const n = 33000 + var central, reported strings.Builder + central.WriteString(`{"clients":[`) + reported.WriteString(`{"clients":[`) + for i := 1; i <= n; i++ { + if i > 1 { + central.WriteByte(',') + reported.WriteByte(',') + } + fmt.Fprintf(¢ral, `{"email":"c%d","id":"00000000-0000-4000-8000-%012d","enable":true,"comment":"note %d"}`, i, i, i) + fmt.Fprintf(&reported, `{"email":"c%d","id":"00000000-0000-4000-8000-%012d","enable":true}`, i, i) + } + central.WriteString(`]}`) + reported.WriteString(`]}`) + createNodeInboundWithSettings(t, db, 1, "n1-big", 41301, central.String()) + for _, stmt := range []string{ + `WITH RECURSIVE seq(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM seq WHERE i < ?) + INSERT INTO clients (email, uuid, enable, sub_id, comment) + SELECT 'c' || i, '00000000-0000-4000-8000-' || printf('%012d', i), true, '', 'note ' || i FROM seq`, + } { + if err := db.Exec(stmt, n).Error; err != nil { + t.Fatalf("seed clients: %v", err) + } + } + if err := db.Exec(`INSERT INTO client_inbounds (client_id, inbound_id) SELECT id, 1 FROM clients`).Error; err != nil { + t.Fatalf("link clients: %v", err) + } + + syncNodeWithSettings(t, &InboundService{}, 1, "n1-big", reported.String()) + + var row model.ClientRecord + if err := db.Where("email = ?", fmt.Sprintf("c%d", n)).First(&row).Error; err != nil { + t.Fatalf("lookup client: %v", err) + } + if want := fmt.Sprintf("note %d", n); row.Comment != want { + t.Fatalf("comment after the node sync = %q, want %q", row.Comment, want) + } +} diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index 053fef57a..1243ceba6 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -2551,12 +2551,14 @@ func (s *InboundService) stripDisabledClients(tx *gorm.DB, inbound *model.Inboun trafficIDs := make(map[string]int) if inbound.Protocol == model.TUIC { - var rows []xray.ClientTraffic - if err := tx.Select("id", "email").Where("email IN ?", emails).Find(&rows).Error; err != nil { - return nil, err - } - for _, row := range rows { - trafficIDs[row.Email] = row.Id + for _, batch := range chunkStrings(emails, sqlInChunk) { + var rows []xray.ClientTraffic + if err := tx.Select("id", "email").Where("email IN ?", batch).Find(&rows).Error; err != nil { + return nil, err + } + for _, row := range rows { + trafficIDs[row.Email] = row.Id + } } } finalClients := make([]any, 0, len(clients)) diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index 4259005a9..d465b57ba 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -1405,24 +1405,25 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi localEmails = append(localEmails, filtered[i].Email) } } - if len(localEmails) > 0 { + commentByEmail := make(map[string]string, len(localEmails)) + for _, batch := range chunkStrings(localEmails, sqlInChunk) { var localMeta []struct { Email string Comment string `gorm:"column:comment"` } if err := tx.Table("clients"). Select("email, comment"). - Where("email IN ?", localEmails). - Find(&localMeta).Error; err == nil { - commentByEmail := make(map[string]string, len(localMeta)) - for _, m := range localMeta { - commentByEmail[m.Email] = m.Comment - } - for i := range filtered { - if cmt, ok := commentByEmail[filtered[i].Email]; ok { - filtered[i].Comment = cmt - } - } + Where("email IN ?", batch). + Find(&localMeta).Error; err != nil { + continue + } + for _, m := range localMeta { + commentByEmail[m.Email] = m.Comment + } + } + for i := range filtered { + if cmt, ok := commentByEmail[filtered[i].Email]; ok { + filtered[i].Comment = cmt } } if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil { diff --git a/internal/web/service/inbound_traffic.go b/internal/web/service/inbound_traffic.go index e03458a31..be41c96c4 100644 --- a/internal/web/service/inbound_traffic.go +++ b/internal/web/service/inbound_traffic.go @@ -1,6 +1,7 @@ package service import ( + "cmp" "context" "encoding/json" "errors" @@ -153,13 +154,15 @@ func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTr // shared row then carried the node inbound's id (AddClientStat used to use // OnConflict DoNothing and never refreshed it; it now refreshes inbound_id on // conflict, but this filter was removed rather than relying on that ordering). - err = tx.Model(xray.ClientTraffic{}). - Where("email IN (?)", emails). - Order("id"). - Find(&dbClientTraffics).Error - if err != nil { - return err + for _, batch := range chunkStrings(emails, sqlInChunk) { + var page []*xray.ClientTraffic + if err = tx.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil { + return err + } + dbClientTraffics = append(dbClientTraffics, page...) } + // One id order across the chunks keeps the row UPDATEs below lock-compatible. + slices.SortFunc(dbClientTraffics, func(a, b *xray.ClientTraffic) int { return cmp.Compare(a.Id, b.Id) }) // Avoid empty slice error if len(dbClientTraffics) == 0 {