From c23e1cb23152db34e4596e5ac16e96614221dea5 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Sun, 29 Nov 2026 13:47:59 +0330 Subject: [PATCH] feat(nodes): show how many clients are online on the node itself Since a69f2dee a node's online report is cut to the clients linked to its inbounds on this panel, so a node that also serves inbounds the panel does not import (inboundSyncMode=selected, or inbounds created on the node) shows only part of its load, and an operator cannot tell a busy node from an idle one. The panel now counts the distinct clients in the node's own entry of that report before the cut and keeps the number only: the emails of clients it does not manage are still dropped, so they cannot mark another client online or reach the IP limit. The count needs no new node endpoint, so nodes on older builds report it too, and it is dropped together with the node's online clients when the node is no longer synced. The Nodes page shows it as "synced / total" in the online tag when the node reports more than the synced count. Transitive sub-nodes carry no total: the panel takes no counts from an intermediate node. --- docs/public/openapi.json | 15 ++ frontend/public/openapi.json | 15 ++ frontend/src/generated/examples.ts | 2 + frontend/src/generated/schemas.ts | 11 ++ frontend/src/generated/types.ts | 2 + frontend/src/generated/zod.ts | 2 + frontend/src/pages/nodes/NodeList.tsx | 48 ++++-- frontend/src/schemas/node.ts | 2 + .../src/test/node-list-online-total.test.tsx | 80 ++++++++++ internal/database/model/model.go | 14 +- internal/web/service/inbound_node.go | 27 ++++ internal/web/service/node.go | 5 + internal/web/service/node_contract.go | 2 + .../web/service/node_online_total_test.go | 139 ++++++++++++++++++ internal/web/service/node_tree.go | 3 + internal/web/translation/ar-EG.json | 1 + internal/web/translation/en-US.json | 1 + internal/web/translation/es-ES.json | 1 + internal/web/translation/fa-IR.json | 1 + internal/web/translation/id-ID.json | 1 + internal/web/translation/ja-JP.json | 1 + internal/web/translation/pt-BR.json | 1 + internal/web/translation/ru-RU.json | 1 + internal/web/translation/sk-SK.json | 1 + internal/web/translation/tr-TR.json | 1 + internal/web/translation/uk-UA.json | 1 + internal/web/translation/vi-VN.json | 1 + internal/web/translation/zh-CN.json | 1 + internal/web/translation/zh-TW.json | 1 + internal/xray/process.go | 37 ++++- 30 files changed, 395 insertions(+), 23 deletions(-) create mode 100644 frontend/src/test/node-list-online-total.test.tsx create mode 100644 internal/web/service/node_online_total_test.go diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 483eae866..8ee92524e 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -4434,6 +4434,11 @@ "example": 3, "type": "integer" }, + "onlineTotalCount": { + "description": "OnlineTotalCount also counts clients on inbounds this panel does not sync.", + "example": 7, + "type": "integer" + }, "outboundTag": { "type": "string" }, @@ -4537,6 +4542,7 @@ "netDown", "netUp", "onlineCount", + "onlineTotalCount", "outboundTag", "panelVersion", "pinnedCertSha256", @@ -4759,6 +4765,10 @@ "example": 5, "type": "integer" }, + "onlineTotalCount": { + "example": 9, + "type": "integer" + }, "outboundTag": { "example": "direct", "type": "string" @@ -4852,6 +4862,7 @@ "netDown", "netUp", "onlineCount", + "onlineTotalCount", "outboundTag", "panelVersion", "pinnedCertSha256", @@ -13563,6 +13574,7 @@ "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", @@ -13767,6 +13779,7 @@ "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", @@ -13920,6 +13933,7 @@ "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", @@ -19719,6 +19733,7 @@ "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 483eae866..8ee92524e 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -4434,6 +4434,11 @@ "example": 3, "type": "integer" }, + "onlineTotalCount": { + "description": "OnlineTotalCount also counts clients on inbounds this panel does not sync.", + "example": 7, + "type": "integer" + }, "outboundTag": { "type": "string" }, @@ -4537,6 +4542,7 @@ "netDown", "netUp", "onlineCount", + "onlineTotalCount", "outboundTag", "panelVersion", "pinnedCertSha256", @@ -4759,6 +4765,10 @@ "example": 5, "type": "integer" }, + "onlineTotalCount": { + "example": 9, + "type": "integer" + }, "outboundTag": { "example": "direct", "type": "string" @@ -4852,6 +4862,7 @@ "netDown", "netUp", "onlineCount", + "onlineTotalCount", "outboundTag", "panelVersion", "pinnedCertSha256", @@ -13563,6 +13574,7 @@ "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", @@ -13767,6 +13779,7 @@ "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", @@ -13920,6 +13933,7 @@ "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", @@ -19719,6 +19733,7 @@ "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index ce21c190d..1c7b6c620 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -1158,6 +1158,7 @@ export const EXAMPLES: Record = { "netDown": 2097152, "netUp": 1048576, "onlineCount": 3, + "onlineTotalCount": 7, "outboundTag": "", "panelVersion": "v3.x.x", "parentGuid": "", @@ -1226,6 +1227,7 @@ export const EXAMPLES: Record = { "netDown": 1048576, "netUp": 2097152, "onlineCount": 5, + "onlineTotalCount": 9, "outboundTag": "direct", "panelVersion": "v3.x.x", "parentGuid": "", diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index 19fb6bf0b..bd97abbdc 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -4408,6 +4408,11 @@ export const SCHEMAS: Record = { "example": 3, "type": "integer" }, + "onlineTotalCount": { + "description": "OnlineTotalCount also counts clients on inbounds this panel does not sync.", + "example": 7, + "type": "integer" + }, "outboundTag": { "type": "string" }, @@ -4511,6 +4516,7 @@ export const SCHEMAS: Record = { "netDown", "netUp", "onlineCount", + "onlineTotalCount", "outboundTag", "panelVersion", "pinnedCertSha256", @@ -4733,6 +4739,10 @@ export const SCHEMAS: Record = { "example": 5, "type": "integer" }, + "onlineTotalCount": { + "example": 9, + "type": "integer" + }, "outboundTag": { "example": "direct", "type": "string" @@ -4826,6 +4836,7 @@ export const SCHEMAS: Record = { "netDown", "netUp", "onlineCount", + "onlineTotalCount", "outboundTag", "panelVersion", "pinnedCertSha256", diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index e49e8ae56..5b406d8d8 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -1011,6 +1011,7 @@ export interface Node { netDown: number; netUp: number; onlineCount: number; + onlineTotalCount: number; outboundTag: string; panelVersion: string; parentGuid?: string; @@ -1075,6 +1076,7 @@ export interface NodeView { netDown: number; netUp: number; onlineCount: number; + onlineTotalCount: number; outboundTag: string; panelVersion: string; parentGuid?: string; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index 38c619155..3611c3061 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -1074,6 +1074,7 @@ export const NodeSchema = z.object({ netDown: z.number().int(), netUp: z.number().int(), onlineCount: z.number().int(), + onlineTotalCount: z.number().int(), outboundTag: z.string(), panelVersion: z.string(), parentGuid: z.string().optional(), @@ -1140,6 +1141,7 @@ export const NodeViewSchema = z.object({ netDown: z.number().int(), netUp: z.number().int(), onlineCount: z.number().int(), + onlineTotalCount: z.number().int(), outboundTag: z.string(), panelVersion: z.string(), parentGuid: z.string().optional(), diff --git a/frontend/src/pages/nodes/NodeList.tsx b/frontend/src/pages/nodes/NodeList.tsx index 17185f869..b85606bec 100644 --- a/frontend/src/pages/nodes/NodeList.tsx +++ b/frontend/src/pages/nodes/NodeList.tsx @@ -53,6 +53,15 @@ function isUpdateEligible(n: NodeRecord): boolean { return !!n.enable && n.status === 'online'; } +// A node also serves clients on inbounds this panel does not sync; when it reports +// more online than the synced count, both show as "synced / total". +function onlineCounts(n: NodeRecord): { label: string; synced: number; total: number } | null { + const synced = n.onlineCount || 0; + const total = Math.max(n.onlineTotalCount || 0, synced); + if (!total) return null; + return { label: total > synced ? `${synced} / ${total}` : String(synced), synced, total }; +} + interface NodeRow extends NodeRecord { url: string; key: string | number; @@ -177,6 +186,27 @@ function useRelativeTime() { ); } +function OnlineTag({ node, compact }: { node: NodeRecord; compact?: boolean }) { + const { t } = useTranslation(); + const counts = onlineCounts(node); + if (!counts) return null; + const tag = compact ? ( + + {counts.label} + + ) : ( + + {counts.label} {t('online')} + + ); + if (counts.total > counts.synced) { + const title = t('pages.nodes.onlineOnNode', { synced: counts.synced, total: counts.total }); + return {tag}; + } + // The compact tag is a bare number, so it still needs to say what it counts. + return compact ? {tag} : tag; +} + export default function NodeList({ nodes, loading = false, @@ -530,17 +560,7 @@ export default function NodeList({ ) : null} - {record.onlineCount ? ( - - - {record.onlineCount} - - - ) : null} + ), }, @@ -887,11 +907,7 @@ export default function NodeList({ {statsNode.depletedCount} {t('depleted')} ) : null} - {statsNode.onlineCount ? ( - - {statsNode.onlineCount} {t('online')} - - ) : null} +
{t('pages.nodes.lastHeartbeat')} diff --git a/frontend/src/schemas/node.ts b/frontend/src/schemas/node.ts index 10efb8242..dc64dd00f 100644 --- a/frontend/src/schemas/node.ts +++ b/frontend/src/schemas/node.ts @@ -23,6 +23,8 @@ export const NodeRecordSchema = z inboundCount: z.number().optional(), clientCount: z.number().optional(), onlineCount: z.number().optional(), + // Clients online on the node itself, including inbounds this panel does not sync. + onlineTotalCount: z.number().optional(), activeCount: z.number().optional(), disabledCount: z.number().optional(), depletedCount: z.number().optional(), diff --git a/frontend/src/test/node-list-online-total.test.tsx b/frontend/src/test/node-list-online-total.test.tsx new file mode 100644 index 000000000..d6bbc9eea --- /dev/null +++ b/frontend/src/test/node-list-online-total.test.tsx @@ -0,0 +1,80 @@ +import { screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it } from 'vitest'; + +import NodeList from '@/pages/nodes/NodeList'; +import type { NodeRecord } from '@/schemas/node'; + +import { renderWithProviders } from './test-utils'; + +const noop = () => {}; + +function renderNode( + counts: Pick, + isMobile = false, +) { + const node: NodeRecord = { + id: 1, + name: 'edge', + guid: 'e1', + enable: true, + status: 'online', + clientCount: 40, + ...counts, + }; + renderWithProviders( + , + ); +} + +// The online badge counts only clients of inbounds imported into this panel, so a node busy on +// its other inbounds looked idle; the node's own total must show beside that count. +describe('NodeList online total', () => { + it('shows synced / total and explains both numbers on hover', async () => { + renderNode({ onlineCount: 3, onlineTotalCount: 12 }); + + await userEvent.hover(screen.getByText('3 / 12')); + + expect((await screen.findByRole('tooltip')).textContent).toBe( + '3 online on inbounds imported into this panel, 12 online on the node in total', + ); + }); + + it('shows the total when no synced client is online', () => { + renderNode({ onlineCount: 0, onlineTotalCount: 5 }); + + expect(screen.getByText('0 / 5')).toBeTruthy(); + }); + + it.each<[string, Pick]>([ + ['the total equals the synced count', { onlineCount: 7, onlineTotalCount: 7 }], + ['the panel reports no total', { onlineCount: 7 }], + ])('keeps the single number when %s', (_name, counts) => { + renderNode(counts); + + expect(screen.getByText('7')).toBeTruthy(); + expect(screen.queryByText(/\d \/ \d/)).toBeNull(); + }); + + it('shows synced / total in the mobile stats dialog', async () => { + renderNode({ onlineCount: 3, onlineTotalCount: 12 }, true); + + await userEvent.click(screen.getByRole('button', { name: 'More Information' })); + + expect(within(await screen.findByRole('dialog')).getByText('3 / 12 Online')).toBeTruthy(); + }); +}); diff --git a/internal/database/model/model.go b/internal/database/model/model.go index ebc39449b..9e733e5e0 100644 --- a/internal/database/model/model.go +++ b/internal/database/model/model.go @@ -941,12 +941,14 @@ type Node struct { DownNotified bool `json:"-" gorm:"column:down_notified;default:false"` - InboundCount int `json:"inboundCount" gorm:"-" example:"5"` - ClientCount int `json:"clientCount" gorm:"-" example:"27"` - OnlineCount int `json:"onlineCount" gorm:"-" example:"3"` - ActiveCount int `json:"activeCount" gorm:"-" example:"23"` - DisabledCount int `json:"disabledCount" gorm:"-" example:"3"` - DepletedCount int `json:"depletedCount" gorm:"-" example:"1"` + InboundCount int `json:"inboundCount" gorm:"-" example:"5"` + ClientCount int `json:"clientCount" gorm:"-" example:"27"` + OnlineCount int `json:"onlineCount" gorm:"-" example:"3"` + // OnlineTotalCount also counts clients on inbounds this panel does not sync. + OnlineTotalCount int `json:"onlineTotalCount" gorm:"-" example:"7"` + ActiveCount int `json:"activeCount" gorm:"-" example:"23"` + DisabledCount int `json:"disabledCount" gorm:"-" example:"3"` + DepletedCount int `json:"depletedCount" gorm:"-" example:"1"` // ParentGuid + Transitive are set only when a node is surfaced as part of a // node tree (#4983): direct nodes carry the master panel's own GUID, a diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index 6630462cb..16757f266 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -1558,6 +1558,8 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } + ownOnlineTotal := reportedOwnOnlineTotal(snap, nodeRow.Guid) + // The online report outlives this merge, so it is cut first to the node's own clients. if len(snap.OnlineTree) > 0 || len(snap.OnlineEmails) > 0 { attached, err := nodeAttachedEmails(db, nodeID) @@ -1584,6 +1586,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } process.SetNodeOnlineTree(nodeID, filterGuidTreeKeys(tree, hostedGuids)) + process.SetNodeOnlineTotal(nodeID, ownOnlineTotal) activeTree := normalizeActiveInboundTreeTags(snap.ActiveInboundTree, tagToCentral) if guidShared && len(activeTree) > 0 { @@ -1698,6 +1701,16 @@ func (s *InboundService) SetNodeOnlineTree(nodeID int, tree map[string][]string) } } +// GetNodeOnlineTotals returns, per direct node id, how many clients that node reported +// online on its own core, including those on inbounds this panel does not sync. +func (s *InboundService) GetNodeOnlineTotals() map[int]int { + process := currentXrayProcess() + if process == nil { + return map[int]int{} + } + return process.GetNodeOnlineTotals() +} + func (s *InboundService) ClearNodeOnlineClients(nodeID int) { if process := currentXrayProcess(); process != nil { process.ClearNodeOnlineClients(nodeID) @@ -1769,6 +1782,20 @@ func remapGuidTreeKey(tree map[string][]string, from, to string) map[string][]st return remapped } +// reportedOwnOnlineTotal counts the clients a node reports online on its own core, synced +// here or not. An old build's flat list is all it sends, so its sub-nodes' clients count too. +func reportedOwnOnlineTotal(snap *runtime.TrafficSnapshot, nodeGuid string) int { + emails := snap.OnlineEmails + if len(snap.OnlineTree) > 0 { + emails = snap.OnlineTree[nodeGuid] + } + distinct := make(map[string]struct{}, len(emails)) + for _, email := range emails { + distinct[email] = struct{}{} + } + return len(distinct) +} + // keepAttachedOnlineEmails cuts a node's online report to the clients linked to its inbounds, // once each per GUID, into fresh slices so the reported ones are not pinned. func keepAttachedOnlineEmails(snap *runtime.TrafficSnapshot, attached map[string]struct{}) { diff --git a/internal/web/service/node.go b/internal/web/service/node.go index d9f1a9845..3365f62e1 100644 --- a/internal/web/service/node.go +++ b/internal/web/service/node.go @@ -163,6 +163,11 @@ func (s *NodeService) populateClientCounts(db *gorm.DB, nodes []*model.Node) { } func (s *NodeService) enrichDashboardStats(db *gorm.DB, nodes []*model.Node) { + // Set before the early returns: a node with nothing synced still has clients online. + onlineTotals := (&InboundService{}).GetNodeOnlineTotals() + for _, n := range nodes { + n.OnlineTotalCount = onlineTotals[n.Id] + } type inboundRow struct { Id int NodeID int `gorm:"column:node_id"` diff --git a/internal/web/service/node_contract.go b/internal/web/service/node_contract.go index 782808c9b..d1e136189 100644 --- a/internal/web/service/node_contract.go +++ b/internal/web/service/node_contract.go @@ -45,6 +45,7 @@ type NodeView struct { InboundCount int `json:"inboundCount" example:"3"` ClientCount int `json:"clientCount" example:"25"` OnlineCount int `json:"onlineCount" example:"5"` + OnlineTotalCount int `json:"onlineTotalCount" example:"9"` ActiveCount int `json:"activeCount" example:"20"` DisabledCount int `json:"disabledCount" example:"2"` DepletedCount int `json:"depletedCount" example:"1"` @@ -94,6 +95,7 @@ func toNodeView(n *model.Node) *NodeView { InboundCount: n.InboundCount, ClientCount: n.ClientCount, OnlineCount: n.OnlineCount, + OnlineTotalCount: n.OnlineTotalCount, ActiveCount: n.ActiveCount, DisabledCount: n.DisabledCount, DepletedCount: n.DepletedCount, diff --git a/internal/web/service/node_online_total_test.go b/internal/web/service/node_online_total_test.go new file mode 100644 index 000000000..fbbdcec4a --- /dev/null +++ b/internal/web/service/node_online_total_test.go @@ -0,0 +1,139 @@ +package service + +import ( + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +// The node list counts only the clients this panel syncs as online; clients on the +// node's unsynced inbounds must still reach it as a number, never as emails. +func TestNodeTreeCountsEveryClientOnlineOnTheNode(t *testing.T) { + db := initTrafficTestDB(t) + useOnlineTestProcess(t) + svc := &InboundService{} + seedNodeRow(t, db, &model.Node{Id: 1, Name: "n1", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true, Guid: "node-guid"}) + createNodeInboundWithClient(t, db, 1, "keep", 41411, "kept@x") + settings := `{"clients":[{"email":"kept@x","enable":true}]}` + sync := func(t *testing.T, report func(*runtime.TrafficSnapshot)) { + t.Helper() + snap := snapshotWithClients(t, "keep", settings, xray.ClientTraffic{Email: "kept@x", Enable: true}) + report(snap) + if _, err := svc.setRemoteTrafficLocked(1, snap, false, false); err != nil { + t.Fatalf("sync: %v", err) + } + } + sync(t, func(*runtime.TrafficSnapshot) {}) + + steps := []struct { + name string + report func(*runtime.TrafficSnapshot) + subNode bool + wantSynced int + wantTotal int + }{ + { + name: "own GUID entry counted once per client, other GUIDs left out", + report: func(snap *runtime.TrafficSnapshot) { + snap.OnlineTree = map[string][]string{ + "node-guid": {"kept@x", "local-a@x", "local-a@x", "local-b@x"}, + "someone-else": {"s1@x", "s2@x", "s3@x", "s4@x", "s5@x"}, + } + }, + wantSynced: 1, + wantTotal: 3, + }, + { + name: "survives the per-GUID recount a sub-node triggers", + report: func(snap *runtime.TrafficSnapshot) { + snap.OnlineTree = map[string][]string{"node-guid": {"kept@x", "local-a@x"}} + }, + subNode: true, + wantSynced: 1, + wantTotal: 2, + }, + { + name: "flat list of a node without the per-GUID endpoint", + report: func(snap *runtime.TrafficSnapshot) { + snap.OnlineEmails = []string{"local-a@x", "local-b@x", "local-c@x", "kept@x"} + }, + wantSynced: 1, + wantTotal: 4, + }, + { + name: "an empty report replaces the previous total", + report: func(*runtime.TrafficSnapshot) {}, + }, + } + for _, step := range steps { + t.Run(step.name, func(t *testing.T) { + if step.subNode { + nodeDescendantsMu.Lock() + nodeDescendantsCache[1] = []model.NodeSummary{{Guid: "sub-guid", ParentGuid: "node-guid", Name: "sub"}} + nodeDescendantsMu.Unlock() + t.Cleanup(func() { + nodeDescendantsMu.Lock() + nodeDescendantsCache = map[int][]model.NodeSummary{} + nodeDescendantsMu.Unlock() + }) + } + sync(t, step.report) + + tree, err := (&NodeService{}).GetNodeTree() + if err != nil { + t.Fatalf("GetNodeTree: %v", err) + } + for _, n := range tree { + if n.Id != 1 { + if n.OnlineTotalCount != 0 { + t.Errorf("sub-node %q total online = %d, want 0: nothing reports it", n.Guid, n.OnlineTotalCount) + } + continue + } + if n.OnlineCount != step.wantSynced || n.OnlineTotalCount != step.wantTotal { + t.Errorf("online = %d synced / %d total, want %d / %d", n.OnlineCount, n.OnlineTotalCount, step.wantSynced, step.wantTotal) + } + } + if step.subNode && len(tree) != 2 { + t.Fatalf("tree has %d nodes, want the node and its sub-node", len(tree)) + } + }) + } +} + +// A node the sync no longer reaches keeps no online clients, so it keeps no total either. +func TestNodeOnlineTotalIsDroppedWithTheNodesOnlineClients(t *testing.T) { + tests := []struct { + name string + drop func(svc *InboundService) + }{ + {"failed probe", func(svc *InboundService) { svc.ClearNodeOnlineClients(1) }}, + {"node disabled", func(svc *InboundService) { + svc.RetainSyncedNodeOnlineClients([]*model.Node{{Id: 1, Enable: false, Status: "online"}}) + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + db := initTrafficTestDB(t) + useOnlineTestProcess(t) + svc := &InboundService{} + seedNodeRow(t, db, &model.Node{Id: 1, Name: "n1", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true, Guid: "node-guid"}) + // No synced client is online, so only the total holds the node's entry. + snap := &runtime.TrafficSnapshot{OnlineTree: map[string][]string{"node-guid": {"local-a@x", "local-b@x"}}} + if _, err := svc.setRemoteTrafficLocked(1, snap, false, false); err != nil { + t.Fatalf("sync: %v", err) + } + if got := svc.GetNodeOnlineTotals()[1]; got != 2 { + t.Fatalf("total online before the drop = %d, want 2", got) + } + + tt.drop(svc) + + if got := svc.GetNodeOnlineTotals(); len(got) != 0 { + t.Errorf("total online after the drop = %v, want none", got) + } + }) + } +} diff --git a/internal/web/service/node_tree.go b/internal/web/service/node_tree.go index 11f2a39aa..393cad1b4 100644 --- a/internal/web/service/node_tree.go +++ b/internal/web/service/node_tree.go @@ -260,10 +260,13 @@ func (s *NodeService) recountByGuid(nodes []*model.Node, selfGuid string) { } onlineByGuid := s.onlineEmailsByGuid() + onlineTotals := (&InboundService{}).GetNodeOnlineTotals() for _, n := range nodes { guid := effectiveNodeGuid(n, ambiguous) n.InboundCount = inboundCountByGuid[guid] n.OnlineCount = len(onlineByGuid[guid]) + // Keyed by node id, so a transitive sub-node (id 0) never has one. + n.OnlineTotalCount = onlineTotals[n.Id] n.DepletedCount = depletedByGuid[guid] n.DisabledCount = disabledByGuid[guid] n.ActiveCount = activeByGuid[guid] diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index 8793eaa33..d7729f1c3 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -1222,6 +1222,7 @@ "onlineNodes": "متصل", "offlineNodes": "غير متصل", "avgLatency": "متوسط الكمون", + "onlineOnNode": "{synced} متصل على الاتصالات الواردة المستوردة إلى هذه اللوحة، و{total} متصل على العقدة إجمالاً", "name": "الاسم", "namePlaceholder": "مثال: de-frankfurt-1", "addressPlaceholder": "panel.example.com أو 1.2.3.4", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index 49ab6c892..a092f1c62 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -1343,6 +1343,7 @@ "onlineNodes": "Online", "offlineNodes": "Offline", "avgLatency": "Avg Latency", + "onlineOnNode": "{synced} online on inbounds imported into this panel, {total} online on the node in total", "name": "Name", "namePlaceholder": "e.g. de-frankfurt-1", "addressPlaceholder": "panel.example.com or 1.2.3.4", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index aeb4bc385..fc8562787 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -1222,6 +1222,7 @@ "onlineNodes": "En línea", "offlineNodes": "Sin conexión", "avgLatency": "Latencia media", + "onlineOnNode": "{synced} en línea en los inbounds importados a este panel, {total} en línea en total en el nodo", "name": "Nombre", "namePlaceholder": "p. ej. de-frankfurt-1", "addressPlaceholder": "panel.example.com o 1.2.3.4", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index 51d3effe5..4ea72f867 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -1222,6 +1222,7 @@ "onlineNodes": "آنلاین", "offlineNodes": "آفلاین", "avgLatency": "میانگین تاخیر", + "onlineOnNode": "{synced} آنلاین روی اینباندهای واردشده به این پنل، {total} آنلاین در کل نود", "name": "نام", "namePlaceholder": "مثلاً de-frankfurt-1", "addressPlaceholder": "panel.example.com یا 1.2.3.4", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 479bce2dc..a825d4c33 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -1222,6 +1222,7 @@ "onlineNodes": "Online", "offlineNodes": "Offline", "avgLatency": "Latensi Rata-rata", + "onlineOnNode": "{synced} online pada inbound yang diimpor ke panel ini, total {total} online di node", "name": "Nama", "namePlaceholder": "mis. de-frankfurt-1", "addressPlaceholder": "panel.example.com atau 1.2.3.4", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index 26a98d514..2338bbc1c 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -1222,6 +1222,7 @@ "onlineNodes": "オンライン", "offlineNodes": "オフライン", "avgLatency": "平均レイテンシ", + "onlineOnNode": "このパネルにインポートしたインバウンドでオンライン: {synced}、ノード全体でオンライン: {total}", "name": "名前", "namePlaceholder": "例: de-frankfurt-1", "addressPlaceholder": "panel.example.com または 1.2.3.4", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index b9eeed22b..5fd957531 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -1222,6 +1222,7 @@ "onlineNodes": "Online", "offlineNodes": "Offline", "avgLatency": "Latência média", + "onlineOnNode": "{synced} online nos inbounds importados para este painel, {total} online no nó no total", "name": "Nome", "namePlaceholder": "ex.: de-frankfurt-1", "addressPlaceholder": "panel.example.com ou 1.2.3.4", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index 59b97274c..49a3f2a43 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -1222,6 +1222,7 @@ "onlineNodes": "В сети", "offlineNodes": "Не в сети", "avgLatency": "Средняя задержка", + "onlineOnNode": "В сети на инбаундах, импортированных в эту панель: {synced}; всего в сети на узле: {total}", "name": "Имя", "namePlaceholder": "напр. de-frankfurt-1", "addressPlaceholder": "panel.example.com или 1.2.3.4", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index a400e4e45..7562dd9f8 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -1343,6 +1343,7 @@ "onlineNodes": "Online", "offlineNodes": "Offline", "avgLatency": "Priemerná odozva", + "onlineOnNode": "{synced} online na vstupoch importovaných do tohto panela, celkovo {total} online na uzle", "name": "Názov", "namePlaceholder": "napr. de-frankfurt-1", "addressPlaceholder": "panel.example.com alebo 1.2.3.4", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index 147d35004..cde7b4f35 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -1222,6 +1222,7 @@ "onlineNodes": "Çevrimiçi", "offlineNodes": "Çevrimdışı", "avgLatency": "Ortalama Gecikme", + "onlineOnNode": "Bu panele içe aktarılan inbound'larda {synced} çevrimiçi, düğümde toplam {total} çevrimiçi", "name": "Ad", "namePlaceholder": "ör. de-frankfurt-1", "addressPlaceholder": "panel.example.com veya 1.2.3.4", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index 4af33898f..da0390bf0 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -1222,6 +1222,7 @@ "onlineNodes": "У мережі", "offlineNodes": "Не в мережі", "avgLatency": "Середня затримка", + "onlineOnNode": "У мережі на інбаундах, імпортованих у цю панель: {synced}; усього в мережі на вузлі: {total}", "name": "Назва", "namePlaceholder": "напр. de-frankfurt-1", "addressPlaceholder": "panel.example.com або 1.2.3.4", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index 2790b96eb..03aea4d6d 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -1222,6 +1222,7 @@ "onlineNodes": "Trực tuyến", "offlineNodes": "Ngoại tuyến", "avgLatency": "Độ trễ trung bình", + "onlineOnNode": "{synced} trực tuyến trên các inbound đã nhập vào bảng điều khiển này, tổng cộng {total} trực tuyến trên nút", "name": "Tên", "namePlaceholder": "vd: de-frankfurt-1", "addressPlaceholder": "panel.example.com hoặc 1.2.3.4", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index 1d1720dec..3d49fe829 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -1222,6 +1222,7 @@ "onlineNodes": "在线", "offlineNodes": "离线", "avgLatency": "平均延迟", + "onlineOnNode": "导入此面板的入站上有 {synced} 个在线,该节点上共有 {total} 个在线", "name": "名称", "namePlaceholder": "例如:de-frankfurt-1", "addressPlaceholder": "panel.example.com 或 1.2.3.4", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index 3ff06dfc3..05fb344f4 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -1222,6 +1222,7 @@ "onlineNodes": "上線", "offlineNodes": "離線", "avgLatency": "平均延遲", + "onlineOnNode": "匯入此面板的入站上有 {synced} 個上線,該節點上共有 {total} 個上線", "name": "名稱", "namePlaceholder": "例如:de-frankfurt-1", "addressPlaceholder": "panel.example.com 或 1.2.3.4", diff --git a/internal/xray/process.go b/internal/xray/process.go index fd3792183..6fe89d505 100644 --- a/internal/xray/process.go +++ b/internal/xray/process.go @@ -182,7 +182,10 @@ type process struct { // traffic within its own grace window. The inbounds page combines this with // nodeOnlineTrees so a multi-inbound client is not shown on an idle inbound. nodeActiveInboundTrees map[int]map[string][]string - onlineMu sync.RWMutex + // nodeOnlineTotals is, per direct node id, how many clients that node reported online + // on its own core: a number only, since most are not this panel's clients. + nodeOnlineTotals map[int]int + onlineMu sync.RWMutex // onlineAPISupport caches whether the running core implements the // online-stats RPCs (GetUsersStats). A new process is created on every @@ -583,6 +586,32 @@ func (p *Process) SetNodeActiveInboundTree(nodeID int, tree map[string][]string) p.nodeActiveInboundTrees[nodeID] = tree } +// SetNodeOnlineTotal records how many clients a direct node reported online on its own +// core, replacing the previous tick's number. +func (p *Process) SetNodeOnlineTotal(nodeID, total int) { + p.onlineMu.Lock() + defer p.onlineMu.Unlock() + if total <= 0 { + delete(p.nodeOnlineTotals, nodeID) + return + } + if p.nodeOnlineTotals == nil { + p.nodeOnlineTotals = map[int]int{} + } + p.nodeOnlineTotals[nodeID] = total +} + +// GetNodeOnlineTotals returns a copy of the per-node totals SetNodeOnlineTotal recorded. +func (p *Process) GetNodeOnlineTotals() map[int]int { + p.onlineMu.RLock() + defer p.onlineMu.RUnlock() + out := make(map[int]int, len(p.nodeOnlineTotals)) + for nodeID, total := range p.nodeOnlineTotals { + out[nodeID] = total + } + return out +} + // ClearNodeOnlineClients drops a direct node's whole subtree contribution. // Called when a probe fails so a downed node — and everything behind it — doesn't // keep its clients listed as "online" until the next successful probe. @@ -591,6 +620,7 @@ func (p *Process) ClearNodeOnlineClients(nodeID int) { defer p.onlineMu.Unlock() delete(p.nodeOnlineTrees, nodeID) delete(p.nodeActiveInboundTrees, nodeID) + delete(p.nodeOnlineTotals, nodeID) } // RetainNodeOnlineClients drops the subtree of every direct node keep rejects: nodes @@ -608,6 +638,11 @@ func (p *Process) RetainNodeOnlineClients(keep func(nodeID int) bool) { delete(p.nodeActiveInboundTrees, nodeID) } } + for nodeID := range p.nodeOnlineTotals { + if !keep(nodeID) { + delete(p.nodeOnlineTotals, nodeID) + } + } } // GetUptime returns the uptime of the Xray process in seconds.