Files
mirror-3x-ui/internal/web/service/node_fleet.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

168 lines
5.9 KiB
Go

package service
import (
"encoding/json"
"slices"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
type NodeFleetCounts struct {
InboundCount int `json:"inboundCount" example:"8"`
ClientCount int `json:"clientCount" example:"100"`
ActiveCount int `json:"activeCount" example:"90"`
DisabledCount int `json:"disabledCount" example:"8"`
DepletedCount int `json:"depletedCount" example:"2"`
OnlineCount int `json:"onlineCount" example:"20"`
}
type NodeMasterView struct {
Counts NodeFleetCounts `json:"counts"`
Telemetry *model.NodeTelemetry `json:"telemetry,omitempty"`
XrayVersion string `json:"xrayVersion,omitempty" example:"26.1.1"`
PanelVersion string `json:"panelVersion,omitempty" example:"v3.12.0"`
XrayState string `json:"xrayState,omitempty" example:"running"`
XrayError string `json:"xrayError,omitempty"`
}
type NodeOverview struct {
Nodes []*NodeView `json:"nodes"`
Master NodeMasterView `json:"master"`
Fleet NodeFleetCounts `json:"fleet"`
}
func (s *NodeService) GetNodeOverview(local *Status) (*NodeOverview, error) {
nodes, master, fleet, err := s.getNodeTreeWithCounts(true)
if err != nil {
return nil, err
}
overview := &NodeOverview{Nodes: nodeTreeViews(nodes), Master: NodeMasterView{Counts: master}, Fleet: fleet}
if len(nodes) > 0 && local != nil {
overview.Master.XrayVersion = local.Xray.Version
overview.Master.PanelVersion = local.PanelVersion
overview.Master.XrayState = string(local.Xray.State)
overview.Master.XrayError = local.Xray.ErrorMsg
// Use the same typed projection and availability checks as remote heartbeats.
if payload, err := json.Marshal(local); err == nil {
var metrics nodeStatusMetrics
if json.Unmarshal(payload, &metrics) == nil && !local.T.IsZero() {
overview.Master.Telemetry = liveNodeTelemetry(&model.Node{
Enable: true, Status: "online", Telemetry: metrics.telemetry(local.T),
}, time.Now())
}
}
}
return overview, nil
}
type nodeFleetStatsRow struct {
Fleet int
Host string
NodeFleetCounts
}
func (s *NodeService) countNodeFleet(nodes []*model.Node, selfGUID string, overview bool) (NodeFleetCounts, NodeFleetCounts, error) {
ambiguous := ambiguousNodeGuids(nodes, selfGUID)
// Always reserve the local GUID, including when an old topology advertises a loop.
ambiguous[selfGUID] = struct{}{}
ambiguous[""] = struct{}{}
ambiguousGUIDs := make([]string, 0, len(ambiguous))
for guid := range ambiguous {
ambiguousGUIDs = append(ambiguousGUIDs, guid)
}
slices.Sort(ambiguousGUIDs)
fleetClients, fleetInbounds := "", ""
if overview {
fleetClients = "UNION ALL SELECT 1, '', id FROM clients"
fleetInbounds = "UNION ALL SELECT 1, '', COUNT(*) FROM hosted"
}
var rows []nodeFleetStatsRow
err := database.GetDB().Raw(`
WITH hosted AS (
SELECT i.id, CASE
WHEN i.node_id IS NULL THEN ''
WHEN COALESCE(i.origin_node_guid, '') NOT IN ? THEN i.origin_node_guid
WHEN COALESCE(i.origin_node_guid, '') = '' AND COALESCE(n.guid, '') NOT IN ? THEN n.guid
ELSE 'node:' || CAST(i.node_id AS TEXT)
END AS host
FROM inbounds i LEFT JOIN nodes n ON n.id = i.node_id
WHERE (? OR i.node_id IS NOT NULL)
), memberships AS (
SELECT DISTINCT hosted.host, ci.client_id
FROM hosted JOIN client_inbounds ci ON ci.inbound_id = hosted.id
), scoped AS (
SELECT 0 AS fleet, host, client_id FROM memberships
`+fleetClients+`
), classified AS (
SELECT s.fleet, s.host, CASE
WHEN (ct.expiry_time > 0 AND ct.expiry_time <= ?)
OR CASE
-- Subtract a nonnegative counter from a positive quota to stay in BIGINT range.
WHEN ct.total > 0 AND ct.down >= 0 THEN ct.up >= ct.total - ct.down
WHEN ct.total > 0 AND ct.up >= 0 THEN ct.down >= ct.total - ct.up
ELSE FALSE
END THEN 'depleted'
WHEN COALESCE(c.enable, FALSE) = FALSE THEN 'disabled'
ELSE 'active' END AS state
FROM scoped s JOIN clients c ON c.id = s.client_id
LEFT JOIN client_traffics ct ON ct.email = c.email
), clients_by_host AS (
SELECT fleet, host, COUNT(*) AS client_count,
COUNT(*) FILTER (WHERE state = 'active') AS active_count,
COUNT(*) FILTER (WHERE state = 'disabled') AS disabled_count,
COUNT(*) FILTER (WHERE state = 'depleted') AS depleted_count
FROM classified GROUP BY fleet, host
), inbound_counts AS (
SELECT 0 AS fleet, host, COUNT(*) AS inbound_count FROM hosted GROUP BY host
`+fleetInbounds+`
)
SELECT i.fleet, i.host, i.inbound_count, c.client_count, c.active_count, c.disabled_count, c.depleted_count
FROM inbound_counts i LEFT JOIN clients_by_host c ON c.fleet = i.fleet AND c.host = i.host
`, ambiguousGUIDs, ambiguousGUIDs, overview, time.Now().UnixMilli()).Scan(&rows).Error
if err != nil {
return NodeFleetCounts{}, NodeFleetCounts{}, err
}
byHost := make(map[string]NodeFleetCounts, len(rows))
var fleet NodeFleetCounts
for _, row := range rows {
if row.Fleet == 1 {
fleet = row.NodeFleetCounts
} else {
byHost[row.Host] = row.NodeFleetCounts
}
}
master := byHost[""]
online := s.onlineEmailsByGuid()
uniqueOnline := make(map[string]struct{})
if overview {
if process := currentXrayProcess(); process != nil {
for _, email := range process.GetLocalOnlineClients() {
uniqueOnline[email] = struct{}{}
}
}
}
master.OnlineCount = len(uniqueOnline)
totalOnline := (&InboundService{}).GetNodeOnlineTotals()
for _, node := range nodes {
guid := effectiveNodeGuid(node, ambiguous)
stats := byHost[guid]
node.InboundCount = stats.InboundCount
node.ClientCount = stats.ClientCount
node.ActiveCount = stats.ActiveCount
node.DisabledCount = stats.DisabledCount
node.DepletedCount = stats.DepletedCount
node.OnlineCount = len(online[guid])
node.OnlineTotalCount = totalOnline[node.Id]
if overview {
for email := range online[guid] {
uniqueOnline[email] = struct{}{}
}
}
}
fleet.OnlineCount = len(uniqueOnline)
return master, fleet, nil
}