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") }