mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-29 22:14:50 +03:00
feat(nodes): show live network throughput (#7249)
Comparing current traffic across nodes meant opening each node's history chart. The heartbeat already carries every node's upload and download rate. Show both rates in a stacked column of the Nodes table, between Memory and Xray Version, and in the mobile detail dialog, which now follows heartbeat updates. A measured idle link reads 0 B/s; a disabled, offline or transitive node, a peer too old to report throughput, and a sample older than 30 seconds read as a dash. The sample's age is computed on the master and anchored to when the browser received it, so a skewed browser clock does not blank the column. The probe now records a missing or invalid direction as unavailable where it used to store zero, so such peers also stop adding zero points to the history chart. Fixes #7238
This commit is contained in:
@@ -4720,6 +4720,12 @@
|
||||
"example": true,
|
||||
"type": "boolean"
|
||||
},
|
||||
"heartbeatAgeMillis": {
|
||||
"example": 1250,
|
||||
"format": "int64",
|
||||
"nullable": true,
|
||||
"type": "integer"
|
||||
},
|
||||
"id": {
|
||||
"example": 1,
|
||||
"type": "integer"
|
||||
@@ -13570,6 +13576,7 @@
|
||||
"enable": true,
|
||||
"guid": "node-guid",
|
||||
"hasApiToken": true,
|
||||
"heartbeatAgeMillis": 1250,
|
||||
"id": 1,
|
||||
"inboundCount": 3,
|
||||
"inboundSyncMode": "all",
|
||||
@@ -13775,6 +13782,7 @@
|
||||
"enable": true,
|
||||
"guid": "node-guid",
|
||||
"hasApiToken": true,
|
||||
"heartbeatAgeMillis": 1250,
|
||||
"id": 1,
|
||||
"inboundCount": 3,
|
||||
"inboundSyncMode": "all",
|
||||
@@ -13929,6 +13937,7 @@
|
||||
"enable": true,
|
||||
"guid": "node-guid",
|
||||
"hasApiToken": true,
|
||||
"heartbeatAgeMillis": 1250,
|
||||
"id": 1,
|
||||
"inboundCount": 3,
|
||||
"inboundSyncMode": "all",
|
||||
@@ -19729,6 +19738,7 @@
|
||||
"enable": true,
|
||||
"guid": "node-guid",
|
||||
"hasApiToken": true,
|
||||
"heartbeatAgeMillis": 1250,
|
||||
"id": 1,
|
||||
"inboundCount": 3,
|
||||
"inboundSyncMode": "all",
|
||||
|
||||
@@ -4720,6 +4720,12 @@
|
||||
"example": true,
|
||||
"type": "boolean"
|
||||
},
|
||||
"heartbeatAgeMillis": {
|
||||
"example": 1250,
|
||||
"format": "int64",
|
||||
"nullable": true,
|
||||
"type": "integer"
|
||||
},
|
||||
"id": {
|
||||
"example": 1,
|
||||
"type": "integer"
|
||||
@@ -13570,6 +13576,7 @@
|
||||
"enable": true,
|
||||
"guid": "node-guid",
|
||||
"hasApiToken": true,
|
||||
"heartbeatAgeMillis": 1250,
|
||||
"id": 1,
|
||||
"inboundCount": 3,
|
||||
"inboundSyncMode": "all",
|
||||
@@ -13775,6 +13782,7 @@
|
||||
"enable": true,
|
||||
"guid": "node-guid",
|
||||
"hasApiToken": true,
|
||||
"heartbeatAgeMillis": 1250,
|
||||
"id": 1,
|
||||
"inboundCount": 3,
|
||||
"inboundSyncMode": "all",
|
||||
@@ -13929,6 +13937,7 @@
|
||||
"enable": true,
|
||||
"guid": "node-guid",
|
||||
"hasApiToken": true,
|
||||
"heartbeatAgeMillis": 1250,
|
||||
"id": 1,
|
||||
"inboundCount": 3,
|
||||
"inboundSyncMode": "all",
|
||||
@@ -19729,6 +19738,7 @@
|
||||
"enable": true,
|
||||
"guid": "node-guid",
|
||||
"hasApiToken": true,
|
||||
"heartbeatAgeMillis": 1250,
|
||||
"id": 1,
|
||||
"inboundCount": 3,
|
||||
"inboundSyncMode": "all",
|
||||
|
||||
@@ -74,6 +74,7 @@ export function useNodesQuery() {
|
||||
|
||||
return {
|
||||
nodes,
|
||||
nodesUpdatedAt: query.dataUpdatedAt,
|
||||
totals,
|
||||
loading: query.isFetching,
|
||||
fetched: query.data !== undefined || query.isError,
|
||||
|
||||
@@ -1215,6 +1215,7 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"enable": true,
|
||||
"guid": "node-guid",
|
||||
"hasApiToken": true,
|
||||
"heartbeatAgeMillis": 1250,
|
||||
"id": 1,
|
||||
"inboundCount": 3,
|
||||
"inboundSyncMode": "all",
|
||||
|
||||
@@ -4694,6 +4694,12 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"example": true,
|
||||
"type": "boolean"
|
||||
},
|
||||
"heartbeatAgeMillis": {
|
||||
"example": 1250,
|
||||
"format": "int64",
|
||||
"nullable": true,
|
||||
"type": "integer"
|
||||
},
|
||||
"id": {
|
||||
"example": 1,
|
||||
"type": "integer"
|
||||
|
||||
@@ -1066,6 +1066,7 @@ export interface NodeView {
|
||||
enable: boolean;
|
||||
guid: string;
|
||||
hasApiToken: boolean;
|
||||
heartbeatAgeMillis?: number | null;
|
||||
id: number;
|
||||
inboundCount: number;
|
||||
inboundSyncMode: string;
|
||||
|
||||
@@ -1131,6 +1131,7 @@ export const NodeViewSchema = z.object({
|
||||
enable: z.boolean(),
|
||||
guid: z.string(),
|
||||
hasApiToken: z.boolean(),
|
||||
heartbeatAgeMillis: z.number().int().nullable().optional(),
|
||||
id: z.number().int(),
|
||||
inboundCount: z.number().int(),
|
||||
inboundSyncMode: z.string(),
|
||||
|
||||
@@ -142,3 +142,19 @@
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.node-network-speed {
|
||||
display: inline-grid;
|
||||
row-gap: 2px;
|
||||
text-align: start;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.node-network-direction {
|
||||
display: grid;
|
||||
grid-template-columns: 1em auto;
|
||||
column-gap: 4px;
|
||||
align-items: center;
|
||||
white-space: nowrap;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
} from '@ant-design/icons';
|
||||
|
||||
import NodeHistoryPanel from './NodeHistoryPanel';
|
||||
import NodeNetworkSpeed from './NodeNetworkSpeed';
|
||||
import type { NodeRecord } from '@/api/queries/useNodesQuery';
|
||||
import { isPanelUpdateAvailable } from '@/lib/panel-version';
|
||||
import { activateOnKey } from '@/utils/a11y';
|
||||
@@ -30,6 +31,7 @@ import './NodeList.css';
|
||||
|
||||
interface NodeListProps {
|
||||
nodes: NodeRecord[];
|
||||
nodesUpdatedAt?: number;
|
||||
loading?: boolean;
|
||||
isMobile?: boolean;
|
||||
latestVersion?: string;
|
||||
@@ -209,6 +211,7 @@ function OnlineTag({ node, compact }: { node: NodeRecord; compact?: boolean }) {
|
||||
|
||||
export default function NodeList({
|
||||
nodes,
|
||||
nodesUpdatedAt,
|
||||
loading = false,
|
||||
isMobile = false,
|
||||
latestVersion = '',
|
||||
@@ -229,7 +232,7 @@ export default function NodeList({
|
||||
const relativeTime = useRelativeTime();
|
||||
|
||||
const [showAddress, setShowAddress] = useState(false);
|
||||
const [statsNode, setStatsNode] = useState<NodeRow | null>(null);
|
||||
const [statsNodeId, setStatsNodeId] = useState<number | null>(null);
|
||||
const [expandedIds, setExpandedIds] = useState<Set<number>>(new Set());
|
||||
|
||||
const restartItems = useCallback(
|
||||
@@ -288,6 +291,11 @@ export default function NodeList({
|
||||
return ordered;
|
||||
}, [nodes]);
|
||||
|
||||
const statsNode =
|
||||
statsNodeId === null
|
||||
? undefined
|
||||
: dataSource.find((node) => !node.transitive && node.id === statsNodeId);
|
||||
|
||||
function toggleExpanded(id: number) {
|
||||
setExpandedIds((prev) => {
|
||||
const next = new Set(prev);
|
||||
@@ -480,6 +488,13 @@ export default function NodeList({
|
||||
width: 90,
|
||||
render: (_value, record) => formatPct(record.memPct),
|
||||
},
|
||||
{
|
||||
title: t('pages.nodes.networkSpeed'),
|
||||
key: 'networkSpeed',
|
||||
align: 'center',
|
||||
width: 125,
|
||||
render: (_value, record) => <NodeNetworkSpeed node={record} receivedAt={nodesUpdatedAt} />,
|
||||
},
|
||||
{
|
||||
title: t('pages.nodes.xrayVersion'),
|
||||
dataIndex: 'xrayVersion',
|
||||
@@ -585,6 +600,7 @@ export default function NodeList({
|
||||
showAddress,
|
||||
relativeTime,
|
||||
latestVersion,
|
||||
nodesUpdatedAt,
|
||||
onToggleEnable,
|
||||
onProbe,
|
||||
onEdit,
|
||||
@@ -706,8 +722,8 @@ export default function NodeList({
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={t('info')}
|
||||
onClick={() => setStatsNode(record)}
|
||||
onKeyDown={activateOnKey(() => setStatsNode(record))}
|
||||
onClick={() => setStatsNodeId(record.id)}
|
||||
onKeyDown={activateOnKey(() => setStatsNodeId(record.id))}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Switch
|
||||
@@ -795,7 +811,7 @@ export default function NodeList({
|
||||
width={360}
|
||||
centered
|
||||
title={statsNode?.name || ''}
|
||||
onCancel={() => setStatsNode(null)}
|
||||
onCancel={() => setStatsNodeId(null)}
|
||||
>
|
||||
{statsNode && (
|
||||
<div className="card-stats">
|
||||
@@ -860,6 +876,10 @@ export default function NodeList({
|
||||
<span className="stat-label">{t('pages.nodes.mem')}</span>
|
||||
<Tag>{formatPct(statsNode.memPct)}</Tag>
|
||||
</div>
|
||||
<div className="stat-row">
|
||||
<span className="stat-label">{t('pages.nodes.networkSpeed')}</span>
|
||||
<NodeNetworkSpeed node={statsNode} receivedAt={nodesUpdatedAt} />
|
||||
</div>
|
||||
<div className="stat-row">
|
||||
<span className="stat-label">{t('pages.nodes.xrayVersion')}</span>
|
||||
<Tag>{statsNode.xrayVersion || '-'}</Tag>
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { useCallback, useSyncExternalStore } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Tooltip, theme } from 'antd';
|
||||
import { ArrowDownOutlined, ArrowUpOutlined } from '@ant-design/icons';
|
||||
|
||||
import type { NodeRecord } from '@/api/queries/useNodesQuery';
|
||||
import { SizeFormatter } from '@/utils';
|
||||
|
||||
const HEARTBEAT_FRESHNESS_MS = 30_000;
|
||||
|
||||
export default function NodeNetworkSpeed({
|
||||
node,
|
||||
receivedAt,
|
||||
}: {
|
||||
node: NodeRecord;
|
||||
receivedAt?: number;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { token } = theme.useToken();
|
||||
const expiration =
|
||||
receivedAt && node.heartbeatAgeMillis != null
|
||||
? receivedAt + HEARTBEAT_FRESHNESS_MS - node.heartbeatAgeMillis
|
||||
: node.lastHeartbeat
|
||||
? node.lastHeartbeat * 1000 + HEARTBEAT_FRESHNESS_MS
|
||||
: 0;
|
||||
const subscribe = useCallback(
|
||||
(onChange: () => void) => {
|
||||
const delay = expiration - Date.now();
|
||||
const timer =
|
||||
delay > 0 && delay <= HEARTBEAT_FRESHNESS_MS
|
||||
? window.setTimeout(onChange, delay)
|
||||
: undefined;
|
||||
return () => window.clearTimeout(timer);
|
||||
},
|
||||
[expiration],
|
||||
);
|
||||
const isFresh = () => {
|
||||
const delay = expiration - Date.now();
|
||||
return delay > 0 && delay <= HEARTBEAT_FRESHNESS_MS;
|
||||
};
|
||||
const fresh = useSyncExternalStore(subscribe, isFresh);
|
||||
const available = node.enable && node.status === 'online' && !node.transitive && fresh;
|
||||
const directions = [
|
||||
{
|
||||
key: 'netDown' as const,
|
||||
label: t('pages.index.download'),
|
||||
Icon: ArrowDownOutlined,
|
||||
color: token.colorTextTertiary,
|
||||
},
|
||||
{
|
||||
key: 'netUp' as const,
|
||||
label: t('pages.index.upload'),
|
||||
Icon: ArrowUpOutlined,
|
||||
color: token.colorPrimary,
|
||||
},
|
||||
];
|
||||
return (
|
||||
<span className="node-network-speed">
|
||||
{directions.map(({ key, label, Icon, color }) => {
|
||||
const rate = node[key];
|
||||
const value =
|
||||
available &&
|
||||
!node.unavailableMetrics?.includes(key) &&
|
||||
typeof rate === 'number' &&
|
||||
Number.isFinite(rate) &&
|
||||
rate >= 0
|
||||
? SizeFormatter.speedFormat(rate)
|
||||
: '—';
|
||||
return (
|
||||
<Tooltip key={key} title={label}>
|
||||
<span
|
||||
role="img"
|
||||
aria-label={label + ' ' + value}
|
||||
className="node-network-direction"
|
||||
dir="ltr"
|
||||
>
|
||||
<Icon aria-hidden style={{ color }} />
|
||||
<span aria-hidden>{value}</span>
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -77,7 +77,7 @@ export default function NodesPage() {
|
||||
setMessageInstance(messageApi);
|
||||
}, [messageApi]);
|
||||
|
||||
const { nodes, loading, fetched, fetchError, refetch, totals } = useNodesQuery();
|
||||
const { nodes, nodesUpdatedAt, loading, fetched, fetchError, refetch, totals } = useNodesQuery();
|
||||
const {
|
||||
create,
|
||||
update,
|
||||
@@ -409,6 +409,7 @@ export default function NodesPage() {
|
||||
<Col span={24}>
|
||||
<NodeList
|
||||
nodes={nodes}
|
||||
nodesUpdatedAt={nodesUpdatedAt}
|
||||
loading={loading}
|
||||
isMobile={isMobile}
|
||||
latestVersion={latestVersion}
|
||||
|
||||
@@ -16,6 +16,9 @@ export const NodeRecordSchema = z
|
||||
latencyMs: z.number().optional(),
|
||||
cpuPct: z.number().optional(),
|
||||
memPct: z.number().optional(),
|
||||
netDown: z.number().optional(),
|
||||
heartbeatAgeMillis: z.number().nonnegative().optional(),
|
||||
netUp: z.number().optional(),
|
||||
xrayVersion: z.string().optional(),
|
||||
panelVersion: z.string().optional(),
|
||||
uptimeSecs: z.number().optional(),
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { fireEvent, screen, within } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { useState } from 'react';
|
||||
import { act, fireEvent, screen, within } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import NodeList from '@/pages/nodes/NodeList';
|
||||
import NodeNetworkSpeed from '@/pages/nodes/NodeNetworkSpeed';
|
||||
import { NodeRecordSchema } from '@/schemas/node';
|
||||
import { renderWithProviders } from './test-utils';
|
||||
const noop = () => {};
|
||||
@@ -73,3 +75,101 @@ describe('node metric availability', () => {
|
||||
expect(cells[headers.indexOf('Uptime')].textContent).toBe('-');
|
||||
});
|
||||
});
|
||||
|
||||
describe('node network speed', () => {
|
||||
const controls = {
|
||||
selectedIds: [],
|
||||
onSelectionChange: noop,
|
||||
onAdd: noop,
|
||||
onMtls: noop,
|
||||
onEdit: noop,
|
||||
onDelete: noop,
|
||||
onProbe: noop,
|
||||
onToggleEnable: noop,
|
||||
onUpdateNode: noop,
|
||||
onUpdateSelected: noop,
|
||||
onRestart: noop,
|
||||
};
|
||||
it.each([false, true])(
|
||||
'renders current directions and preserves measured zero (mobile=%s)',
|
||||
(isMobile) => {
|
||||
const node = NodeRecordSchema.parse({
|
||||
id: 1,
|
||||
name: 'edge',
|
||||
enable: true,
|
||||
status: 'online',
|
||||
lastHeartbeat: Math.floor(Date.now() / 1000),
|
||||
netDown: 2048,
|
||||
netUp: 0,
|
||||
});
|
||||
function Fixture() {
|
||||
const [record, setRecord] = useState(node);
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setRecord({ ...record, lastHeartbeat: (node.lastHeartbeat ?? 0) - 120 })
|
||||
}
|
||||
>
|
||||
Age sample
|
||||
</button>
|
||||
<NodeList {...controls} nodes={[record]} isMobile={isMobile} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
renderWithProviders(<Fixture />);
|
||||
if (isMobile) fireEvent.click(screen.getByRole('button', { name: 'More Information' }));
|
||||
expect(screen.getByLabelText(/^download .*2\.00 KB\/s$/i).textContent).toContain('2.00 KB/s');
|
||||
expect(screen.getByLabelText(/^upload .*0 B\/s$/i).textContent).toContain('0 B/s');
|
||||
// A heartbeat cache update must also refresh the open mobile stats dialog.
|
||||
fireEvent.click(screen.getByText('Age sample'));
|
||||
expect(screen.getByLabelText(/^download .*—$/i).textContent).toContain('—');
|
||||
},
|
||||
);
|
||||
|
||||
it.each([-120, 120])('expires throughput with %s seconds of clock skew', (skew) => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const node = NodeRecordSchema.parse({
|
||||
id: 1,
|
||||
name: 'edge',
|
||||
enable: true,
|
||||
status: 'online',
|
||||
lastHeartbeat: Math.floor(Date.now() / 1000) + skew,
|
||||
heartbeatAgeMillis: 250,
|
||||
netDown: 2048,
|
||||
netUp: 0,
|
||||
});
|
||||
renderWithProviders(<NodeNetworkSpeed node={node} receivedAt={Date.now()} />);
|
||||
expect(screen.getByLabelText(/^download .*2\.00 KB\/s$/i).textContent).toContain('2.00 KB/s');
|
||||
act(() => vi.advanceTimersByTime(30_000));
|
||||
expect(screen.getByLabelText(/^download .*—$/i).textContent).toContain('—');
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('honors disabled, legacy, and transitive availability', () => {
|
||||
const base = { enable: true, status: 'online', lastHeartbeat: Math.floor(Date.now() / 1000) };
|
||||
renderWithProviders(
|
||||
<NodeList
|
||||
{...controls}
|
||||
nodes={[
|
||||
{
|
||||
...base,
|
||||
id: 1,
|
||||
name: 'legacy',
|
||||
unavailableMetrics: ['netUp', 'netDown'],
|
||||
netDown: 0,
|
||||
netUp: 0,
|
||||
},
|
||||
{ ...base, id: 2, name: 'disabled', enable: false, netDown: 123, netUp: 123 },
|
||||
{ ...base, id: 3, name: 'descendant', transitive: true, netDown: 123, netUp: 123 },
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getAllByLabelText(/^download .*—$/i)).toHaveLength(3);
|
||||
expect(screen.getAllByLabelText(/^upload .*—$/i)).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1379,13 +1379,10 @@ func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string)
|
||||
State string `json:"state"`
|
||||
ErrorMsg string `json:"errorMsg"`
|
||||
} `json:"xray"`
|
||||
PanelVersion string `json:"panelVersion"`
|
||||
PanelGuid string `json:"panelGuid"`
|
||||
Uptime uint64 `json:"uptime"`
|
||||
NetIO struct {
|
||||
Up uint64 `json:"up"`
|
||||
Down uint64 `json:"down"`
|
||||
} `json:"netIO"`
|
||||
PanelVersion string `json:"panelVersion"`
|
||||
PanelGuid string `json:"panelGuid"`
|
||||
Uptime uint64 `json:"uptime"`
|
||||
NetIO json.RawMessage `json:"netIO"`
|
||||
} `json:"obj"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, maxProbeBodyBytes)).Decode(&envelope); err != nil {
|
||||
@@ -1418,8 +1415,19 @@ func (s *NodeService) probe(ctx context.Context, n *model.Node, proxyURL string)
|
||||
}
|
||||
patch.Guid = o.PanelGuid
|
||||
patch.UptimeSecs = o.Uptime
|
||||
patch.NetUp = o.NetIO.Up
|
||||
patch.NetDown = o.NetIO.Down
|
||||
var network map[string]json.RawMessage
|
||||
_ = json.Unmarshal(o.NetIO, &network)
|
||||
for _, metric := range []struct {
|
||||
key, direction string
|
||||
value *uint64
|
||||
}{{"netUp", "up", &patch.NetUp}, {"netDown", "down", &patch.NetDown}} {
|
||||
var value *uint64
|
||||
if json.Unmarshal(network[metric.direction], &value) == nil && value != nil {
|
||||
*metric.value = *value
|
||||
} else if !slices.Contains(patch.UnavailableMetrics, metric.key) {
|
||||
patch.UnavailableMetrics = append(patch.UnavailableMetrics, metric.key)
|
||||
}
|
||||
}
|
||||
return patch, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ type NodeView struct {
|
||||
Guid string `json:"guid" example:"node-guid"`
|
||||
Status string `json:"status" example:"online"`
|
||||
LastHeartbeat int64 `json:"lastHeartbeat" example:"1700000000"`
|
||||
HeartbeatAgeMillis *int64 `json:"heartbeatAgeMillis,omitempty" example:"1250"`
|
||||
LatencyMs int `json:"latencyMs" example:"42"`
|
||||
XrayVersion string `json:"xrayVersion" example:"25.10.31"`
|
||||
PanelVersion string `json:"panelVersion" example:"v3.x.x"`
|
||||
|
||||
@@ -120,8 +120,8 @@ func unavailableMetricsOf(t *testing.T, value any) []string {
|
||||
}
|
||||
|
||||
const (
|
||||
unavailableStatusBody = `{"success":true,"obj":{"cpu":0,"uptime":0,"unavailableMetrics":["cpu","uptime"],"mem":{"current":1,"total":2},"xray":{"state":"running"}}}`
|
||||
zeroStatusBody = `{"success":true,"obj":{"cpu":0,"uptime":0,"mem":{"current":1,"total":2},"xray":{"state":"running"}}}`
|
||||
unavailableStatusBody = `{"success":true,"obj":{"cpu":0,"uptime":0,"unavailableMetrics":["cpu","uptime"],"mem":{"current":1,"total":2},"netIO":{"up":0,"down":0},"xray":{"state":"running"}}}`
|
||||
zeroStatusBody = `{"success":true,"obj":{"cpu":0,"uptime":0,"mem":{"current":1,"total":2},"netIO":{"up":0,"down":0},"xray":{"state":"running"}}}`
|
||||
)
|
||||
|
||||
func TestProbeKeepsMetricAvailability(t *testing.T) {
|
||||
@@ -230,3 +230,27 @@ func TestNodeAvailabilityColumnKeepsLegacyRows(t *testing.T) {
|
||||
t.Fatalf("legacy row changed: id=%d availability=%v", stored.Id, stored.UnavailableMetrics)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProbeDistinguishesMissingNetworkMetricsFromZero(t *testing.T) {
|
||||
svc, n, setBody := availabilityNodeFixture(t, `{"success":true,"obj":{"panelGuid":"legacy"}}`)
|
||||
patch, err := svc.Probe(context.Background(), n)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !slices.Equal(patch.UnavailableMetrics, []string{"netUp", "netDown"}) {
|
||||
t.Fatalf("legacy metric availability = %v, want missing throughput directions", patch.UnavailableMetrics)
|
||||
}
|
||||
setBody(`{"success":true,"obj":{"panelGuid":"legacy","netIO":{"up":0}}}`)
|
||||
patch, err = svc.Probe(context.Background(), n)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if patch.NetUp != 0 || !slices.Equal(patch.UnavailableMetrics, []string{"netDown"}) {
|
||||
t.Fatalf("zero upload or missing download was lost: %+v", patch)
|
||||
}
|
||||
setBody(`{"success":true,"obj":{"panelGuid":"legacy","netIO":{"up":-1,"down":250}}}`)
|
||||
patch, err = svc.Probe(context.Background(), n)
|
||||
if err != nil || patch.NetDown != 250 || !slices.Equal(patch.UnavailableMetrics, []string{"netUp"}) {
|
||||
t.Fatalf("one invalid rate should not hide the valid direction: %+v, %v", patch, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
@@ -184,7 +185,14 @@ func (s *NodeService) GetNodeTreeView() ([]*NodeView, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toNodeViews(nodes), nil
|
||||
views := toNodeViews(nodes)
|
||||
now := time.Now()
|
||||
for _, view := range views {
|
||||
if view.LastHeartbeat > 0 && !view.Transitive {
|
||||
view.HeartbeatAgeMillis = new(max(0, now.Sub(time.Unix(view.LastHeartbeat, 0)).Milliseconds()))
|
||||
}
|
||||
}
|
||||
return views, nil
|
||||
}
|
||||
|
||||
// recountByGuid recomputes InboundCount/OnlineCount/DepletedCount for every node
|
||||
|
||||
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
@@ -80,3 +81,29 @@ func TestGetNodeTree_SurfacesTransitiveNodeNestedUnderParent(t *testing.T) {
|
||||
t.Errorf("transitive Node3 should host its 1 inbound, got %d", node3.InboundCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNodeTreeViewReportsMasterRelativeHeartbeatAge(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
now := time.Now()
|
||||
for _, node := range []model.Node{
|
||||
{Name: "sampled", Address: "10.0.0.2", Port: 2053, LastHeartbeat: now.Add(-5 * time.Second).Unix()},
|
||||
{Name: "unprobed", Address: "10.0.0.3", Port: 2053},
|
||||
} {
|
||||
if err := database.GetDB().Create(&node).Error; err != nil {
|
||||
t.Fatalf("create node: %v", err)
|
||||
}
|
||||
}
|
||||
views, err := (&NodeService{}).GetNodeTreeView()
|
||||
if err != nil || len(views) != 2 {
|
||||
t.Fatalf("get node views: len=%d err=%v", len(views), err)
|
||||
}
|
||||
sampled, unprobed := views[0], views[1]
|
||||
minAge := now.UnixMilli() - sampled.LastHeartbeat*1000
|
||||
maxAge := time.Now().UnixMilli() - sampled.LastHeartbeat*1000
|
||||
if age := sampled.HeartbeatAgeMillis; age == nil || *age < minAge || *age > maxAge {
|
||||
t.Fatalf("sampled heartbeat age = %v, want a value in [%d, %d]", age, minAge, maxAge)
|
||||
}
|
||||
if unprobed.HeartbeatAgeMillis != nil {
|
||||
t.Fatal("unprobed node has a heartbeat age")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1255,6 +1255,7 @@
|
||||
"cpu": "CPU",
|
||||
"mem": "الذاكرة",
|
||||
"netUp": "صعود الشبكة (KB/s)",
|
||||
"networkSpeed": "سرعة الشبكة",
|
||||
"netDown": "نزول الشبكة (KB/s)",
|
||||
"uptime": "مدة التشغيل",
|
||||
"latency": "الكمون",
|
||||
|
||||
@@ -1376,6 +1376,7 @@
|
||||
"cpu": "CPU",
|
||||
"mem": "Memory",
|
||||
"netUp": "Net Up (KB/s)",
|
||||
"networkSpeed": "Network speed",
|
||||
"netDown": "Net Down (KB/s)",
|
||||
"uptime": "Uptime",
|
||||
"latency": "Latency",
|
||||
|
||||
@@ -1255,6 +1255,7 @@
|
||||
"cpu": "CPU",
|
||||
"mem": "Memoria",
|
||||
"netUp": "Subida de red (KB/s)",
|
||||
"networkSpeed": "Velocidad de red",
|
||||
"netDown": "Bajada de red (KB/s)",
|
||||
"uptime": "Tiempo activo",
|
||||
"latency": "Latencia",
|
||||
|
||||
@@ -1255,6 +1255,7 @@
|
||||
"cpu": "CPU",
|
||||
"mem": "حافظه",
|
||||
"netUp": "آپلود شبکه (KB/s)",
|
||||
"networkSpeed": "سرعت شبکه",
|
||||
"netDown": "دانلود شبکه (KB/s)",
|
||||
"uptime": "مدت فعالیت",
|
||||
"latency": "تاخیر",
|
||||
|
||||
@@ -1255,6 +1255,7 @@
|
||||
"cpu": "CPU",
|
||||
"mem": "Memori",
|
||||
"netUp": "Upload Jaringan (KB/s)",
|
||||
"networkSpeed": "Kecepatan jaringan",
|
||||
"netDown": "Download Jaringan (KB/s)",
|
||||
"uptime": "Uptime",
|
||||
"latency": "Latensi",
|
||||
|
||||
@@ -1255,6 +1255,7 @@
|
||||
"cpu": "CPU",
|
||||
"mem": "メモリ",
|
||||
"netUp": "送信 (KB/s)",
|
||||
"networkSpeed": "ネットワーク速度",
|
||||
"netDown": "受信 (KB/s)",
|
||||
"uptime": "稼働時間",
|
||||
"latency": "レイテンシ",
|
||||
|
||||
@@ -1255,6 +1255,7 @@
|
||||
"cpu": "CPU",
|
||||
"mem": "Memória",
|
||||
"netUp": "Subida de rede (KB/s)",
|
||||
"networkSpeed": "Velocidade de rede",
|
||||
"netDown": "Descida de rede (KB/s)",
|
||||
"uptime": "Tempo ativo",
|
||||
"latency": "Latência",
|
||||
|
||||
@@ -1255,6 +1255,7 @@
|
||||
"cpu": "CPU",
|
||||
"mem": "Память",
|
||||
"netUp": "Отдача (KB/s)",
|
||||
"networkSpeed": "Скорость сети",
|
||||
"netDown": "Приём (KB/s)",
|
||||
"uptime": "Аптайм",
|
||||
"latency": "Задержка",
|
||||
|
||||
@@ -1376,6 +1376,7 @@
|
||||
"cpu": "CPU",
|
||||
"mem": "Pamäť",
|
||||
"netUp": "Odosielanie (KB/s)",
|
||||
"networkSpeed": "Rýchlosť siete",
|
||||
"netDown": "Sťahovanie (KB/s)",
|
||||
"uptime": "Čas prevádzky",
|
||||
"latency": "Odozva",
|
||||
|
||||
@@ -1255,6 +1255,7 @@
|
||||
"cpu": "CPU",
|
||||
"mem": "Bellek",
|
||||
"netUp": "Ağ Yükleme (KB/s)",
|
||||
"networkSpeed": "Ağ hızı",
|
||||
"netDown": "Ağ İndirme (KB/s)",
|
||||
"uptime": "Çalışma Süresi",
|
||||
"latency": "Gecikme",
|
||||
|
||||
@@ -1255,6 +1255,7 @@
|
||||
"cpu": "CPU",
|
||||
"mem": "Пам'ять",
|
||||
"netUp": "Вихідний (KB/s)",
|
||||
"networkSpeed": "Швидкість мережі",
|
||||
"netDown": "Вхідний (KB/s)",
|
||||
"uptime": "Час роботи",
|
||||
"latency": "Затримка",
|
||||
|
||||
@@ -1255,6 +1255,7 @@
|
||||
"cpu": "CPU",
|
||||
"mem": "Bộ nhớ",
|
||||
"netUp": "Mạng lên (KB/s)",
|
||||
"networkSpeed": "Tốc độ mạng",
|
||||
"netDown": "Mạng xuống (KB/s)",
|
||||
"uptime": "Thời gian hoạt động",
|
||||
"latency": "Độ trễ",
|
||||
|
||||
@@ -1255,6 +1255,7 @@
|
||||
"cpu": "CPU",
|
||||
"mem": "内存",
|
||||
"netUp": "网络上行 (KB/s)",
|
||||
"networkSpeed": "网络速率",
|
||||
"netDown": "网络下行 (KB/s)",
|
||||
"uptime": "运行时长",
|
||||
"latency": "延迟",
|
||||
|
||||
@@ -1255,6 +1255,7 @@
|
||||
"cpu": "CPU",
|
||||
"mem": "記憶體",
|
||||
"netUp": "網路上行 (KB/s)",
|
||||
"networkSpeed": "網路速率",
|
||||
"netDown": "網路下行 (KB/s)",
|
||||
"uptime": "運行時間",
|
||||
"latency": "延遲",
|
||||
|
||||
Reference in New Issue
Block a user