mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-03 16:04:50 +03:00
fix(nodes): preserve standalone view and scope fleet monitoring
This commit is contained in:
@@ -18,7 +18,11 @@ async function fetchNodeOverview() {
|
||||
const emptyNodes: NodeRecord[] = [];
|
||||
|
||||
export function useNodeOverviewQuery() {
|
||||
const query = useQuery({ queryKey: keys.nodes.overview(), queryFn: fetchNodeOverview });
|
||||
const query = useQuery({
|
||||
queryKey: keys.nodes.overview(),
|
||||
queryFn: fetchNodeOverview,
|
||||
refetchInterval: 5_000,
|
||||
});
|
||||
return {
|
||||
nodes: query.data?.nodes ?? emptyNodes,
|
||||
master: query.data?.master,
|
||||
|
||||
@@ -4,7 +4,6 @@ import { useQueryClient } from '@tanstack/react-query';
|
||||
import { getSharedWebSocketClient } from '@/api/websocket';
|
||||
import { keys } from '@/api/queryKeys';
|
||||
import { isRecentLocalInvalidate } from '@/api/invalidationTracker';
|
||||
import { NodeOverviewSchema } from '@/schemas/node';
|
||||
|
||||
type Handler = (payload: unknown) => void;
|
||||
|
||||
@@ -42,11 +41,6 @@ export function useWebSocketBridge() {
|
||||
queryClient.setQueryData(keys.nodes.list(), payload);
|
||||
};
|
||||
|
||||
const onNodesOverview: Handler = (payload) => {
|
||||
const overview = NodeOverviewSchema.safeParse(payload);
|
||||
if (overview.success) queryClient.setQueryData(keys.nodes.overview(), overview.data);
|
||||
};
|
||||
|
||||
const onInbounds: Handler = (payload) => {
|
||||
if (!Array.isArray(payload)) return;
|
||||
queryClient.setQueryData(keys.inbounds.slim(), payload);
|
||||
@@ -55,7 +49,6 @@ export function useWebSocketBridge() {
|
||||
client.on('invalidate', onInvalidate);
|
||||
client.on('outbounds', onOutbounds);
|
||||
client.on('nodes', onNodes);
|
||||
client.on('nodesOverview', onNodesOverview);
|
||||
client.on('inbounds', onInbounds);
|
||||
client.connect();
|
||||
|
||||
@@ -63,7 +56,6 @@ export function useWebSocketBridge() {
|
||||
client.off('invalidate', onInvalidate);
|
||||
client.off('outbounds', onOutbounds);
|
||||
client.off('nodes', onNodes);
|
||||
client.off('nodesOverview', onNodesOverview);
|
||||
client.off('inbounds', onInbounds);
|
||||
clearTimeout(invalidateTimer);
|
||||
};
|
||||
|
||||
@@ -584,3 +584,69 @@
|
||||
margin-inline-start: 0;
|
||||
}
|
||||
}
|
||||
@container (width < 920px) {
|
||||
.node-fleet-table,
|
||||
.node-fleet-table thead,
|
||||
.node-fleet-table tbody,
|
||||
.node-fleet-table tr,
|
||||
.node-fleet-table .node-history-row td {
|
||||
display: block;
|
||||
min-width: 0;
|
||||
}
|
||||
.node-fleet-table colgroup {
|
||||
display: none;
|
||||
}
|
||||
.node-fleet-table thead th:not(:first-child) {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
}
|
||||
.node-fleet-table thead th:first-child {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding-inline: 10px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.node-fleet-table tbody > tr:not(.node-history-row) {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
height: auto;
|
||||
margin-block-start: 8px;
|
||||
padding: 10px;
|
||||
border: 1px solid var(--node-line);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.node-row-fleet {
|
||||
background: var(--node-fleet);
|
||||
}
|
||||
.node-fleet-table tbody td,
|
||||
.node-fleet-table .node-name-cell {
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
text-align: start;
|
||||
}
|
||||
.node-fleet-table .node-name-cell,
|
||||
.node-fleet-table tbody td:first-child {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.node-fleet-table .node-name-cell {
|
||||
grid-row: 1;
|
||||
}
|
||||
.node-fleet-table td[data-label]::before {
|
||||
display: block;
|
||||
margin-block-end: 4px;
|
||||
color: var(--node-secondary);
|
||||
font-size: 11px;
|
||||
content: attr(data-label);
|
||||
}
|
||||
.node-fleet-table .node-row-fleet td:first-child {
|
||||
box-shadow: none;
|
||||
}
|
||||
.node-fleet-table .node-history-row td {
|
||||
padding: 10px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -529,6 +529,7 @@ export default function NodeList({
|
||||
const now = useTelemetryClock(samples, nodesUpdatedAt);
|
||||
|
||||
const rows = useMemo<FleetRow[]>(() => {
|
||||
// Fleet monitoring, including Master, is shown only after a remote is registered.
|
||||
if (!nodes.length) return [];
|
||||
const masterTelemetry = freshTelemetry(master?.telemetry, now, nodesUpdatedAt);
|
||||
const remote = nodes.map((node): FleetRow & { kind: 'remote' } => ({
|
||||
@@ -793,7 +794,7 @@ export default function NodeList({
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="node-enabled">
|
||||
<td className="node-enabled" data-label={headers[1]}>
|
||||
{managed ? (
|
||||
<Switch
|
||||
size="small"
|
||||
@@ -817,7 +818,7 @@ export default function NodeList({
|
||||
</small>
|
||||
</div>
|
||||
</th>
|
||||
<td>
|
||||
<td data-label={headers[3]}>
|
||||
{url ? (
|
||||
<Tooltip
|
||||
title={showAddress ? url : undefined}
|
||||
@@ -836,7 +837,7 @@ export default function NodeList({
|
||||
'—'
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<td data-label={headers[4]}>
|
||||
{isFleet ? (
|
||||
<Tooltip
|
||||
trigger={['hover', 'focus', 'click']}
|
||||
@@ -883,20 +884,20 @@ export default function NodeList({
|
||||
/>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<td data-label={headers[5]}>
|
||||
<Hardware sample={row.telemetry} fleet={isFleet} system={!remote} />
|
||||
</td>
|
||||
<td>
|
||||
<td data-label={headers[6]}>
|
||||
<NetworkSpeedValues
|
||||
up={row.telemetry?.netUp}
|
||||
down={row.telemetry?.netDown}
|
||||
uploadFirst
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<td data-label={headers[7]}>
|
||||
<Connections sample={row.telemetry} fleet={isFleet} />
|
||||
</td>
|
||||
<td>
|
||||
<td data-label={headers[8]}>
|
||||
{isFleet ? (
|
||||
<div className="node-cell-stack node-runtime">
|
||||
<strong>
|
||||
@@ -940,7 +941,7 @@ export default function NodeList({
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<td data-label={headers[9]}>
|
||||
{row.kind === 'remote' ? (
|
||||
<ClientCounts counts={row.node} />
|
||||
) : (
|
||||
|
||||
@@ -26,15 +26,16 @@ const actions = {
|
||||
onRestart: noop,
|
||||
};
|
||||
|
||||
it('shows monitoring only while a node is configured and keeps Add Node available', async () => {
|
||||
it('hides Master and All nodes without a remote, even with fresh Master telemetry', async () => {
|
||||
const onAdd = vi.fn();
|
||||
const sampledAt = Date.now();
|
||||
function list(nodes: NodeRecord[]) {
|
||||
return (
|
||||
<NodeList
|
||||
{...actions}
|
||||
onAdd={onAdd}
|
||||
nodes={nodes}
|
||||
master={{ counts }}
|
||||
master={{ counts, telemetry: { sampledAt, cpuPct: 31 } }}
|
||||
fleet={counts}
|
||||
selectedIds={[]}
|
||||
onSelectionChange={noop}
|
||||
@@ -52,12 +53,12 @@ it('shows monitoring only while a node is configured and keeps Add Node availabl
|
||||
view.rerender(list([{ id: 1, name: 'disabled edge', enable: false, status: 'online' }]));
|
||||
const rows = screen.getAllByRole('row');
|
||||
expect(rows[1].textContent).toContain('All nodes');
|
||||
expect(rows[1].textContent).toContain('0/2 reporting');
|
||||
expect(rows[1].textContent).toContain('1/2 reporting');
|
||||
expect(rows[2].textContent).toContain('Master');
|
||||
expect(rows[3].textContent).toContain('disabled edge');
|
||||
fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'unmatched' } });
|
||||
expect(screen.getAllByRole('row')).toHaveLength(3);
|
||||
expect(screen.getByText('0/2 reporting')).toBeTruthy();
|
||||
expect(screen.getByText('1/2 reporting')).toBeTruthy();
|
||||
view.rerender(list([]));
|
||||
expect(screen.queryByRole('table')).toBeNull();
|
||||
expect(screen.queryByText(/totals use reporting nodes/)).toBeNull();
|
||||
|
||||
@@ -31,7 +31,6 @@ type NodeHeartbeatJob struct {
|
||||
settingService service.SettingService
|
||||
running sync.Mutex
|
||||
health map[int]nodeHealth
|
||||
localStatus func() *service.Status
|
||||
}
|
||||
|
||||
type nodeHealth struct {
|
||||
@@ -48,10 +47,6 @@ func NewNodeHeartbeatJob() *NodeHeartbeatJob {
|
||||
return &NodeHeartbeatJob{}
|
||||
}
|
||||
|
||||
func (j *NodeHeartbeatJob) SetLocalStatusSource(read func() *service.Status) {
|
||||
j.localStatus = read
|
||||
}
|
||||
|
||||
func (j *NodeHeartbeatJob) Run() {
|
||||
if !j.running.TryLock() {
|
||||
return
|
||||
@@ -91,17 +86,16 @@ func (j *NodeHeartbeatJob) Run() {
|
||||
if !websocket.HasClients() {
|
||||
return
|
||||
}
|
||||
var local *service.Status
|
||||
if j.localStatus != nil {
|
||||
local = j.localStatus()
|
||||
if len(nodes) == 0 {
|
||||
websocket.BroadcastNodes([]*service.NodeView{})
|
||||
return
|
||||
}
|
||||
updated, err := j.nodeService.GetNodeOverview(local)
|
||||
updated, err := j.nodeService.GetNodeTreeView()
|
||||
if err != nil {
|
||||
logger.Warning("node heartbeat: load nodes for broadcast failed:", err)
|
||||
return
|
||||
}
|
||||
websocket.BroadcastNodes(updated.Nodes)
|
||||
websocket.BroadcastNodesOverview(updated)
|
||||
websocket.BroadcastNodes(updated)
|
||||
}
|
||||
|
||||
func (j *NodeHeartbeatJob) probeOne(n *model.Node) service.HeartbeatPatch {
|
||||
|
||||
@@ -34,7 +34,7 @@ type NodeOverview struct {
|
||||
}
|
||||
|
||||
func (s *NodeService) GetNodeOverview(local *Status) (*NodeOverview, error) {
|
||||
nodes, master, fleet, err := s.getNodeTreeWithCounts()
|
||||
nodes, master, fleet, err := s.getNodeTreeWithCounts(true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -63,7 +63,7 @@ type nodeFleetStatsRow struct {
|
||||
NodeFleetCounts
|
||||
}
|
||||
|
||||
func (s *NodeService) countNodeFleet(nodes []*model.Node, selfGUID string) (NodeFleetCounts, NodeFleetCounts, error) {
|
||||
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{}{}
|
||||
@@ -73,6 +73,11 @@ func (s *NodeService) countNodeFleet(nodes []*model.Node, selfGUID string) (Node
|
||||
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 (
|
||||
@@ -83,12 +88,13 @@ func (s *NodeService) countNodeFleet(nodes []*model.Node, selfGUID string) (Node
|
||||
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
|
||||
UNION ALL SELECT 1, '', id FROM clients
|
||||
`+fleetClients+`
|
||||
), classified AS (
|
||||
SELECT s.fleet, s.host, CASE
|
||||
WHEN (ct.expiry_time > 0 AND ct.expiry_time <= ?)
|
||||
@@ -105,11 +111,11 @@ func (s *NodeService) countNodeFleet(nodes []*model.Node, selfGUID string) (Node
|
||||
FROM classified GROUP BY fleet, host
|
||||
), inbound_counts AS (
|
||||
SELECT 0 AS fleet, host, COUNT(*) AS inbound_count FROM hosted GROUP BY host
|
||||
UNION ALL SELECT 1, '', COUNT(*) FROM hosted
|
||||
`+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, time.Now().UnixMilli()).Scan(&rows).Error
|
||||
`, ambiguousGUIDs, ambiguousGUIDs, overview, time.Now().UnixMilli()).Scan(&rows).Error
|
||||
if err != nil {
|
||||
return NodeFleetCounts{}, NodeFleetCounts{}, err
|
||||
}
|
||||
@@ -126,9 +132,11 @@ func (s *NodeService) countNodeFleet(nodes []*model.Node, selfGUID string) (Node
|
||||
master := byHost[""]
|
||||
online := s.onlineEmailsByGuid()
|
||||
uniqueOnline := make(map[string]struct{})
|
||||
if process := currentXrayProcess(); process != nil {
|
||||
for _, email := range process.GetLocalOnlineClients() {
|
||||
uniqueOnline[email] = struct{}{}
|
||||
if overview {
|
||||
if process := currentXrayProcess(); process != nil {
|
||||
for _, email := range process.GetLocalOnlineClients() {
|
||||
uniqueOnline[email] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
master.OnlineCount = len(uniqueOnline)
|
||||
@@ -143,8 +151,10 @@ func (s *NodeService) countNodeFleet(nodes []*model.Node, selfGUID string) (Node
|
||||
node.DepletedCount = stats.DepletedCount
|
||||
node.OnlineCount = len(online[guid])
|
||||
node.OnlineTotalCount = totalOnline[node.Id]
|
||||
for email := range online[guid] {
|
||||
uniqueOnline[email] = struct{}{}
|
||||
if overview {
|
||||
for email := range online[guid] {
|
||||
uniqueOnline[email] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
fleet.OnlineCount = len(uniqueOnline)
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -174,6 +175,20 @@ func TestNodeOverviewCountsHostMembershipsAndUniqueFleetClients(t *testing.T) {
|
||||
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) {
|
||||
|
||||
@@ -117,7 +117,7 @@ func TestRecountByGuid_SplitsClonedNodesWithSharedGuid(t *testing.T) {
|
||||
}
|
||||
|
||||
nodes := []*model.Node{n1, n2, n3}
|
||||
if _, _, err := svc.countNodeFleet(nodes, selfGuid); err != nil {
|
||||
if _, _, err := svc.countNodeFleet(nodes, selfGuid, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
|
||||
@@ -129,11 +129,11 @@ func cachedDescendants() []model.NodeSummary {
|
||||
// nodes are read-only projections (Id == 0). Used by the Nodes page and the
|
||||
// heartbeat broadcast — never for probing/syncing, which stay on ListOperational.
|
||||
func (s *NodeService) GetNodeTree() ([]*model.Node, error) {
|
||||
nodes, _, _, err := s.getNodeTreeWithCounts()
|
||||
nodes, _, _, err := s.getNodeTreeWithCounts(false)
|
||||
return nodes, err
|
||||
}
|
||||
|
||||
func (s *NodeService) getNodeTreeWithCounts() ([]*model.Node, NodeFleetCounts, NodeFleetCounts, error) {
|
||||
func (s *NodeService) getNodeTreeWithCounts(overview bool) ([]*model.Node, NodeFleetCounts, NodeFleetCounts, error) {
|
||||
nodes, err := s.ListOperational()
|
||||
if err != nil || len(nodes) == 0 {
|
||||
return nodes, NodeFleetCounts{}, NodeFleetCounts{}, err
|
||||
@@ -181,7 +181,7 @@ func (s *NodeService) getNodeTreeWithCounts() ([]*model.Node, NodeFleetCounts, N
|
||||
})
|
||||
}
|
||||
all := append(nodes, transitive...)
|
||||
master, fleet, err := s.countNodeFleet(all, selfGuid)
|
||||
master, fleet, err := s.countNodeFleet(all, selfGuid, overview)
|
||||
return all, master, fleet, err
|
||||
}
|
||||
|
||||
|
||||
@@ -364,7 +364,6 @@ func (s *Server) startTask(restartXray bool, loc *time.Location) {
|
||||
_, _ = s.cron.AddJob(cadenceClientIPScan, job.NewCheckClientIpJob())
|
||||
|
||||
nodeHeartbeat := job.NewNodeHeartbeatJob()
|
||||
nodeHeartbeat.SetLocalStatusSource(s.api.LastStatus)
|
||||
_, _ = s.cron.AddJob(cadenceNodeHeartbeat, nodeHeartbeat)
|
||||
|
||||
s.nodeTrafficJob = job.NewNodeTrafficSyncJob()
|
||||
|
||||
@@ -14,18 +14,17 @@ import (
|
||||
type MessageType string
|
||||
|
||||
const (
|
||||
MessageTypeStatus MessageType = "status"
|
||||
MessageTypeTraffic MessageType = "traffic"
|
||||
MessageTypeInbounds MessageType = "inbounds"
|
||||
MessageTypeOutbounds MessageType = "outbounds"
|
||||
MessageTypeNodes MessageType = "nodes"
|
||||
MessageTypeNodesOverview MessageType = "nodesOverview"
|
||||
MessageTypeNotification MessageType = "notification"
|
||||
MessageTypeXrayState MessageType = "xray_state"
|
||||
MessageTypeClientStats MessageType = "client_stats"
|
||||
MessageTypeClients MessageType = "clients"
|
||||
MessageTypeInvalidate MessageType = "invalidate"
|
||||
maxMessageSize = 10 * 1024 * 1024 // 10MB
|
||||
MessageTypeStatus MessageType = "status"
|
||||
MessageTypeTraffic MessageType = "traffic"
|
||||
MessageTypeInbounds MessageType = "inbounds"
|
||||
MessageTypeOutbounds MessageType = "outbounds"
|
||||
MessageTypeNodes MessageType = "nodes"
|
||||
MessageTypeNotification MessageType = "notification"
|
||||
MessageTypeXrayState MessageType = "xray_state"
|
||||
MessageTypeClientStats MessageType = "client_stats"
|
||||
MessageTypeClients MessageType = "clients"
|
||||
MessageTypeInvalidate MessageType = "invalidate"
|
||||
maxMessageSize = 10 * 1024 * 1024 // 10MB
|
||||
|
||||
enqueueTimeout = 100 * time.Millisecond
|
||||
clientSendQueue = 512 // ~50s of buffering for a momentarily slow browser.
|
||||
|
||||
@@ -69,12 +69,6 @@ func BroadcastNodes(nodes any) {
|
||||
}
|
||||
}
|
||||
|
||||
func BroadcastNodesOverview(overview any) {
|
||||
if hub := GetHub(); hub != nil {
|
||||
hub.Broadcast(MessageTypeNodesOverview, overview)
|
||||
}
|
||||
}
|
||||
|
||||
// BroadcastOutbounds broadcasts outbounds list update to all connected clients.
|
||||
func BroadcastOutbounds(outbounds any) {
|
||||
if hub := GetHub(); hub != nil {
|
||||
|
||||
Reference in New Issue
Block a user