package service import ( "encoding/json" "fmt" "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" ) 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{}).ClearDescendants(nodes[0].Id) }) 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}, } 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 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") }) }