From c7c7584ab182bb132f3eb39e246412e315ff463b Mon Sep 17 00:00:00 2001 From: Sanaei Date: Wed, 25 Nov 2026 22:01:02 +0330 Subject: [PATCH] fix(inbounds): stop sending one UPDATE per client on an inbound save The inbound form cannot change clients, yet a save issued one client_traffics UPDATE for every client it kept. efb6c6d5 made those statements write nothing when the row already matched, but each one was still a round trip: 100,514 statements to save a 100,000-client inbound. On a remote PostgreSQL that is about a minute, past the 30 s the HTTP server allows a response, so the save looked failed after it committed. Read the kept clients' lifecycle columns in chunks, compare them in Go and send the guarded UPDATE only for the rows that differ, a NULL column included. The same save is now 764 statements. Against a running panel on PostgreSQL 16 with Xray 26.11.9 it went from 23.0 s to 5.9 s; what remains is decoding and rewriting the 29 MB settings value. Closes #7207 --- .../service/client_traffic_lifecycle_test.go | 64 +++++++++++++++++++ internal/web/service/inbound.go | 9 +-- internal/web/service/inbound_traffic.go | 47 ++++++++++++++ 3 files changed, 116 insertions(+), 4 deletions(-) diff --git a/internal/web/service/client_traffic_lifecycle_test.go b/internal/web/service/client_traffic_lifecycle_test.go index f1509de16..af2e3dbdb 100644 --- a/internal/web/service/client_traffic_lifecycle_test.go +++ b/internal/web/service/client_traffic_lifecycle_test.go @@ -4,6 +4,7 @@ import ( "errors" "os" "strings" + "sync/atomic" "testing" "github.com/jackc/pgx/v5/pgconn" @@ -26,6 +27,8 @@ func TestClientTrafficLifecyclePostgres(t *testing.T) { run func(*testing.T) }{ {"inbound save", TestInboundEditWritesOnlyDriftedTraffic}, + {"no update per unchanged client", TestInboundEditSendsNoUpdateForUnchangedClients}, + {"null lifecycle columns", TestInboundEditRepairsNullLifecycleColumns}, {"fields and errors", TestUpdateClientStatPreservesLifecycleAndCounters}, {"row locks", checkUpdateClientStatRowLocks}, {"one connection", TestUpdateClientTrafficsStaysOnOneConnection}, @@ -265,3 +268,64 @@ func checkUpdateClientStatRowLocks(t *testing.T) { }) } } + +// A form save cannot change clients, yet it sent one UPDATE per client it kept: on +// PostgreSQL a 100k-client inbound spent about a minute on them and the request died. +func TestInboundEditSendsNoUpdateForUnchangedClients(t *testing.T) { + setupBulkDB(t) + svc := &InboundService{} + clients := makeScaleClients(sqlInChunk + 1) + for i := range clients { + clients[i].TotalGB = 1 << 30 + } + ib := seedTrafficLifecycleInbound(t, svc, clients) + drifted := clients[len(clients)-1].Email + execLifecycleTestSQL(t, "UPDATE client_traffics SET total = 0 WHERE email = '"+drifted+"'") + + var updates atomic.Int64 + if err := database.GetDB().Callback().Update().After("gorm:update").Register("test:count_lifecycle_updates", func(tx *gorm.DB) { + if tx.Statement.Table == "client_traffics" { + updates.Add(1) + } + }); err != nil { + t.Fatal(err) + } + form := *ib + form.Remark = "edited" + if _, _, err := svc.UpdateInbound(&form); err != nil { + t.Fatal(err) + } + if got := updates.Load(); got != 1 { + t.Fatalf("save sent %d client_traffics UPDATEs for %d clients, want 1 for the drifted row", got, len(clients)) + } + if got := readClientTraffic(t, drifted).Total; got != 1<<30 { + t.Fatalf("drifted total = %d, want it repaired to %d", got, 1<<30) + } +} + +// NULL is not the zero the settings hold; the row comparison must still call it drift. +func TestInboundEditRepairsNullLifecycleColumns(t *testing.T) { + setupBulkDB(t) + svc := &InboundService{} + columns := []string{"enable", "expiry_time", "total", "reset", "reset_day", "reset_max", "reset_weekday"} + clients := makeScaleClients(len(columns)) + ib := seedTrafficLifecycleInbound(t, svc, clients) + for i, column := range columns { + execLifecycleTestSQL(t, "UPDATE client_traffics SET "+column+" = NULL WHERE email = '"+clients[i].Email+"'") + } + form := *ib + form.Remark = "edited" + if _, _, err := svc.UpdateInbound(&form); err != nil { + t.Fatal(err) + } + for i, column := range columns { + var nulls int64 + if err := database.GetDB().Model(xray.ClientTraffic{}). + Where("email = ? AND "+column+" IS NULL", clients[i].Email).Count(&nulls).Error; err != nil { + t.Fatal(err) + } + if nulls != 0 { + t.Errorf("a NULL %s survived the save", column) + } + } +} diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index 1243ceba6..2faf2144b 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -2655,22 +2655,23 @@ func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inb return err } } + keptEmails := make([]string, 0, len(newClients)) + keptClients := make(map[string]*model.Client, len(newClients)) for i := range newClients { email := newClients[i].Email if email == "" { continue } if _, existed := oldEmails[email]; existed { - if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil { - return err - } + keptEmails = append(keptEmails, email) + keptClients[email] = &newClients[i] continue } if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil { return err } } - return nil + return s.updateDriftedClientStats(tx, keptEmails, keptClients) } func (s *InboundService) GetInboundTags() (string, error) { diff --git a/internal/web/service/inbound_traffic.go b/internal/web/service/inbound_traffic.go index be41c96c4..bf84b0787 100644 --- a/internal/web/service/inbound_traffic.go +++ b/internal/web/service/inbound_traffic.go @@ -684,6 +684,53 @@ func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *mod }).Error } +// storedClientLifecycle is the part of a client_traffics row its client's settings +// decide. A nil field is a NULL, which no configured value equals. +type storedClientLifecycle struct { + Email string + Enable *bool + ExpiryTime *int64 + Total *int64 + Reset *int + ResetDay *int + ResetMax *int + ResetWeekday *int +} + +func (row *storedClientLifecycle) holds(client *model.Client) bool { + return row.Enable != nil && *row.Enable == client.Enable && + row.ExpiryTime != nil && *row.ExpiryTime == client.ExpiryTime && + row.Total != nil && *row.Total == client.TotalGB && + row.Reset != nil && *row.Reset == client.Reset && + row.ResetDay != nil && *row.ResetDay == client.ResetDay && + row.ResetMax != nil && *row.ResetMax == client.ResetMax && + row.ResetWeekday != nil && *row.ResetWeekday == client.ResetWeekday +} + +// updateDriftedClientStats reads the rows a chunk at a time and rewrites only those that +// differ: one statement per kept client made saving a 100k-client inbound take a minute. +func (s *InboundService) updateDriftedClientStats(tx *gorm.DB, emails []string, clients map[string]*model.Client) error { + for _, batch := range chunkStrings(emails, sqlInChunk) { + var rows []storedClientLifecycle + if err := tx.Model(xray.ClientTraffic{}). + Select("email", "enable", "expiry_time", "total", "reset", "reset_day", "reset_max", "reset_weekday"). + Where("email IN ?", batch). + Find(&rows).Error; err != nil { + return err + } + for i := range rows { + client := clients[rows[i].Email] + if client == nil || rows[i].holds(client) { + continue + } + if err := s.UpdateClientStat(tx, rows[i].Email, client); err != nil { + return err + } + } + } + return nil +} + func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error { if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{email}); err != nil { return err