diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a6e105ae9..957d845db 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -312,6 +312,15 @@ jobs: exit 1 fi + - name: PostgreSQL node client ownership scopes + run: | + set -o pipefail + test "$XUI_DB_TYPE" = postgres + test -n "$XUI_DB_DSN" + go test ./internal/web/service -run '^TestClientLinkScopes(HighFanout)?$' -count=1 -v | tee /tmp/postgres-client-link-scopes.log + grep -q '^--- PASS: TestClientLinkScopes ' /tmp/postgres-client-link-scopes.log + grep -q '^--- PASS: TestClientLinkScopesHighFanout ' /tmp/postgres-client-link-scopes.log + - name: PostgreSQL node snapshot regressions run: | set -o pipefail diff --git a/internal/web/service/client_link_scopes_test.go b/internal/web/service/client_link_scopes_test.go new file mode 100644 index 000000000..46ddb2533 --- /dev/null +++ b/internal/web/service/client_link_scopes_test.go @@ -0,0 +1,254 @@ +package service + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "maps" + "path/filepath" + "strings" + "testing" + "time" + + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" +) + +func TestClientLinkScopes(t *testing.T) { + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "scopes.db")) + inbounds := []model.Inbound{ + {Tag: "own-disabled", NodeID: new(1)}, + {Tag: "own-other-inbound", NodeID: new(1), Enable: true}, + {Tag: "other", NodeID: new(2)}, + {Tag: "another-node", NodeID: new(3)}, + {Tag: "master"}, + } + if err := db.Create(&inbounds).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&model.ClientRecord{Id: 7, Email: "detached@example.test"}).Error; err != nil { + t.Fatal(err) + } + var links []model.ClientInbound + for id, indexes := range [][]int{{0, 1}, {2, 3}, {4}, {0, 2}, {1, 4}, {3, 4}, {}} { + for _, index := range indexes { + links = append(links, model.ClientInbound{ClientId: id + 1, InboundId: inbounds[index].Id}) + } + } + links = append(links, model.ClientInbound{ClientId: 8, InboundId: inbounds[len(inbounds)-1].Id + 1}, + model.ClientInbound{ClientId: 10, InboundId: inbounds[0].Id}) + if err := db.Create(&links).Error; err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name string + id int + want map[int]clientLinkScope + }{ + {"own multiple including disabled", 1, map[int]clientLinkScope{1: {here: true}}}, + {"other nodes only", 2, map[int]clientLinkScope{2: {elsewhere: true}}}, + {"master only", 3, map[int]clientLinkScope{3: {elsewhere: true}}}, + {"own plus other", 4, map[int]clientLinkScope{4: {here: true, elsewhere: true}}}, + {"own plus master", 5, map[int]clientLinkScope{5: {here: true, elsewhere: true}}}, + {"other plus master", 6, map[int]clientLinkScope{6: {elsewhere: true}}}, + {"disabled inbound only", 10, map[int]clientLinkScope{10: {here: true}}}, + {"detached", 7, nil}, + {"dangling inbound", 8, nil}, + {"unknown", 9, nil}, + } { + t.Run(tc.name, func(t *testing.T) { + got, err := clientLinkScopes(db, 1, []int{tc.id, tc.id}) + if err != nil || !maps.Equal(got, tc.want) { + t.Fatalf("scopes = %v, %v, want %v", got, err, tc.want) + } + }) + } + trace := &linkScopeTrace{Interface: logger.Discard} + if got, err := clientLinkScopes(db.Session(&gorm.Session{Logger: trace}), 1, nil); err != nil || len(got) != 0 || len(trace.sql) != 0 { + t.Fatalf("empty IDs: scopes=%v queries=%d error=%v", got, len(trace.sql), err) + } + tx := db.Begin() + if err := tx.Rollback().Error; err != nil { + t.Fatal(err) + } + if got, err := clientLinkScopes(tx, 1, []int{1}); got != nil || !errors.Is(err, sql.ErrTxDone) { + t.Fatalf("closed transaction: scopes=%v error=%v", got, err) + } +} + +type linkScopeTrace struct { + logger.Interface + rows int64 + sql []string +} + +func (l *linkScopeTrace) Trace(_ context.Context, _ time.Time, fc func() (string, int64), _ error) { + query, rows := fc() + l.rows += rows + l.sql = append(l.sql, query) +} + +func TestClientLinkScopesHighFanout(t *testing.T) { + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "scope-fanout.db")) + ids, pairs := seedLinkScopeFanout(t, db) + const edges = 115041 + oldTrace := &linkScopeTrace{Interface: logger.Discard} + newTrace := &linkScopeTrace{Interface: logger.Discard} + want, err := legacyClientLinkScopes(db.Session(&gorm.Session{Logger: oldTrace}), 1, ids) + if err != nil || oldTrace.rows != edges { + t.Fatalf("legacy lookup: rows=%d error=%v", oldTrace.rows, err) + } + input := append(append([]int(nil), ids...), ids[0], ids[len(ids)-1]) + got, err := clientLinkScopes(db.Session(&gorm.Session{Logger: newTrace}), 1, input) + if err != nil || !maps.Equal(got, want) || newTrace.rows != int64(pairs) { + t.Fatalf("lookup: scopes=%d equal=%t rows=%d want=%d error=%v", len(got), maps.Equal(got, want), newTrace.rows, pairs, err) + } + if wantQueries := (len(ids) + sqlInChunk - 1) / sqlInChunk; len(newTrace.sql) != wantQueries || len(oldTrace.sql) != wantQueries { + t.Fatalf("query count: legacy=%d current=%d want=%d", len(oldTrace.sql), len(newTrace.sql), wantQueries) + } + for _, statement := range newTrace.sql { + if !strings.HasPrefix(statement, "SELECT DISTINCT client_inbounds.client_id AS client_id, inbounds.node_id AS node_id FROM ") { + t.Fatalf("expected composite DISTINCT: %s", statement) + } + } +} + +// The 30 inbounds overlap instead of partitioning the client population. +func seedLinkScopeFanout(t testing.TB, db *gorm.DB) ([]int, int) { + t.Helper() + const clientsCount = 7101 + clients := make([]model.ClientRecord, clientsCount) + for i := range clients { + clients[i] = model.ClientRecord{Email: fmt.Sprintf("scope-%d@example.test", i)} + } + if err := db.CreateInBatches(&clients, 150).Error; err != nil { + t.Fatal(err) + } + ids := make([]int, clientsCount) + for i, client := range clients { + ids[i] = client.Id + } + pairs := 0 + for scope, edges := range []int{46061, 26000, 22000, 18000, 2980} { + inboundCount := [...]int{11, 6, 5, 4, 4}[scope] + seen := make(map[int]struct{}) + for i := range inboundCount { + inbound := model.Inbound{Tag: fmt.Sprintf("scope-%d-%d", scope, i)} + if scope < 4 { + inbound.NodeID = new(scope + 1) + } + if err := db.Create(&inbound).Error; err != nil { + t.Fatal(err) + } + links := make([]model.ClientInbound, edges/inboundCount) + if i < edges%inboundCount { + links = append(links, model.ClientInbound{}) + } + for j := range links { + id := ids[(scope*137+i*1100+j)%clientsCount] + links[j] = model.ClientInbound{ClientId: id, InboundId: inbound.Id, CreatedAt: 1} + seen[id] = struct{}{} + } + if err := db.CreateInBatches(links, 200).Error; err != nil { + t.Fatal(err) + } + } + pairs += len(seen) + } + return ids, pairs +} + +func legacyClientLinkScopes(tx *gorm.DB, nodeID int, ids []int) (map[int]clientLinkScope, error) { + scopes := make(map[int]clientLinkScope, len(ids)) + for _, batch := range chunkInts(uniqueInts(ids), sqlInChunk) { + var rows []struct { + ClientID int + NodeID *int + } + if err := tx.Table("client_inbounds").Select("client_inbounds.client_id AS client_id, inbounds.node_id AS node_id"). + Joins("JOIN inbounds ON inbounds.id = client_inbounds.inbound_id"). + Where("client_inbounds.client_id IN ?", batch).Scan(&rows).Error; err != nil { + return nil, err + } + for _, row := range rows { + scope := scopes[row.ClientID] + if row.NodeID != nil && *row.NodeID == nodeID { + scope.here = true + } else { + scope.elsewhere = true + } + scopes[row.ClientID] = scope + } + } + return scopes, nil +} + +func BenchmarkClientLinkScopesFanout(b *testing.B) { + cleanup, err := testpg.IsolatePackage("link_scope_bench") + if err != nil { + b.Fatal(err) + } + b.Cleanup(cleanup) + setupScaleDB(b) + db := database.GetDB() + ids, _ := seedLinkScopeFanout(b, db) + if err := db.Exec("ANALYZE").Error; err != nil { + b.Fatal(err) + } + for _, batch := range []struct { + name string + ids []int + }{{"sparse-16", ids[2000:2016]}, {"dense-400", ids[2000:2400]}, {"full-7101", ids}} { + b.Run(batch.name, func(b *testing.B) { + for _, impl := range []struct { + name string + read func(*gorm.DB, int, []int) (map[int]clientLinkScope, error) + }{{"edges", legacyClientLinkScopes}, {"distinct", clientLinkScopes}} { + b.Run(impl.name, func(b *testing.B) { + trace := &linkScopeTrace{Interface: logger.Discard} + if _, err := impl.read(db.Session(&gorm.Session{Logger: trace}), 1, batch.ids); err != nil { + b.Fatal(err) + } + b.ReportAllocs() + for b.Loop() { + if _, err := impl.read(db, 1, batch.ids); err != nil { + b.Fatal(err) + } + } + b.ReportMetric(float64(trace.rows), "rows/op") + b.ReportMetric(float64(len(trace.sql)), "queries/op") + if db.Name() == database.DialectPostgres && len(trace.sql) == 1 { + reportLinkScopePlan(b, db, trace.sql[0]) + } + }) + } + }) + } +} + +func reportLinkScopePlan(b *testing.B, db *gorm.DB, query string) { + b.Helper() + var raw []byte + if err := db.Raw("EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) " + query).Row().Scan(&raw); err != nil { + b.Fatal(err) + } + var plans []struct { + ExecutionTime float64 `json:"Execution Time"` + Plan struct { + SharedHits int `json:"Shared Hit Blocks"` + SharedReads int `json:"Shared Read Blocks"` + } + } + if err := json.Unmarshal(raw, &plans); err != nil || len(plans) != 1 { + b.Fatalf("decode EXPLAIN plan: %v", err) + } + b.ReportMetric(plans[0].ExecutionTime, "sql-ms/batch") + b.ReportMetric(float64(plans[0].Plan.SharedHits), "shared-hit/batch") + b.ReportMetric(float64(plans[0].Plan.SharedReads), "shared-read/batch") +} diff --git a/internal/web/service/inbound_node_claims.go b/internal/web/service/inbound_node_claims.go index 248a587c9..d57734b53 100644 --- a/internal/web/service/inbound_node_claims.go +++ b/internal/web/service/inbound_node_claims.go @@ -207,7 +207,7 @@ func clientLinkScopes(tx *gorm.DB, nodeID int, ids []int) (map[int]clientLinkSco NodeID *int } if err := tx.Table("client_inbounds"). - Select("client_inbounds.client_id AS client_id, inbounds.node_id AS node_id"). + Distinct("client_inbounds.client_id AS client_id, inbounds.node_id AS node_id"). Joins("JOIN inbounds ON inbounds.id = client_inbounds.inbound_id"). Where("client_inbounds.client_id IN ?", batch). Scan(&rows).Error; err != nil {