Files
mirror-3x-ui/internal/web/service/node_fleet_test.go
T
Hamed 3d6655ffb0 fix(nodes): prevent quota overflow in fleet counts (#7323)
Complete the remaining correctness work for #7319 on top of the SQL fleet aggregation introduced by #7342.

Replace the overflowing BIGINT upload-plus-download quota comparison in countNodeFleet with a guarded subtraction-based CASE. Preserve depletion precedence, unlimited quotas, missing traffic behavior, email-based traffic attribution, host deduplication, exclusion of orphan memberships, and database error propagation.

Add regression coverage for signed int64 limits, negative counters, unlimited quotas and orphan memberships. Require both fleet regression tests to execute and pass in PostgreSQL CI without weakening existing checks.

Validation: reviewed head e9b344a63bdf6aa945f0e4f6b3cbe933a416fabe; all 12 CI jobs passed, including both PostgreSQL fleet tests and all seven quota subcases. Independent arithmetic comparison over 1,331 boundary combinations found zero mismatches. See https://github.com/MHSanaei/3x-ui/pull/7323#issuecomment-7388723297. The green CI is for the reviewed PR head, not a fresh post-merge run.

Closes #7319.
2026-12-03 22:21:58 +03:30

406 lines
15 KiB
Go

package service
import (
"encoding/json"
"fmt"
"math"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/testpg"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
func TestNodeOverviewWithoutNodesSkipsFleetReads(t *testing.T) {
setupConflictDB(t)
db := database.GetDB()
if err := db.Create(&model.ClientRecord{Email: "standalone@example.test"}).Error; err != nil {
t.Fatal(err)
}
queries := recordExecutedSQL(t, db)
view, err := (&NodeService{}).GetNodeOverview(&Status{T: time.Now(), CpuCores: 4, LogicalPro: 8})
if err != nil {
t.Fatal(err)
}
if len(*queries) != 1 {
t.Fatalf("standalone overview should only read the nodes table, queried %v", *queries)
}
if view.Nodes == nil || len(view.Nodes) != 0 ||
view.Master != (NodeMasterView{}) || view.Fleet != (NodeFleetCounts{}) {
t.Fatalf("standalone overview should be empty: %+v", view)
}
}
func TestNodeHeartbeatPublishesTelemetry(t *testing.T) {
svc, node, response := availabilityNodeFixture(t, `{"success":true,"obj":{"cpu":0,"cpuCores":4,"logicalPro":8,"mem":{"current":0,"total":4294967296},"tcpCount":0,"udpCount":7,"loads":[0,0.25,1.5],"netIO":{"up":0,"down":100}}}`)
read := func() map[string]any {
t.Helper()
patch, err := svc.Probe(t.Context(), node)
if err != nil {
t.Fatal(err)
}
patch.Status = "online"
if err := svc.UpdateHeartbeat(node.Id, patch); err != nil {
t.Fatal(err)
}
nodes, err := svc.GetNodeTreeView()
if err != nil || len(nodes) != 1 {
t.Fatalf("views: %v, %v", nodes, err)
}
data, err := json.Marshal(nodes[0])
if err != nil {
t.Fatal(err)
}
var view struct{ Telemetry map[string]any }
if err := json.Unmarshal(data, &view); err != nil {
t.Fatal(err)
}
return view.Telemetry
}
first := read()
for key, want := range map[string]float64{"cpuPct": 0, "physicalCores": 4, "logicalCores": 8, "memUsedBytes": 0, "memTotalBytes": 4294967296, "tcpCount": 0, "udpCount": 7, "load1": 0, "load5": 0.25, "load15": 1.5, "netUp": 0, "netDown": 100} {
if got := first[key]; got != want {
t.Errorf("%s = %v, want %v", key, got, want)
}
}
response(`{"success":true,"obj":{"cpu":0,"resourceScope":"container","cpuCores":4,"logicalPro":2,"unavailableMetrics":["cpu","tcpCount"],"tcpCount":0,"loads":[1e999,-1,0]}}`)
partial := read()
for _, field := range []string{"cpuPct", "physicalCores", "tcpCount", "udpCount", "memUsedBytes", "load1", "load5", "netUp"} {
if got := partial[field]; got != nil {
t.Errorf("unavailable %s = %v", field, got)
}
}
if partial["logicalCores"] != float64(2) || partial["load15"] != float64(0) {
t.Fatalf("lost valid partial metrics: %v", partial)
}
if err := svc.UpdateHeartbeat(node.Id, HeartbeatPatch{Status: "offline", LastHeartbeat: time.Now().Unix()}); err != nil {
t.Fatal(err)
}
view, err := svc.GetViewById(node.Id)
if err != nil || view.Status != "offline" || view.Telemetry != nil {
t.Fatalf("offline transition: %+v, %v", view, err)
}
response(`{"success":true,"obj":{"sampleAgeMillis":31000,"cpu":5}}`)
if stale := read(); stale != nil {
t.Fatalf("stale sample treated as live: %v", stale)
}
response(`{"success":true,"obj":{"cpu":5}}`)
if recovered := read(); recovered["cpuPct"] != float64(5) || recovered["tcpCount"] != nil {
t.Fatalf("legacy node recovery: %v", recovered)
}
}
func TestNodeOverviewCountsHostMembershipsAndUniqueFleetClients(t *testing.T) {
cleanup, err := testpg.IsolatePackage("node_fleet_counts")
if err != nil {
t.Fatal(err)
}
t.Cleanup(cleanup)
dbtest.InitDB(t, filepath.Join(t.TempDir(), "fleet.db"))
db := database.GetDB()
self, err := (&SettingService{}).GetPanelGuid()
if err != nil {
t.Fatal(err)
}
nodes := []model.Node{
{Name: "direct", Address: "192.0.2.1", Port: 2053, Guid: "direct"},
{Name: "cloned", Address: "192.0.2.2", Port: 2053, Guid: self},
}
if err := db.Create(&nodes).Error; err != nil {
t.Fatal(err)
}
nodeDescendantsMu.Lock()
nodeDescendantsCache[nodes[0].Id] = []model.NodeSummary{
{
Guid: "child", ParentGuid: "direct", Name: "child", Status: "online",
Telemetry: &model.NodeTelemetry{SampledAt: time.Now().UnixMilli(), UDPCount: new(0)},
},
}
nodeDescendantsMu.Unlock()
t.Cleanup(func() { (&NodeService{}).PruneNodeDescendants(nil) })
createInbound := func(tag string, nodeID *int, guid string) model.Inbound {
t.Helper()
ib := model.Inbound{Tag: tag, Port: 443, NodeID: nodeID, OriginNodeGuid: guid, Settings: `{"clients":[]}`}
if err := db.Create(&ib).Error; err != nil {
t.Fatal(err)
}
return ib
}
local := createInbound("local", nil, self)
direct := createInbound("direct", &nodes[0].Id, "direct")
child := createInbound("child", &nodes[0].Id, "child")
clone := createInbound("clone", &nodes[1].Id, self)
clients := []model.ClientRecord{{Email: "shared@test"}, {Email: "child@test"}, {Email: "orphan@test"}}
if err := db.Create(&clients).Error; err != nil {
t.Fatal(err)
}
links := []model.ClientInbound{
{ClientId: clients[0].Id, InboundId: local.Id},
{ClientId: clients[0].Id, InboundId: direct.Id},
{ClientId: clients[0].Id, InboundId: child.Id},
{ClientId: clients[1].Id, InboundId: child.Id},
{ClientId: clients[1].Id, InboundId: clone.Id},
{ClientId: math.MaxInt32, InboundId: clone.Id},
}
if err := db.Create(&links).Error; err != nil {
t.Fatal(err)
}
status := &Status{T: time.Now(), LogicalPro: 8, CpuCores: 4, Cpu: 31, Loads: []float64{1, 2, 3}}
status.Mem.Total, status.Mem.Current = 8<<30, 2<<30
overview, err := (&NodeService{}).GetNodeOverview(status)
if err != nil {
t.Fatal(err)
}
if overview.Fleet.ClientCount != 3 || overview.Fleet.InboundCount != 4 ||
overview.Master.Counts.ClientCount != 1 || overview.Master.Counts.InboundCount != 1 {
t.Fatalf("wrong host counts: %+v", overview)
}
want := map[string]int{"direct": 1, "cloned": 1, "child": 2}
for _, node := range overview.Nodes {
if node.ClientCount != want[node.Name] || node.InboundCount != 1 {
t.Errorf("wrong placement for %s: %+v", node.Name, node)
}
if node.Transitive && (node.Telemetry == nil || node.Telemetry.UDPCount == nil || *node.Telemetry.UDPCount != 0) {
t.Fatalf("missing descendant's own sample: %+v", node)
}
delete(want, node.Name)
}
if len(want) != 0 || overview.Master.Telemetry == nil || *overview.Master.Telemetry.Load15 != 3 {
t.Fatalf("missing view rows or master sample: %+v, missing=%v", overview.Master, want)
}
queries := recordExecutedSQL(t, db)
tree, err := (&NodeService{}).GetNodeTree()
if err != nil || len(tree) != 3 {
t.Fatalf("unexpected node tree: %v, %v", tree, err)
}
if strings.Contains(strings.Join(*queries, "\n"), "id FROM clients") {
t.Fatalf("node listing should skip the fleet aggregate: %v", *queries)
}
for i, node := range tree {
if node.ClientCount != overview.Nodes[i].ClientCount {
t.Errorf("wrong list count for %s: %d", node.Name, node.ClientCount)
}
}
}
func TestNodeFleetQuotaClassificationAtInt64Limits(t *testing.T) {
cleanup, err := testpg.IsolatePackage("node_fleet_quota")
if err != nil {
t.Fatal(err)
}
t.Cleanup(cleanup)
dbtest.InitDB(t, filepath.Join(t.TempDir(), "fleet-quota.db"))
db := database.GetDB()
node := model.Node{Name: "remote", Address: "192.0.2.1", Port: 2053, Guid: "remote"}
inbound := model.Inbound{Tag: "remote", Port: 443, NodeID: &node.Id, Settings: `{"clients":[]}`}
client := model.ClientRecord{Email: "quota@test", Enable: true}
for _, row := range []any{&node, &inbound, &client} {
if err := db.Create(row).Error; err != nil {
t.Fatal(err)
}
}
membership := model.ClientInbound{ClientId: client.Id, InboundId: inbound.Id}
if err := db.Create(&membership).Error; err != nil {
t.Fatal(err)
}
traffic := xray.ClientTraffic{Email: client.Email, InboundId: inbound.Id}
if err := db.Create(&traffic).Error; err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
up, down, total int64
depleted int
}{
{"above limit", math.MaxInt64, 1, math.MaxInt64, 1},
{"at limit", 1, math.MaxInt64 - 1, math.MaxInt64, 1},
{"below limit", math.MaxInt64 - 1, 0, math.MaxInt64, 0},
{"negative upload", -1, math.MaxInt64, math.MaxInt64, 0},
{"negative download", math.MaxInt64, -1, math.MaxInt64, 0},
{"negative underflow", math.MinInt64, -1, 1, 0},
{"unlimited", math.MaxInt64, 1, 0, 0},
} {
t.Run(tc.name, func(t *testing.T) {
if err := db.Model(&traffic).Updates(map[string]any{"up": tc.up, "down": tc.down, "total": tc.total}).Error; err != nil {
t.Fatal(err)
}
overview, err := (&NodeService{}).GetNodeOverview(nil)
if err != nil {
t.Fatal(err)
}
want := NodeFleetCounts{InboundCount: 1, ClientCount: 1, ActiveCount: 1 - tc.depleted, DepletedCount: tc.depleted}
if overview.Fleet != want || len(overview.Nodes) != 1 {
t.Fatalf("fleet counts = %+v, nodes = %d, want %+v and one node", overview.Fleet, len(overview.Nodes), want)
}
got := overview.Nodes[0]
if got.ClientCount != want.ClientCount || got.ActiveCount != want.ActiveCount ||
got.DisabledCount != 0 || got.DepletedCount != want.DepletedCount {
t.Fatalf("unexpected remote client counts: %+v", got)
}
})
}
}
func TestNodeOverviewUsesBestDescendantObservation(t *testing.T) {
cleanup, err := testpg.IsolatePackage("node_fleet_descendants")
if err != nil {
t.Fatal(err)
}
t.Cleanup(cleanup)
dbtest.InitDB(t, filepath.Join(t.TempDir(), "fleet-descendants.db"))
db := database.GetDB()
svc := &NodeService{}
t.Cleanup(func() { svc.PruneNodeDescendants(nil) })
parents := []model.Node{
{Name: "parent-a", Address: "192.0.2.1", Port: 2053, Guid: "parent-a", Enable: true},
{Name: "parent-b", Address: "192.0.2.2", Port: 2053, Guid: "parent-b", Enable: true},
}
if err := db.Create(&parents).Error; err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
status [2]string
age [2]time.Duration
wantParent int
wantStatus string
}{
{"lower ID offline", [2]string{"offline", "online"}, [2]time.Duration{}, 1, "online"},
{"higher ID offline", [2]string{"online", "offline"}, [2]time.Duration{}, 0, "online"},
{"lower ID disabled", [2]string{"disabled", "online"}, [2]time.Duration{}, 1, "online"},
{"higher ID disabled", [2]string{"online", "disabled"}, [2]time.Duration{}, 0, "online"},
{"both unavailable", [2]string{"offline", "disabled"}, [2]time.Duration{}, 0, "unknown"},
{"first sample stale", [2]string{"online", "online"}, [2]time.Duration{time.Minute, 0}, 1, "online"},
{"newer sample preferred", [2]string{"online", "online"}, [2]time.Duration{time.Second, 0}, 1, "online"},
{"equal samples keep lower ID", [2]string{"online", "online"}, [2]time.Duration{}, 0, "online"},
} {
t.Run(tc.name, func(t *testing.T) {
now := time.Now()
for i, parent := range parents {
if err := db.Model(&parent).Updates(map[string]any{
"enable": tc.status[i] != "disabled", "status": tc.status[i],
}).Error; err != nil {
t.Fatal(err)
}
nodeDescendantsMu.Lock()
nodeDescendantsCache[parent.Id] = []model.NodeSummary{{
Guid: "shared-child", Name: "shared-child", ParentGuid: parent.Guid, Status: "online",
Telemetry: &model.NodeTelemetry{SampledAt: now.Add(-tc.age[i]).UnixMilli(), CpuPct: new(float64(20 + i))},
}}
nodeDescendantsMu.Unlock()
}
view, err := svc.GetNodeOverview(nil)
if err != nil || len(view.Nodes) != 3 {
t.Fatalf("expected two parents and one child: %+v, %v", view, err)
}
child := view.Nodes[2]
if !child.Transitive || child.Guid != "shared-child" || child.ParentGuid != parents[tc.wantParent].Guid || child.Status != tc.wantStatus {
t.Fatalf("unexpected descendant observation: %+v", child)
}
if tc.wantStatus == "unknown" {
if child.Telemetry != nil {
t.Fatalf("unavailable descendant has telemetry: %+v", child.Telemetry)
}
} else if child.Telemetry == nil || child.Telemetry.CpuPct == nil || *child.Telemetry.CpuPct != float64(20+tc.wantParent) {
t.Fatalf("wrong descendant telemetry: %+v", child.Telemetry)
}
})
}
}
func BenchmarkNodeOverviewFleetScale(b *testing.B) {
dbtest.InitDB(b, filepath.Join(b.TempDir(), "fleet-scale.db"))
db := database.GetDB()
statusJSON := `{"success":true,"obj":{"cpu":25,"cpuCores":4,"logicalPro":8,"mem":{"current":2147483648,"total":8589934592,"available":6442450944},"tcpCount":132,"udpCount":22,"loads":[0.2,0.3,0.4],"uptime":90000,"netIO":{"up":12582912,"down":512}}}`
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(statusJSON))
}))
b.Cleanup(server.Close)
u, _ := url.Parse(server.URL)
port, _ := strconv.Atoi(u.Port())
nodes := make([]model.Node, 4)
for i := range nodes {
nodes[i] = model.Node{
Name: fmt.Sprint("remote-", i), Guid: fmt.Sprint("remote-guid-", i),
Scheme: "http", Address: u.Hostname(), Port: port, AllowPrivateAddress: true,
}
}
if err := db.Create(&nodes).Error; err != nil {
b.Fatal(err)
}
inbounds := make([]model.Inbound, 40)
for i := range inbounds {
inbounds[i] = model.Inbound{Tag: fmt.Sprint("inbound-", i), Port: 2000 + i, Settings: `{"clients":[]}`}
if i%5 != 0 {
node := &nodes[i%5-1]
inbounds[i].NodeID, inbounds[i].OriginNodeGuid = &node.Id, node.Guid
}
}
if err := db.CreateInBatches(&inbounds, 40).Error; err != nil {
b.Fatal(err)
}
clients := make([]model.ClientRecord, 7100)
for i := range clients {
clients[i].Email = fmt.Sprintf("client-%05d@test", i)
}
if err := db.CreateInBatches(&clients, 100).Error; err != nil {
b.Fatal(err)
}
links := make([]model.ClientInbound, 115000)
for i := range links {
client := clients[i%len(clients)]
ib := inbounds[(i/len(clients)+i)%len(inbounds)]
links[i] = model.ClientInbound{ClientId: client.Id, InboundId: ib.Id}
}
if err := db.CreateInBatches(&links, 250).Error; err != nil {
b.Fatal(err)
}
svc := &NodeService{}
cycle := func() {
for i := range nodes {
patch, err := svc.Probe(b.Context(), &nodes[i])
if err != nil {
b.Fatal(err)
}
patch.Status = "online"
if err := svc.UpdateHeartbeat(nodes[i].Id, patch); err != nil {
b.Fatal(err)
}
}
}
cycle()
b.Run("FourHeartbeatProbesAndWrites", func(b *testing.B) {
for b.Loop() {
cycle()
}
b.ReportMetric(float64(4*len(statusJSON)), "status-wire-B/cycle")
})
b.Run("OverviewAndJSON", func(b *testing.B) {
var payload []byte
for b.Loop() {
result, err := svc.GetNodeOverview(&Status{T: time.Now(), CpuCores: 4, LogicalPro: 8})
if err != nil {
b.Fatal(err)
}
payload, err = json.Marshal(result)
if err != nil || result.Fleet.ClientCount != 7100 {
b.Fatalf("fixture: %v", err)
}
}
b.ReportMetric(float64(len(payload)), "overview-wire-B/op")
})
}