From 263f9c1ed443cd8d5d62da5608f35883eaf74dab Mon Sep 17 00:00:00 2001 From: Hamed Sanaei Date: Mon, 30 Nov 2026 21:36:31 +0330 Subject: [PATCH] perf(clients): avoid repeated inbound settings reads Project only the inbound fields and protocol defaults needed to prepare a create. Validate flow against the locked apply snapshot, and reuse that snapshot for add and update until the transactional rebase guard. --- .../web/service/client_create_reads_test.go | 174 ++++++++++++++++++ internal/web/service/client_crud.go | 27 ++- internal/web/service/client_inbound_apply.go | 27 +-- 3 files changed, 210 insertions(+), 18 deletions(-) create mode 100644 internal/web/service/client_create_reads_test.go diff --git a/internal/web/service/client_create_reads_test.go b/internal/web/service/client_create_reads_test.go new file mode 100644 index 000000000..283c7cc83 --- /dev/null +++ b/internal/web/service/client_create_reads_test.go @@ -0,0 +1,174 @@ +package service + +import ( + "encoding/hex" + "fmt" + "slices" + "strings" + "sync" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +type inboundSettingsReads struct { + mu sync.Mutex + sizes []int +} + +func trackInboundSettingsReads(t testing.TB) *inboundSettingsReads { + t.Helper() + reads := &inboundSettingsReads{} + query := database.GetDB().Callback().Query() + const name = "test:track_client_inbound_settings" + if err := query.After("gorm:query").Register(name, func(tx *gorm.DB) { + if tx.Statement.Table != "inbounds" || tx.Error != nil { + return + } + projection, _, _ := strings.Cut(tx.Statement.SQL.String(), " FROM ") + if !strings.Contains(projection, "settings") && !strings.Contains(projection, "*") { + return + } + reads.mu.Lock() + defer reads.mu.Unlock() + switch dest := tx.Statement.Dest.(type) { + case *model.Inbound: + reads.sizes = append(reads.sizes, len(dest.Settings)) + case *[]string: + for _, settings := range *dest { + reads.sizes = append(reads.sizes, len(settings)) + } + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := query.Remove(name); err != nil { + t.Error(err) + } + }) + return reads +} + +func seedInboundSettingsReadTest(t *testing.T, port int, protocol model.Protocol, settings string) *model.Inbound { + t.Helper() + ib := &model.Inbound{Tag: fmt.Sprintf("settings-reads-%d", port), Enable: true, Port: port, Protocol: protocol, Settings: settings} + if err := database.GetDB().Create(ib).Error; err != nil { + t.Fatal(err) + } + return ib +} + +func TestClientCreateReadsInboundSettingsOnlyForMutation(t *testing.T) { + setupBulkDB(t) + const flow = "xtls-rprx-vision" + ib := seedInboundSettingsReadTest(t, 23121, model.VLESS, `{"clients":[],"decryption":"mlkem768x25519plus.native.0rtt.test"}`) + reads := trackInboundSettingsReads(t) + + if _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{ + InboundIds: []int{ib.Id}, + Client: model.Client{Email: "create-reads@example.test", Flow: flow}, + }); err != nil { + t.Fatal(err) + } + want := []int{0, len(ib.Settings), len(ib.Settings)} + if !slices.Equal(reads.sizes, want) { + t.Fatalf("inbound settings bytes by read = %v, want %v (preparation, locked read, transaction guard)", reads.sizes, want) + } + if client, found := settingsClient(t, ib.Id, "create-reads@example.test"); !found || client.Flow != flow { + t.Fatalf("encrypted VLESS inbound saved flow %q, want %q", client.Flow, flow) + } +} + +func TestClientCreateClearsFlowOnIneligibleInbound(t *testing.T) { + setupBulkDB(t) + ib := seedInboundSettingsReadTest(t, 23123, model.VLESS, `{"clients":[],"decryption":"none"}`) + if _, err := (&ClientService{}).CreateOne(&InboundService{}, ib.Id, model.Client{ + Email: "create-noflow@example.test", Flow: "xtls-rprx-vision", + }); err != nil { + t.Fatal(err) + } + if client, found := settingsClient(t, ib.Id, "create-noflow@example.test"); !found || client.Flow != "" { + t.Fatalf("ineligible VLESS inbound has client=%v with flow %q, want client without flow", found, client.Flow) + } +} + +func TestClientCreatePreservesSettingsBasedDefaults(t *testing.T) { + setupBulkDB(t) + const method = "2022-blake3-aes-256-gcm" + const domain = "front.example.test" + ss := seedInboundSettingsReadTest(t, 23124, model.Shadowsocks, `{"clients":[],"method":"`+method+`","password":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="}`) + mt := seedInboundSettingsReadTest(t, 23125, model.MTProto, `{"clients":[],"fakeTlsDomain":"`+domain+`"}`) + const email = "create-defaults@example.test" + if _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{ + InboundIds: []int{ss.Id, mt.Id}, + Client: model.Client{Email: email}, + }); err != nil { + t.Fatal(err) + } + if client, found := settingsClient(t, ss.Id, email); !found || !validShadowsocksClientKey(method, client.Password) { + t.Fatalf("Shadowsocks client found=%v, want a valid %s key", found, method) + } + if client, found := settingsClient(t, mt.Id, email); !found || !model.ValidMtprotoSecret(client.Secret) || + !strings.HasSuffix(client.Secret, hex.EncodeToString([]byte(domain))) { + t.Fatalf("MTProto client found=%v, want a valid FakeTLS secret for %s", found, domain) + } +} + +func TestUpdateInboundClientReadsSettingsOnceBeforeCommit(t *testing.T) { + setupBulkDB(t) + svc, inbounds := &ClientService{}, &InboundService{} + client := model.Client{Email: "update-reads@example.test", ID: "225452da-1385-4a1c-84ab-05481e000001", SubID: "update-reads"} + ib := seedInboundSettingsReadTest(t, 23122, model.VLESS, clientsSettings(t, []model.Client{client})) + if err := svc.SyncInbound(nil, ib.Id, []model.Client{client}); err != nil { + t.Fatal(err) + } + reads := trackInboundSettingsReads(t) + + client.Comment = "changed" + if _, err := svc.UpdateInboundClient(inbounds, &model.Inbound{ + Id: ib.Id, Settings: clientsSettings(t, []model.Client{client}), + }, client.Email); err != nil { + t.Fatal(err) + } + want := []int{len(ib.Settings), len(ib.Settings)} + if !slices.Equal(reads.sizes, want) { + t.Fatalf("inbound settings bytes by read = %v, want %v (locked read, transaction guard)", reads.sizes, want) + } +} + +func BenchmarkClientCreateLargeInboundSettings(b *testing.B) { + setupScaleDB(b) + const inbounds, clientsPerInbound = 11, 4000 + data := seedScaleDataset(b, inbounds*clientsPerInbound, inbounds) + svc, inboundSvc := &ClientService{}, &InboundService{} + reads := trackInboundSettingsReads(b) + var times []time.Duration + for b.Loop() { + payload := &ClientCreatePayload{ + InboundIds: data.inboundIds, + Client: model.Client{Email: fmt.Sprintf("add-%d@example.test", len(times))}, + } + start := time.Now() + if _, err := svc.Create(inboundSvc, payload); err != nil { + b.Fatal(err) + } + times = append(times, time.Since(start)) + } + slices.Sort(times) + b.ReportMetric(float64(times[(95*len(times)+99)/100-1].Microseconds())/1000, "p95-ms") + bytes, blobs := 0, 0 + for _, size := range reads.sizes { + bytes += size + if size > 0 { + blobs++ + } + } + b.ReportMetric(float64(len(reads.sizes))/float64(b.N), "inbound-projections/op") + b.ReportMetric(float64(bytes)/float64(b.N), "settings-bytes/op") + b.ReportMetric(float64(blobs)/float64(b.N), "settings-reads/op") +} diff --git a/internal/web/service/client_crud.go b/internal/web/service/client_crud.go index 3646889e0..147737b0e 100644 --- a/internal/web/service/client_crud.go +++ b/internal/web/service/client_crud.go @@ -289,7 +289,7 @@ func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreate // shared credentials on the first inbound and every later one reuses them. adds := make([]*model.Inbound, 0, len(payload.InboundIds)) for _, ibId := range payload.InboundIds { - inbound, getErr := inboundSvc.GetInbound(ibId) + inbound, getErr := getInboundForClientCreate(ibId, client.Secret == "") if getErr != nil { return false, fmt.Errorf("inbound %d: %w", ibId, getErr) } @@ -311,7 +311,7 @@ func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreate if err := validateAmneziaWGClientWrite(inbound, []model.Client{clientForInbound}, ""); err != nil { return false, fmt.Errorf("inbound %d: %w", ibId, err) } - settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(clientForInbound, inbound)}}) + settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientForInbound}}) if mErr != nil { return false, fmt.Errorf("inbound %d: %w", ibId, mErr) } @@ -334,6 +334,23 @@ func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreate return needRestart, s.setClientLimitHwidByEmail(client.Email, payload.LimitHwid) } +// getInboundForClientCreate returns the settings blob only for protocols +// that need it to prepare the client before any writes. +func getInboundForClientCreate(id int, generateSecret bool) (*model.Inbound, error) { + protocolsWithSettings := []model.Protocol{model.Shadowsocks, model.AmneziaWG} + if generateSecret { + protocolsWithSettings = append(protocolsWithSettings, model.MTProto) + } + var inbound model.Inbound + if err := database.GetDB().Select( + "id, protocol, enable, listen, CASE WHEN protocol IN ? THEN settings ELSE '' END AS settings", + protocolsWithSettings, + ).First(&inbound, id).Error; err != nil { + return nil, err + } + return &inbound, nil +} + // inboundFanoutConcurrency caps how many inbounds one client op applies at // once, so a client spanning many of them can't start an unbounded RPC burst. const inboundFanoutConcurrency = 4 @@ -382,12 +399,12 @@ func fanoutInboundApplies(applies []inboundApply) (bool, error) { return needRestart.Load(), errors.Join(errs...) } -// fanoutInboundClientAdds applies one payload per inbound. +// fanoutInboundClientAdds applies the prepared create or attach to each inbound. func (s *ClientService) fanoutInboundClientAdds(inboundSvc *InboundService, adds []*model.Inbound) (bool, error) { applies := make([]inboundApply, 0, len(adds)) for _, add := range adds { applies = append(applies, inboundApply{id: add.Id, run: func() (bool, error) { - return s.AddInboundClient(inboundSvc, add) + return s.addInboundClient(inboundSvc, add, true) }}) } return fanoutInboundApplies(applies) @@ -1267,7 +1284,7 @@ func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds [] if err := s.fillProtocolDefaults(©Client, inbound); err != nil { return false, fmt.Errorf("inbound %d: %w", ibId, err) } - settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(copyClient, inbound)}}) + settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {copyClient}}) if mErr != nil { return false, fmt.Errorf("inbound %d: %w", ibId, mErr) } diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go index 6a1c4842c..abb33309f 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -405,6 +405,10 @@ func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, c } func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) { + return s.addInboundClient(inboundSvc, data, false) +} + +func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model.Inbound, gateFlow bool) (bool, error) { defer InvalidateSubData() lock := lockInbound(data.Id) defer lock.Unlock() @@ -416,15 +420,15 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model if err := validateClientsRenewal(clients); err != nil { return false, err } - inbound, err := inboundSvc.GetInbound(data.Id) + oldInbound, err := inboundSvc.GetInbound(data.Id) if err != nil { return false, err } - existingClients, err := inboundSvc.GetClients(inbound) + existingClients, err := inboundSvc.GetClients(oldInbound) if err != nil { return false, err } - if err := validateClientsKeepAliveAgainstExisting(inbound.Protocol, clients, existingClients); err != nil { + if err := validateClientsKeepAliveAgainstExisting(oldInbound.Protocol, clients, existingClients); err != nil { return false, err } @@ -438,6 +442,11 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model nowTs := time.Now().Unix() * 1000 for i := range interfaceClients { if cm, ok := interfaceClients[i].(map[string]any); ok { + // Create and attach filter flow against the locked inbound snapshot. + if gateFlow && clients[i].Flow != "" && clientWithInboundFlow(clients[i], oldInbound).Flow == "" { + clients[i].Flow = "" + delete(cm, "flow") + } if _, ok2 := cm["created_at"]; !ok2 { cm["created_at"] = nowTs } @@ -457,10 +466,6 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model return false, common.NewError("Duplicate email:", existEmail) } - oldInbound, err := inboundSvc.GetInbound(data.Id) - if err != nil { - return false, err - } if err := validateTuicClientEmails(oldInbound.Protocol, clients); err != nil { return false, err } @@ -765,7 +770,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo if err := validateClientsRenewal(clients); err != nil { return false, err } - inbound, err := inboundSvc.GetInbound(data.Id) + oldInbound, err := inboundSvc.GetInbound(data.Id) if err != nil { return false, err } @@ -777,10 +782,6 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo interfaceClients := settings["clients"].([]any) - oldInbound, err := inboundSvc.GetInbound(data.Id) - if err != nil { - return false, err - } if err := validateTuicClientEmails(oldInbound.Protocol, clients); err != nil { return false, err } @@ -794,7 +795,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo if i == 0 { identityEmail = oldEmail } - if err := validateClientKeepAliveAgainstExisting(inbound.Protocol, client, oldClients, identityEmail); err != nil { + if err := validateClientKeepAliveAgainstExisting(oldInbound.Protocol, client, oldClients, identityEmail); err != nil { return false, fmt.Errorf("client %q: %w", client.Email, err) } }