From 45236cd492c67b74249b6afad18d89fc78ba9ca5 Mon Sep 17 00:00:00 2001 From: Hamed Sanaei Date: Tue, 1 Dec 2026 14:05:35 +0330 Subject: [PATCH] feat(nodes): add fleet monitoring and host telemetry Carry sampled host metrics through existing heartbeats and count client identities in SQL. Show the current panel and fleet in a responsive monitoring table based on the approved design. --- docs/content/docs/en/reference/api/nodes.mdx | 9 +- docs/public/openapi.json | 288 ++++ frontend/public/openapi.json | 288 ++++ frontend/src/api/queries/useNodesQuery.ts | 24 +- frontend/src/api/queryKeys.ts | 1 + frontend/src/api/websocketBridge.ts | 8 + frontend/src/generated/examples.ts | 73 + frontend/src/generated/schemas.ts | 220 +++ frontend/src/generated/types.ts | 47 + frontend/src/generated/zod.ts | 51 + frontend/src/pages/api-docs/endpoints.ts | 7 + frontend/src/pages/nodes/NodeList.css | 305 ++-- frontend/src/pages/nodes/NodeList.stories.tsx | 175 +++ frontend/src/pages/nodes/NodeList.tsx | 1349 +++++++++-------- frontend/src/pages/nodes/NodeNetworkSpeed.tsx | 28 +- frontend/src/pages/nodes/NodesPage.tsx | 107 +- frontend/src/pages/nodes/fleetTelemetry.ts | 103 ++ frontend/src/pages/nodes/fonts/LICENSE.txt | 93 ++ .../nodes/fonts/SourceSansPro-Regular.woff2 | Bin 0 -> 62636 bytes frontend/src/schemas/node.ts | 7 + .../src/test/node-fleet-monitoring.test.tsx | 114 ++ .../src/test/node-list-online-total.test.tsx | 8 +- .../test/node-metrics-availability.test.tsx | 20 +- frontend/src/test/node-restart.test.tsx | 12 +- internal/database/model/model.go | 16 +- internal/database/model/node_telemetry.go | 22 + internal/web/controller/api.go | 5 + internal/web/controller/node.go | 11 + internal/web/controller/server.go | 4 +- internal/web/job/node_heartbeat_job.go | 17 +- internal/web/service/node.go | 196 +-- internal/web/service/node_contract.go | 91 +- internal/web/service/node_fleet.go | 152 ++ internal/web/service/node_fleet_test.go | 240 +++ internal/web/service/node_shared_guid_test.go | 4 +- internal/web/service/node_telemetry.go | 123 ++ internal/web/service/node_tree.go | 131 +- internal/web/service/server.go | 13 +- internal/web/service/server_scope_test.go | 4 +- internal/web/translation/ar-EG.json | 28 +- internal/web/translation/en-US.json | 28 +- internal/web/translation/es-ES.json | 28 +- internal/web/translation/fa-IR.json | 28 +- internal/web/translation/id-ID.json | 28 +- internal/web/translation/ja-JP.json | 28 +- internal/web/translation/pt-BR.json | 28 +- internal/web/translation/ru-RU.json | 28 +- internal/web/translation/sk-SK.json | 28 +- internal/web/translation/tr-TR.json | 28 +- internal/web/translation/uk-UA.json | 28 +- internal/web/translation/vi-VN.json | 28 +- internal/web/translation/zh-CN.json | 28 +- internal/web/translation/zh-TW.json | 28 +- internal/web/web.go | 4 +- internal/web/websocket/hub.go | 23 +- internal/web/websocket/notifier.go | 6 + tools/openapigen/main.go | 4 + 57 files changed, 3477 insertions(+), 1318 deletions(-) create mode 100644 frontend/src/pages/nodes/NodeList.stories.tsx create mode 100644 frontend/src/pages/nodes/fleetTelemetry.ts create mode 100644 frontend/src/pages/nodes/fonts/LICENSE.txt create mode 100644 frontend/src/pages/nodes/fonts/SourceSansPro-Regular.woff2 create mode 100644 frontend/src/test/node-fleet-monitoring.test.tsx create mode 100644 internal/database/model/node_telemetry.go create mode 100644 internal/web/service/node_fleet.go create mode 100644 internal/web/service/node_fleet_test.go create mode 100644 internal/web/service/node_telemetry.go diff --git a/docs/content/docs/en/reference/api/nodes.mdx b/docs/content/docs/en/reference/api/nodes.mdx index fb6e627e3..afc8cc506 100644 --- a/docs/content/docs/en/reference/api/nodes.mdx +++ b/docs/content/docs/en/reference/api/nodes.mdx @@ -11,6 +11,10 @@ _openapi: title: List every configured node with its connection details, health, and last heartbeat patch. url: '#list-every-configured-node-with-its-connection-details-health-and-last-heartbeat-patch' + - depth: 2 + title: Read the local panel, unique fleet client counts and sampled remote host + telemetry. + url: '#read-the-local-panel-unique-fleet-client-counts-and-sampled-remote-host-telemetry' - depth: 2 title: This panel's node-auth CA certificate (public, PEM) to paste into a node's mTLS trust setting. Lazily mints the CA and the master client @@ -99,6 +103,9 @@ _openapi: - content: List every configured node with its connection details, health, and last heartbeat patch. id: list-every-configured-node-with-its-connection-details-health-and-last-heartbeat-patch + - content: Read the local panel, unique fleet client counts and sampled remote + host telemetry. + id: read-the-local-panel-unique-fleet-client-counts-and-sampled-remote-host-telemetry - content: This panel's node-auth CA certificate (public, PEM) to paste into a node's mTLS trust setting. Lazily mints the CA and the master client cert on first call. Pair with setting tlsVerifyMode=mtls on the node. @@ -175,7 +182,7 @@ export default function Layout(props) { return ( <> {props.children} - + ); } \ No newline at end of file diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 4877ccf2d..a373b8720 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -4503,6 +4503,14 @@ "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "enum": [ "verify", @@ -4664,6 +4672,43 @@ ], "type": "object" }, + "NodeFleetCounts": { + "properties": { + "activeCount": { + "example": 90, + "type": "integer" + }, + "clientCount": { + "example": 100, + "type": "integer" + }, + "depletedCount": { + "example": 2, + "type": "integer" + }, + "disabledCount": { + "example": 8, + "type": "integer" + }, + "inboundCount": { + "example": 8, + "type": "integer" + }, + "onlineCount": { + "example": 20, + "type": "integer" + } + }, + "required": [ + "activeCount", + "clientCount", + "depletedCount", + "disabledCount", + "inboundCount", + "onlineCount" + ], + "type": "object" + }, "NodeInboundTraffic": { "properties": { "down": { @@ -4686,6 +4731,40 @@ ], "type": "object" }, + "NodeMasterView": { + "properties": { + "counts": { + "$ref": "#/components/schemas/NodeFleetCounts" + }, + "panelVersion": { + "example": "v3.12.0", + "type": "string" + }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, + "xrayError": { + "type": "string" + }, + "xrayState": { + "example": "running", + "type": "string" + }, + "xrayVersion": { + "example": "26.1.1", + "type": "string" + } + }, + "required": [ + "counts" + ], + "type": "object" + }, "NodeMutationRequest": { "description": "NodeMutationRequest is the node write/probe contract. ApiToken is accepted\nonly as input. On update, nil means keep the stored token; replacement and\nclearing are explicit and mutually exclusive.", "properties": { @@ -4776,6 +4855,33 @@ ], "type": "object" }, + "NodeOverview": { + "properties": { + "fleet": { + "$ref": "#/components/schemas/NodeFleetCounts" + }, + "master": { + "$ref": "#/components/schemas/NodeMasterView" + }, + "nodes": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeView" + } + ], + "nullable": true + }, + "type": "array" + } + }, + "required": [ + "fleet", + "master", + "nodes" + ], + "type": "object" + }, "NodeSnapshotAttachment": { "properties": { "email": { @@ -4819,6 +4925,106 @@ ], "type": "object" }, + "NodeTelemetry": { + "description": "NodeTelemetry describes one host sample. Nil metrics were not measured.", + "properties": { + "cpuPct": { + "example": 12.5, + "nullable": true, + "type": "number" + }, + "load1": { + "example": 0.25, + "nullable": true, + "type": "number" + }, + "load15": { + "example": 0.12, + "nullable": true, + "type": "number" + }, + "load5": { + "example": 0.18, + "nullable": true, + "type": "number" + }, + "logicalCores": { + "example": 8, + "nullable": true, + "type": "integer" + }, + "memAvailableBytes": { + "example": 1073741824, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "memTotalBytes": { + "example": 4294967296, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "memUsedBytes": { + "example": 2147483648, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "netDown": { + "example": 2048, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "netUp": { + "example": 1024, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "physicalCores": { + "example": 4, + "nullable": true, + "type": "integer" + }, + "resourceScope": { + "example": "container", + "type": "string" + }, + "sampleAgeMillis": { + "example": 125, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "sampledAt": { + "example": 1700000000000, + "format": "int64", + "type": "integer" + }, + "tcpCount": { + "example": 75, + "nullable": true, + "type": "integer" + }, + "udpCount": { + "example": 12, + "nullable": true, + "type": "integer" + }, + "uptimeSecs": { + "example": 3600, + "format": "int64", + "nullable": true, + "type": "integer" + } + }, + "required": [ + "sampledAt" + ], + "type": "object" + }, "NodeTrafficSnapshotV1": { "description": "NodeTrafficSnapshotV1 carries complete counters every tick; only unchanged structure is omitted.", "properties": { @@ -5050,6 +5256,14 @@ "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "example": "verify", "type": "string" @@ -5916,6 +6130,12 @@ "resourceScope": { "type": "string" }, + "sampleAgeMillis": { + "example": 125, + "format": "int64", + "nullable": true, + "type": "integer" + }, "swap": {}, "tcpCount": { "type": "integer" @@ -7932,6 +8152,7 @@ "panelVersion": "", "publicIP": null, "resourceScope": "", + "sampleAgeMillis": 125, "swap": null, "tcpCount": 0, "udpCount": 0, @@ -13917,6 +14138,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -13936,6 +14158,69 @@ } } }, + "/panel/api/nodes/overview": { + "get": { + "tags": [ + "Nodes" + ], + "summary": "Read the local panel, unique fleet client counts and sampled remote host telemetry.", + "operationId": "get_panel_api_nodes_overview", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/NodeOverview" + } + } + }, + "example": { + "success": true, + "obj": { + "fleet": { + "activeCount": 90, + "clientCount": 100, + "depletedCount": 2, + "disabledCount": 8, + "inboundCount": 8, + "onlineCount": 20 + }, + "master": { + "counts": { + "activeCount": 90, + "clientCount": 100, + "depletedCount": 2, + "disabledCount": 8, + "inboundCount": 8, + "onlineCount": 20 + }, + "panelVersion": "v3.12.0", + "telemetry": null, + "xrayError": "", + "xrayState": "running", + "xrayVersion": "26.1.1" + }, + "nodes": [ + null + ] + } + } + } + } + } + } + } + }, "/panel/api/nodes/mtls/ca": { "post": { "tags": [ @@ -14123,6 +14408,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -14278,6 +14564,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -20079,6 +20366,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 4877ccf2d..a373b8720 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -4503,6 +4503,14 @@ "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "enum": [ "verify", @@ -4664,6 +4672,43 @@ ], "type": "object" }, + "NodeFleetCounts": { + "properties": { + "activeCount": { + "example": 90, + "type": "integer" + }, + "clientCount": { + "example": 100, + "type": "integer" + }, + "depletedCount": { + "example": 2, + "type": "integer" + }, + "disabledCount": { + "example": 8, + "type": "integer" + }, + "inboundCount": { + "example": 8, + "type": "integer" + }, + "onlineCount": { + "example": 20, + "type": "integer" + } + }, + "required": [ + "activeCount", + "clientCount", + "depletedCount", + "disabledCount", + "inboundCount", + "onlineCount" + ], + "type": "object" + }, "NodeInboundTraffic": { "properties": { "down": { @@ -4686,6 +4731,40 @@ ], "type": "object" }, + "NodeMasterView": { + "properties": { + "counts": { + "$ref": "#/components/schemas/NodeFleetCounts" + }, + "panelVersion": { + "example": "v3.12.0", + "type": "string" + }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, + "xrayError": { + "type": "string" + }, + "xrayState": { + "example": "running", + "type": "string" + }, + "xrayVersion": { + "example": "26.1.1", + "type": "string" + } + }, + "required": [ + "counts" + ], + "type": "object" + }, "NodeMutationRequest": { "description": "NodeMutationRequest is the node write/probe contract. ApiToken is accepted\nonly as input. On update, nil means keep the stored token; replacement and\nclearing are explicit and mutually exclusive.", "properties": { @@ -4776,6 +4855,33 @@ ], "type": "object" }, + "NodeOverview": { + "properties": { + "fleet": { + "$ref": "#/components/schemas/NodeFleetCounts" + }, + "master": { + "$ref": "#/components/schemas/NodeMasterView" + }, + "nodes": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeView" + } + ], + "nullable": true + }, + "type": "array" + } + }, + "required": [ + "fleet", + "master", + "nodes" + ], + "type": "object" + }, "NodeSnapshotAttachment": { "properties": { "email": { @@ -4819,6 +4925,106 @@ ], "type": "object" }, + "NodeTelemetry": { + "description": "NodeTelemetry describes one host sample. Nil metrics were not measured.", + "properties": { + "cpuPct": { + "example": 12.5, + "nullable": true, + "type": "number" + }, + "load1": { + "example": 0.25, + "nullable": true, + "type": "number" + }, + "load15": { + "example": 0.12, + "nullable": true, + "type": "number" + }, + "load5": { + "example": 0.18, + "nullable": true, + "type": "number" + }, + "logicalCores": { + "example": 8, + "nullable": true, + "type": "integer" + }, + "memAvailableBytes": { + "example": 1073741824, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "memTotalBytes": { + "example": 4294967296, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "memUsedBytes": { + "example": 2147483648, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "netDown": { + "example": 2048, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "netUp": { + "example": 1024, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "physicalCores": { + "example": 4, + "nullable": true, + "type": "integer" + }, + "resourceScope": { + "example": "container", + "type": "string" + }, + "sampleAgeMillis": { + "example": 125, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "sampledAt": { + "example": 1700000000000, + "format": "int64", + "type": "integer" + }, + "tcpCount": { + "example": 75, + "nullable": true, + "type": "integer" + }, + "udpCount": { + "example": 12, + "nullable": true, + "type": "integer" + }, + "uptimeSecs": { + "example": 3600, + "format": "int64", + "nullable": true, + "type": "integer" + } + }, + "required": [ + "sampledAt" + ], + "type": "object" + }, "NodeTrafficSnapshotV1": { "description": "NodeTrafficSnapshotV1 carries complete counters every tick; only unchanged structure is omitted.", "properties": { @@ -5050,6 +5256,14 @@ "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "example": "verify", "type": "string" @@ -5916,6 +6130,12 @@ "resourceScope": { "type": "string" }, + "sampleAgeMillis": { + "example": 125, + "format": "int64", + "nullable": true, + "type": "integer" + }, "swap": {}, "tcpCount": { "type": "integer" @@ -7932,6 +8152,7 @@ "panelVersion": "", "publicIP": null, "resourceScope": "", + "sampleAgeMillis": 125, "swap": null, "tcpCount": 0, "udpCount": 0, @@ -13917,6 +14138,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -13936,6 +14158,69 @@ } } }, + "/panel/api/nodes/overview": { + "get": { + "tags": [ + "Nodes" + ], + "summary": "Read the local panel, unique fleet client counts and sampled remote host telemetry.", + "operationId": "get_panel_api_nodes_overview", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/NodeOverview" + } + } + }, + "example": { + "success": true, + "obj": { + "fleet": { + "activeCount": 90, + "clientCount": 100, + "depletedCount": 2, + "disabledCount": 8, + "inboundCount": 8, + "onlineCount": 20 + }, + "master": { + "counts": { + "activeCount": 90, + "clientCount": 100, + "depletedCount": 2, + "disabledCount": 8, + "inboundCount": 8, + "onlineCount": 20 + }, + "panelVersion": "v3.12.0", + "telemetry": null, + "xrayError": "", + "xrayState": "running", + "xrayVersion": "26.1.1" + }, + "nodes": [ + null + ] + } + } + } + } + } + } + } + }, "/panel/api/nodes/mtls/ca": { "post": { "tags": [ @@ -14123,6 +14408,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -14278,6 +14564,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -20079,6 +20366,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ diff --git a/frontend/src/api/queries/useNodesQuery.ts b/frontend/src/api/queries/useNodesQuery.ts index 23d5db507..706c92b55 100644 --- a/frontend/src/api/queries/useNodesQuery.ts +++ b/frontend/src/api/queries/useNodesQuery.ts @@ -3,12 +3,34 @@ import { useMemo } from 'react'; import { HttpUtil } from '@/utils'; import { parseMsg } from '@/utils/zodValidate'; -import { NodeListSchema } from '@/schemas/node'; +import { NodeListSchema, NodeOverviewSchema } from '@/schemas/node'; import type { NodeRecord } from '@/schemas/node'; import { keys } from '@/api/queryKeys'; export type { NodeRecord }; +async function fetchNodeOverview() { + const msg = await HttpUtil.get('/panel/api/nodes/overview', undefined, { silent: true }); + if (!msg.success || msg.obj == null) throw new Error(msg.msg || 'Failed to fetch node overview'); + return NodeOverviewSchema.parse(msg.obj); +} + +const emptyNodes: NodeRecord[] = []; + +export function useNodeOverviewQuery() { + const query = useQuery({ queryKey: keys.nodes.overview(), queryFn: fetchNodeOverview }); + return { + nodes: query.data?.nodes ?? emptyNodes, + master: query.data?.master, + fleet: query.data?.fleet, + nodesUpdatedAt: query.dataUpdatedAt, + loading: query.isFetching, + fetched: query.data !== undefined || query.isError, + fetchError: query.error?.message ?? '', + refetch: query.refetch, + }; +} + export interface NodeTotals { total: number; online: number; diff --git a/frontend/src/api/queryKeys.ts b/frontend/src/api/queryKeys.ts index c03d796ad..e8448b04b 100644 --- a/frontend/src/api/queryKeys.ts +++ b/frontend/src/api/queryKeys.ts @@ -8,6 +8,7 @@ export const keys = { nodes: { root: () => ['nodes'] as const, list: () => ['nodes', 'list'] as const, + overview: () => ['nodes', 'overview'] as const, }, hosts: { root: () => ['hosts'] as const, diff --git a/frontend/src/api/websocketBridge.ts b/frontend/src/api/websocketBridge.ts index 9394398c8..0a69d1b63 100644 --- a/frontend/src/api/websocketBridge.ts +++ b/frontend/src/api/websocketBridge.ts @@ -4,6 +4,7 @@ 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; @@ -40,6 +41,11 @@ 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); @@ -48,6 +54,7 @@ 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(); @@ -55,6 +62,7 @@ export function useWebSocketBridge() { client.off('invalidate', onInvalidate); client.off('outbounds', onOutbounds); client.off('nodes', onNodes); + client.off('nodesOverview', onNodesOverview); client.off('inbounds', onInbounds); if (invalidateTimer != null) { clearTimeout(invalidateTimer); diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index 081067ac9..bc8a64466 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -1173,6 +1173,7 @@ export const EXAMPLES: Record = { "remark": "", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -1200,11 +1201,34 @@ export const EXAMPLES: Record = { "total": 10737418240, "up": 1048576 }, + "NodeFleetCounts": { + "activeCount": 90, + "clientCount": 100, + "depletedCount": 2, + "disabledCount": 8, + "inboundCount": 8, + "onlineCount": 20 + }, "NodeInboundTraffic": { "down": 0, "id": 1, "up": 0 }, + "NodeMasterView": { + "counts": { + "activeCount": 90, + "clientCount": 100, + "depletedCount": 2, + "disabledCount": 8, + "inboundCount": 8, + "onlineCount": 20 + }, + "panelVersion": "v3.12.0", + "telemetry": null, + "xrayError": "", + "xrayState": "running", + "xrayVersion": "26.1.1" + }, "NodeMutationRequest": { "address": "", "allowPrivateAddress": false, @@ -1225,6 +1249,34 @@ export const EXAMPLES: Record = { "scheme": "http", "tlsVerifyMode": "verify" }, + "NodeOverview": { + "fleet": { + "activeCount": 90, + "clientCount": 100, + "depletedCount": 2, + "disabledCount": 8, + "inboundCount": 8, + "onlineCount": 20 + }, + "master": { + "counts": { + "activeCount": 90, + "clientCount": 100, + "depletedCount": 2, + "disabledCount": 8, + "inboundCount": 8, + "onlineCount": 20 + }, + "panelVersion": "v3.12.0", + "telemetry": null, + "xrayError": "", + "xrayState": "running", + "xrayVersion": "26.1.1" + }, + "nodes": [ + null + ] + }, "NodeSnapshotAttachment": { "email": "user1", "inboundId": 1 @@ -1240,6 +1292,25 @@ export const EXAMPLES: Record = { null ] }, + "NodeTelemetry": { + "cpuPct": 12.5, + "load1": 0.25, + "load15": 0.12, + "load5": 0.18, + "logicalCores": 8, + "memAvailableBytes": 1073741824, + "memTotalBytes": 4294967296, + "memUsedBytes": 2147483648, + "netDown": 2048, + "netUp": 1024, + "physicalCores": 4, + "resourceScope": "container", + "sampleAgeMillis": 125, + "sampledAt": 1700000000000, + "tcpCount": 75, + "udpCount": 12, + "uptimeSecs": 3600 + }, "NodeTrafficSnapshotV1": { "activeInboundTree": {}, "clients": [ @@ -1315,6 +1386,7 @@ export const EXAMPLES: Record = { "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -1542,6 +1614,7 @@ export const EXAMPLES: Record = { "panelVersion": "", "publicIP": null, "resourceScope": "", + "sampleAgeMillis": 125, "swap": null, "tcpCount": 0, "udpCount": 0, diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index e5b7085f6..cebcae398 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -4477,6 +4477,14 @@ export const SCHEMAS: Record = { "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "enum": [ "verify", @@ -4638,6 +4646,43 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "NodeFleetCounts": { + "properties": { + "activeCount": { + "example": 90, + "type": "integer" + }, + "clientCount": { + "example": 100, + "type": "integer" + }, + "depletedCount": { + "example": 2, + "type": "integer" + }, + "disabledCount": { + "example": 8, + "type": "integer" + }, + "inboundCount": { + "example": 8, + "type": "integer" + }, + "onlineCount": { + "example": 20, + "type": "integer" + } + }, + "required": [ + "activeCount", + "clientCount", + "depletedCount", + "disabledCount", + "inboundCount", + "onlineCount" + ], + "type": "object" + }, "NodeInboundTraffic": { "properties": { "down": { @@ -4660,6 +4705,40 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "NodeMasterView": { + "properties": { + "counts": { + "$ref": "#/components/schemas/NodeFleetCounts" + }, + "panelVersion": { + "example": "v3.12.0", + "type": "string" + }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, + "xrayError": { + "type": "string" + }, + "xrayState": { + "example": "running", + "type": "string" + }, + "xrayVersion": { + "example": "26.1.1", + "type": "string" + } + }, + "required": [ + "counts" + ], + "type": "object" + }, "NodeMutationRequest": { "description": "NodeMutationRequest is the node write/probe contract. ApiToken is accepted\nonly as input. On update, nil means keep the stored token; replacement and\nclearing are explicit and mutually exclusive.", "properties": { @@ -4750,6 +4829,33 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "NodeOverview": { + "properties": { + "fleet": { + "$ref": "#/components/schemas/NodeFleetCounts" + }, + "master": { + "$ref": "#/components/schemas/NodeMasterView" + }, + "nodes": { + "items": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeView" + } + ], + "nullable": true + }, + "type": "array" + } + }, + "required": [ + "fleet", + "master", + "nodes" + ], + "type": "object" + }, "NodeSnapshotAttachment": { "properties": { "email": { @@ -4793,6 +4899,106 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "NodeTelemetry": { + "description": "NodeTelemetry describes one host sample. Nil metrics were not measured.", + "properties": { + "cpuPct": { + "example": 12.5, + "nullable": true, + "type": "number" + }, + "load1": { + "example": 0.25, + "nullable": true, + "type": "number" + }, + "load15": { + "example": 0.12, + "nullable": true, + "type": "number" + }, + "load5": { + "example": 0.18, + "nullable": true, + "type": "number" + }, + "logicalCores": { + "example": 8, + "nullable": true, + "type": "integer" + }, + "memAvailableBytes": { + "example": 1073741824, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "memTotalBytes": { + "example": 4294967296, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "memUsedBytes": { + "example": 2147483648, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "netDown": { + "example": 2048, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "netUp": { + "example": 1024, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "physicalCores": { + "example": 4, + "nullable": true, + "type": "integer" + }, + "resourceScope": { + "example": "container", + "type": "string" + }, + "sampleAgeMillis": { + "example": 125, + "format": "int64", + "nullable": true, + "type": "integer" + }, + "sampledAt": { + "example": 1700000000000, + "format": "int64", + "type": "integer" + }, + "tcpCount": { + "example": 75, + "nullable": true, + "type": "integer" + }, + "udpCount": { + "example": 12, + "nullable": true, + "type": "integer" + }, + "uptimeSecs": { + "example": 3600, + "format": "int64", + "nullable": true, + "type": "integer" + } + }, + "required": [ + "sampledAt" + ], + "type": "object" + }, "NodeTrafficSnapshotV1": { "description": "NodeTrafficSnapshotV1 carries complete counters every tick; only unchanged structure is omitted.", "properties": { @@ -5024,6 +5230,14 @@ export const SCHEMAS: Record = { "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "example": "verify", "type": "string" @@ -5890,6 +6104,12 @@ export const SCHEMAS: Record = { "resourceScope": { "type": "string" }, + "sampleAgeMillis": { + "example": 125, + "format": "int64", + "nullable": true, + "type": "integer" + }, "swap": {}, "tcpCount": { "type": "integer" diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 5bf30b7ce..601f29fc0 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -1027,6 +1027,7 @@ export interface Node { remark: string; scheme: string; status: string; + telemetry?: NodeTelemetry | null; tlsVerifyMode: string; transitive?: boolean; unavailableMetrics?: string[]; @@ -1054,12 +1055,30 @@ export interface NodeClientTraffic { up: number; } +export interface NodeFleetCounts { + activeCount: number; + clientCount: number; + depletedCount: number; + disabledCount: number; + inboundCount: number; + onlineCount: number; +} + export interface NodeInboundTraffic { down: number; id: number; up: number; } +export interface NodeMasterView { + counts: NodeFleetCounts; + panelVersion?: string; + telemetry?: NodeTelemetry | null; + xrayError?: string; + xrayState?: string; + xrayVersion?: string; +} + export interface NodeMutationRequest { address: string; allowPrivateAddress: boolean; @@ -1079,6 +1098,12 @@ export interface NodeMutationRequest { tlsVerifyMode: string; } +export interface NodeOverview { + fleet: NodeFleetCounts; + master: NodeMasterView; + nodes: NodeView | null[]; +} + export interface NodeSnapshotAttachment { email: string; inboundId: number; @@ -1089,6 +1114,26 @@ export interface NodeSnapshotStructure { inbounds: Inbound | null[]; } +export interface NodeTelemetry { + cpuPct?: number | null; + load1?: number | null; + load15?: number | null; + load5?: number | null; + logicalCores?: number | null; + memAvailableBytes?: number | null; + memTotalBytes?: number | null; + memUsedBytes?: number | null; + netDown?: number | null; + netUp?: number | null; + physicalCores?: number | null; + resourceScope?: string; + sampleAgeMillis?: number | null; + sampledAt: number; + tcpCount?: number | null; + udpCount?: number | null; + uptimeSecs?: number | null; +} + export interface NodeTrafficSnapshotV1 { activeInboundTree: Record; clients: NodeClientTraffic[]; @@ -1138,6 +1183,7 @@ export interface NodeView { remark: string; scheme: string; status: string; + telemetry?: NodeTelemetry | null; tlsVerifyMode: string; transitive?: boolean; unavailableMetrics?: string[]; @@ -1337,6 +1383,7 @@ export interface Status { panelVersion: string; publicIP: unknown; resourceScope?: string; + sampleAgeMillis?: number | null; swap: unknown; tcpCount: number; udpCount: number; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index 91489537e..2810086e1 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -1092,6 +1092,7 @@ export const NodeSchema = z.object({ remark: z.string(), scheme: z.enum(['http', 'https']), status: z.string(), + telemetry: z.lazy(() => NodeTelemetrySchema).nullable().optional(), tlsVerifyMode: z.enum(['verify', 'skip', 'pin', 'mtls']), transitive: z.boolean().optional(), unavailableMetrics: z.array(z.string()).optional(), @@ -1121,6 +1122,16 @@ export const NodeClientTrafficSchema = z.object({ }); export type NodeClientTraffic = z.infer; +export const NodeFleetCountsSchema = z.object({ + activeCount: z.number().int(), + clientCount: z.number().int(), + depletedCount: z.number().int(), + disabledCount: z.number().int(), + inboundCount: z.number().int(), + onlineCount: z.number().int(), +}); +export type NodeFleetCounts = z.infer; + export const NodeInboundTrafficSchema = z.object({ down: z.number().int(), id: z.number().int(), @@ -1128,6 +1139,16 @@ export const NodeInboundTrafficSchema = z.object({ }); export type NodeInboundTraffic = z.infer; +export const NodeMasterViewSchema = z.object({ + counts: z.lazy(() => NodeFleetCountsSchema), + panelVersion: z.string().optional(), + telemetry: z.lazy(() => NodeTelemetrySchema).nullable().optional(), + xrayError: z.string().optional(), + xrayState: z.string().optional(), + xrayVersion: z.string().optional(), +}); +export type NodeMasterView = z.infer; + export const NodeMutationRequestSchema = z.object({ address: z.string(), allowPrivateAddress: z.boolean(), @@ -1148,6 +1169,13 @@ export const NodeMutationRequestSchema = z.object({ }); export type NodeMutationRequest = z.infer; +export const NodeOverviewSchema = z.object({ + fleet: z.lazy(() => NodeFleetCountsSchema), + master: z.lazy(() => NodeMasterViewSchema), + nodes: z.array(z.lazy(() => NodeViewSchema).nullable()), +}); +export type NodeOverview = z.infer; + export const NodeSnapshotAttachmentSchema = z.object({ email: z.string(), inboundId: z.number().int(), @@ -1160,6 +1188,27 @@ export const NodeSnapshotStructureSchema = z.object({ }); export type NodeSnapshotStructure = z.infer; +export const NodeTelemetrySchema = z.object({ + cpuPct: z.number().nullable().optional(), + load1: z.number().nullable().optional(), + load15: z.number().nullable().optional(), + load5: z.number().nullable().optional(), + logicalCores: z.number().int().nullable().optional(), + memAvailableBytes: z.number().int().nullable().optional(), + memTotalBytes: z.number().int().nullable().optional(), + memUsedBytes: z.number().int().nullable().optional(), + netDown: z.number().int().nullable().optional(), + netUp: z.number().int().nullable().optional(), + physicalCores: z.number().int().nullable().optional(), + resourceScope: z.string().optional(), + sampleAgeMillis: z.number().int().nullable().optional(), + sampledAt: z.number().int(), + tcpCount: z.number().int().nullable().optional(), + udpCount: z.number().int().nullable().optional(), + uptimeSecs: z.number().int().nullable().optional(), +}); +export type NodeTelemetry = z.infer; + export const NodeTrafficSnapshotV1Schema = z.object({ activeInboundTree: z.record(z.string(), z.array(z.string())), clients: z.array(z.lazy(() => NodeClientTrafficSchema)), @@ -1210,6 +1259,7 @@ export const NodeViewSchema = z.object({ remark: z.string(), scheme: z.string(), status: z.string(), + telemetry: z.lazy(() => NodeTelemetrySchema).nullable().optional(), tlsVerifyMode: z.string(), transitive: z.boolean().optional(), unavailableMetrics: z.array(z.string()).optional(), @@ -1424,6 +1474,7 @@ export const StatusSchema = z.object({ panelVersion: z.string(), publicIP: z.unknown(), resourceScope: z.string().optional(), + sampleAgeMillis: z.number().int().nullable().optional(), swap: z.unknown(), tcpCount: z.number().int(), udpCount: z.number().int(), diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index 8eb435b29..b7120fc56 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -2052,6 +2052,13 @@ export const sections: readonly Section[] = [ responseSchema: 'NodeView', responseSchemaArray: true, }, + { + method: 'GET', + path: '/panel/api/nodes/overview', + summary: + 'Read the local panel, unique fleet client counts and sampled remote host telemetry.', + responseSchema: 'NodeOverview', + }, { method: 'POST', path: '/panel/api/nodes/mtls/ca', diff --git a/frontend/src/pages/nodes/NodeList.css b/frontend/src/pages/nodes/NodeList.css index 920ac4978..90c8a5e42 100644 --- a/frontend/src/pages/nodes/NodeList.css +++ b/frontend/src/pages/nodes/NodeList.css @@ -1,160 +1,201 @@ -.toolbar { - margin-bottom: 12px; - display: flex; - justify-content: space-between; - align-items: center; +@font-face { + font-family: 'Source Sans Pro'; + src: url('./fonts/SourceSansPro-Regular.woff2') format('woff2'); + font-weight: 400; + font-display: swap; } -.name-cell { - display: flex; - flex-direction: column; -} - -.name-cell .name { - font-weight: 500; -} - -.name-cell .remark { - font-size: 12px; - opacity: 0.65; -} - -.address-header { - display: inline-flex; - align-items: center; - gap: 6px; -} - -.ip-toggle-icon { - cursor: pointer; - font-size: 14px; - opacity: 0.7; -} - -.ip-toggle-icon:hover { - opacity: 1; -} - -.address-hidden { - filter: blur(5px); - transition: filter 0.2s ease; -} - -.address-visible { - filter: none; -} - -.node-cards { - display: flex; - flex-direction: column; - gap: 12px; - margin-top: 4px; -} - -.node-card { - border: 1px solid var(--ant-color-border-secondary); - border-radius: 10px; - padding: 12px; - background: var(--ant-color-fill-quaternary); - display: flex; - flex-direction: column; - gap: 8px; -} - -.card-head { - display: flex; - align-items: center; - gap: 8px; - cursor: pointer; - user-select: none; -} - -.card-expand { - font-size: 12px; - opacity: 0.6; - transition: transform 150ms ease; - flex-shrink: 0; -} - -.card-expand.is-expanded { - transform: rotate(90deg); -} - -.node-name { - font-weight: 600; - flex: 1; +.nodes-overview { min-width: 0; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; } -.card-actions { - display: flex; - align-items: center; - gap: 8px; - flex-shrink: 0; -} - -.row-action-trigger { - font-size: 20px; - cursor: pointer; -} - -.card-stats { - display: flex; - flex-direction: column; - gap: 6px; -} - -.stat-row { +.nodes-heading, +.nodes-toolbar { display: flex; align-items: center; flex-wrap: wrap; - gap: 6px; + gap: 8px 12px; + margin-block-end: 12px; } -.stat-label { - font-size: 10px; - text-transform: uppercase; - letter-spacing: 0.04em; - opacity: 0.6; - min-width: 96px; - flex-shrink: 0; +.nodes-heading { + justify-content: space-between; } -.card-stats .ant-tag { - margin: 0; +.nodes-heading .ant-typography { + margin-block: 0; } -.card-history { - margin-top: 4px; - padding-top: 8px; - border-top: 1px solid var(--ant-color-border-secondary); +.nodes-toolbar .ant-input-affix-wrapper { + width: min(100%, 22rem); } -.card-empty { - text-align: center; - color: var(--ant-color-text-secondary); - padding: 24px 12px; +.nodes-toolbar .ant-select { + min-width: 9rem; +} + +.node-muted { + color: var(--node-muted); + font-size: 12px; +} + +.node-fleet-table .ant-table { + border: 1px solid var(--ant-color-border-secondary); + border-radius: var(--ant-border-radius); +} + +.node-fleet-table .ant-table-cell { + padding-inline: 6px !important; + overflow-wrap: anywhere; + vertical-align: middle; +} + +.node-fleet-table .ant-table-thead > tr > th { + background: var(--ant-color-fill-secondary); +} + +.node-row-fleet > td, +.node-card.node-row-fleet { + background: var(--node-fleet-bg); +} + +.node-row-master > td, +.node-card.node-row-master { + background: var(--node-master-bg); +} + +.node-cell-stack, +.node-client-counts, +.node-cards { display: flex; flex-direction: column; - align-items: center; - gap: 8px; + gap: 3px; + min-width: 0; +} + +.name-cell .name { + font-weight: 600; +} + +.node-child-name { + padding-inline-start: 6px; } .node-network-speed { display: inline-grid; - row-gap: 2px; - text-align: start; - line-height: 1.25; + gap: 3px; + font-variant-numeric: tabular-nums; } .node-network-direction { display: grid; - grid-template-columns: 1em auto; - column-gap: 4px; - align-items: center; - white-space: nowrap; + grid-template-columns: 1em minmax(0, 1fr); + gap: 4px; +} + +.node-hardware { + font-family: 'Source Sans Pro', system-ui, sans-serif; + line-height: 1.25; font-variant-numeric: tabular-nums; } + +.node-cpu { + font-size: 17px; + font-weight: 400; +} + +.node-ram { + font-size: 16px; + font-weight: 400; +} + +.node-open-link, +.node-status-button { + display: inline-flex; + align-items: center; + flex-wrap: wrap; + gap: 4px; +} + +.node-open-link:any-link, +.node-update-available { + color: var(--node-text); + text-decoration: underline; +} + +.node-status-button { + max-width: 100%; + border: 0; + padding: 2px; + background: transparent; + color: inherit; + font: inherit; + text-align: start; + cursor: pointer; +} + +.node-status-button .online-dot, +.node-status-button .xray-error-dot { + display: inline-block; + height: 6px; + width: 6px; + border-radius: 50%; + background: var(--node-online-dot); +} + +.node-status-button .xray-error-dot { + background: #722ed1; +} + +.node-status-tooltip { + overflow-wrap: anywhere; +} + +.node-update-available { + padding-inline: 0; + height: auto; + text-align: start; + white-space: normal; +} + +.node-client-counts .ant-tag { + color: var(--ant-color-text); + margin-inline-end: 0; + padding-inline: 3px; +} + +.node-cards { + gap: 10px; +} + +.node-card { + display: grid; + gap: 10px; + min-width: 0; + overflow-wrap: anywhere; + background: var(--node-surface); + border: 1px solid var(--node-border); + border-radius: var(--node-radius); + padding: 10px; +} + +.node-card-heading, +.node-card-metrics { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(9rem, 100%), 1fr)); + align-items: start; + gap: 8px; +} + +.node-card-history summary { + cursor: pointer; +} + +.node-visually-hidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} diff --git a/frontend/src/pages/nodes/NodeList.stories.tsx b/frontend/src/pages/nodes/NodeList.stories.tsx new file mode 100644 index 000000000..262fb94b6 --- /dev/null +++ b/frontend/src/pages/nodes/NodeList.stories.tsx @@ -0,0 +1,175 @@ +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { expect, within } from 'storybook/test'; +import { ConfigProvider } from 'antd'; +import { useState } from 'react'; +import { useMediaQuery } from '@/hooks/useMediaQuery'; +import type { NodeRecord } from '@/schemas/node'; +import NodeList from './NodeList'; + +const counts = { + clientCount: 7100, + inboundCount: 40, + activeCount: 6050, + disabledCount: 50, + depletedCount: 1000, + onlineCount: 210, +}; +const noop = () => {}; + +function Fixture({ compact, rtl }: { compact?: boolean; rtl?: boolean }) { + const [selectedIds, setSelectedIds] = useState([]); + const { isMobile } = useMediaQuery(1080); + const [now] = useState(Date.now); + const nodes: NodeRecord[] = [ + { + id: 1, + name: 'Finland edge', + status: 'online', + enable: true, + xrayVersion: '26.1.1', + panelVersion: '3.12.0', + latencyMs: 42, + lastHeartbeat: Math.floor(now / 1000) - 2, + scheme: 'https', + address: '2001:db8::3', + port: 2053, + basePath: '/edge/', + telemetry: { + sampledAt: now, + cpuPct: 0, + logicalCores: 8, + memUsedBytes: 4 * 2 ** 30, + memTotalBytes: 16 * 2 ** 30, + netUp: 1024, + netDown: 2048, + tcpCount: 0, + udpCount: 21, + load1: 0.25, + load5: 0.15, + load15: 0.1, + uptimeSecs: 5000, + }, + clientCount: 3077, + onlineCount: 31, + onlineTotalCount: 53, + }, + { + id: 2, + name: 'Frankfurt', + status: 'online', + enable: true, + panelVersion: '3.13.0', + scheme: 'https', + address: 'frankfurt-with-a-very-long-hostname.example.test', + port: 443, + telemetry: { sampledAt: now, cpuPct: 40, logicalCores: 4, tcpCount: 4, load1: 0.75 }, + }, + { + id: 3, + name: 'This-is-an-intentionally-long-node-name-without-spaces', + status: 'offline', + enable: true, + lastError: 'Remote panel did not respond', + }, + { + id: 4, + name: 'Standby', + status: 'online', + enable: false, + telemetry: { sampledAt: now, cpuPct: 100, tcpCount: 9 }, + }, + ]; + return ( + +
+ +
+
+ ); +} + +const meta = { title: 'Nodes/Fleet Monitoring', component: Fixture } satisfies Meta; +export default meta; +type Story = StoryObj; + +export const Desktop: Story = { + play: async ({ canvasElement, userEvent }) => { + const canvas = within(canvasElement); + const row = canvas.getByRole('row', { name: /All nodes/ }); + await expect(within(row).getByText('3/5 reporting')).toBeVisible(); + await expect(within(row).getByText('20.0%')).toBeVisible(); + await expect(within(row).queryByRole('checkbox')).toBeNull(); + await expect( + within(canvas.getByRole('row', { name: /This panel/ })).queryByRole('switch'), + ).toBeNull(); + const edge = canvas.getByRole('row', { name: /Finland edge/ }); + const link = within(edge).getByRole('link', { name: 'Open' }); + await expect(link).toHaveAttribute('href', 'https://[2001:db8::3]:2053/edge/'); + await expect(link).toHaveAttribute('rel', 'noopener noreferrer'); + const status = within(edge).getByRole('button', { name: 'Online' }); + await userEvent.click(status); + await expect( + await within(canvasElement.ownerDocument.body).findByText(/Latency · 42 ms/), + ).toBeVisible(); + const input = canvas.getByRole('searchbox', { name: 'Search' }); + await userEvent.click(input); + for (const viewport of [1280, 1440, 1664, 1920]) { + const container = canvas.getByRole('region', { name: 'Nodes' }); + container.style.width = `${viewport - 260}px`; + const table = container.querySelector('.ant-table-content') as HTMLElement; + await expect(table.scrollWidth).toBeLessThanOrEqual(table.clientWidth + 1); + container.style.width = ''; + } + await userEvent.type(input, 'Frankfurt'); + await expect(canvas.queryByText('Finland edge')).toBeNull(); + await expect(canvas.getByText('3/5 reporting')).toBeVisible(); + await userEvent.clear(input); + }, +}; + +export const Mobile: Story = { args: { compact: true } }; +export const RTL: Story = { args: { rtl: true }, globals: { theme: 'light' } }; diff --git a/frontend/src/pages/nodes/NodeList.tsx b/frontend/src/pages/nodes/NodeList.tsx index 3ae461c32..1e31c75f3 100644 --- a/frontend/src/pages/nodes/NodeList.tsx +++ b/frontend/src/pages/nodes/NodeList.tsx @@ -1,36 +1,58 @@ -import { useCallback, useMemo, useState } from 'react'; +import { useMemo, useState, type CSSProperties, type ReactNode } from 'react'; import { useTranslation } from 'react-i18next'; -import { Badge, Button, Card, Dropdown, Modal, Space, Switch, Table, Tag, Tooltip } from 'antd'; +import { + Badge, + Button, + Dropdown, + Input, + Select, + Space, + Switch, + Table, + Tag, + Tooltip, + Typography, + theme, +} from 'antd'; import type { BadgeProps } from 'antd'; -import type { ColumnsType } from 'antd/es/table'; +import type { ColumnType } from 'antd/es/table'; import { ApartmentOutlined, - ClusterOutlined, CloudDownloadOutlined, DeleteOutlined, EditOutlined, ExclamationCircleOutlined, EyeInvisibleOutlined, EyeOutlined, - InfoCircleOutlined, + ExportOutlined, + SearchOutlined, MoreOutlined, PlusOutlined, ReloadOutlined, - RightOutlined, SafetyCertificateOutlined, TeamOutlined, ThunderboltOutlined, } from '@ant-design/icons'; import NodeHistoryPanel from './NodeHistoryPanel'; -import NodeNetworkSpeed from './NodeNetworkSpeed'; +import { NetworkSpeedValues } from './NodeNetworkSpeed'; +import { + aggregateTelemetry, + freshTelemetry, + reportingSample, + useTelemetryClock, +} from './fleetTelemetry'; +import type { NodeTelemetry, NodeFleetCounts, NodeMasterView } from '@/generated/types'; +import { SizeFormatter } from '@/utils'; +import { withBasePath } from '@/api/http-init'; import type { NodeRecord } from '@/api/queries/useNodesQuery'; import { isPanelUpdateAvailable } from '@/lib/panel-version'; -import { activateOnKey } from '@/utils/a11y'; import './NodeList.css'; interface NodeListProps { nodes: NodeRecord[]; + master?: NodeMasterView; + fleet?: NodeFleetCounts; nodesUpdatedAt?: number; loading?: boolean; isMobile?: boolean; @@ -57,18 +79,15 @@ function isUpdateEligible(n: NodeRecord): boolean { // 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 { +function onlineCounts( + n: Pick, +): { 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; -} - function badgeStatus(status?: string): BadgeProps['status'] { switch (status) { case 'online': @@ -132,16 +151,12 @@ function StatusLabel({ status, xrayState }: HealthProps) { ? t('pages.nodes.statusValues.xrayError') : t('pages.nodes.statusValues.xrayStopped'); return ( - + {t('pages.nodes.statusValues.online')} ({detail}) ); } - return ( - - {t('pages.nodes.statusValues.online')} - - ); + return {t('pages.nodes.statusValues.online')}; } // A sub-node's status is free text from its parent node: show it as unknown, not as a key. return ( @@ -153,13 +168,13 @@ function StatusLabel({ status, xrayState }: HealthProps) { ); } -function formatPct(p?: number, available = true): string { +function formatPct(p?: number | null, available = true): string { if (!available) return '—'; if (typeof p !== 'number' || Number.isNaN(p)) return '-'; return `${p.toFixed(1)}%`; } -function formatUptime(secs?: number, available = true): string { +function formatUptime(secs?: number | null, available = true): string { if (!available) return '—'; if (!secs) return '-'; const days = Math.floor(secs / 86400); @@ -188,29 +203,249 @@ function useRelativeTime() { ); } -function OnlineTag({ node, compact }: { node: NodeRecord; compact?: boolean }) { +function OnlineTag({ node }: { node: Pick }) { const { t } = useTranslation(); const counts = onlineCounts(node); if (!counts) return null; - const tag = compact ? ( - - {counts.label} - - ) : ( - - {counts.label} {t('online')} - + const title = + counts.total > counts.synced + ? t('pages.nodes.onlineOnNode', { synced: counts.synced, total: counts.total }) + : t('online'); + return ( + + + {counts.label} + + ); - 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; } +type FleetRow = + | { kind: 'remote'; key: string | number; node: NodeRecord; telemetry?: NodeTelemetry } + | { kind: 'master'; key: 'master'; host: NodeMasterView; telemetry?: NodeTelemetry } + | { + kind: 'fleet'; + key: 'fleet'; + counts: NodeFleetCounts; + telemetry: NodeTelemetry; + reporting: number; + registered: number; + cpuHosts: number; + memoryHosts: number; + panelVersions: string[]; + xrayVersions: string[]; + }; + +function HealthStatus({ + node, + relativeTime, +}: { + node: HealthProps & + Partial>; + relativeTime: (ts?: number) => string; +}) { + const { t } = useTranslation(); + const status = node.enable === false ? 'disabled' : node.status; + const { tip, iconColor } = statusIssue(node); + return ( + + {node.id !== undefined && ( + <> +
+ {t('pages.nodes.lastHeartbeat')} · {relativeTime(node.lastHeartbeat)} +
+
+ {t('pages.nodes.latency')} · {node.latencyMs ? node.latencyMs + ' ms' : '—'} +
+ + )} + {node.xrayState && ( +
+ {t('pages.nodes.xrayVersion')} · {node.xrayState} +
+ )} + {tip &&
{tip}
} + + } + > + +
+ ); +} + +function Hardware({ sample, fleet }: { sample?: NodeTelemetry; fleet: boolean }) { + const { t } = useTranslation(); + const total = sample?.memTotalBytes; + const used = sample?.memUsedBytes; + const hasMemory = used != null && total != null && total > 0 && used <= total; + return ( +
+
+ {fleet ? t('pages.nodes.fleet.cpuAverage') : t('pages.nodes.cpu')}{' '} + {formatPct(sample?.cpuPct, sample?.cpuPct != null)} + {sample?.logicalCores != null && ( + <> · {t('pages.nodes.fleet.logicalCores', { cores: sample.logicalCores })} + )} +
+
+ RAM{' '} + {hasMemory ? ( + + {SizeFormatter.sizeFormat(used)} / {SizeFormatter.sizeFormat(total)} ·{' '} + {formatPct((100 * used) / total)} + + ) : ( + '—' + )} +
+ {hasMemory && ( + + {sample?.memAvailableBytes != null + ? t('pages.nodes.fleet.availableMemory', { + size: SizeFormatter.sizeFormat(sample?.memAvailableBytes), + }) + : t('pages.nodes.fleet.remainingMemory', { + size: SizeFormatter.sizeFormat(total - used), + })} + + )} +
+ ); +} + +function Connections({ sample, fleet }: { sample?: NodeTelemetry; fleet: boolean }) { + const { t, i18n } = useTranslation(); + const count = new Intl.NumberFormat(i18n.language); + return ( +
+ + TCP {sample?.tcpCount == null ? '—' : count.format(sample.tcpCount)} + + + UDP {sample?.udpCount == null ? '—' : count.format(sample.udpCount)} + + + {fleet ? t('pages.nodes.fleet.loadSum') : t('pages.nodes.fleet.load')}{' '} + + {[sample?.load1, sample?.load5, sample?.load15] + .map((v) => v?.toFixed(2) ?? '—') + .join(' / ')} + + +
+ ); +} + +function ClientCounts({ + counts, +}: { + counts: Pick< + NodeRecord, + | 'clientCount' + | 'activeCount' + | 'disabledCount' + | 'depletedCount' + | 'onlineCount' + | 'onlineTotalCount' + >; +}) { + const { t } = useTranslation(); + return ( +
+ + {counts.clientCount ?? 0} + + + {!!counts.activeCount && ( + + + {counts.activeCount} + + + )} + {!!counts.disabledCount && ( + + {counts.disabledCount} + + )} + {!!counts.depletedCount && ( + + + {counts.depletedCount} + + + )} + + +
+ ); +} + +function panelUrl(node: NodeRecord) { + if ( + (node.scheme !== 'https' && node.scheme !== 'http') || + !node.address || + !node.port || + !Number.isInteger(node.port) || + node.port < 1 || + node.port > 65535 || + /[\s/?#@\\]/.test(node.address) + ) + return undefined; + const address = + node.address.includes(':') && !node.address.startsWith('[') + ? '[' + node.address + ']' + : node.address; + try { + const origin = new URL(node.scheme + '://' + address + ':' + node.port); + const path = node.basePath || '/'; + if (!path.startsWith('/') || path.startsWith('//') || /[\\?#\p{Cc}]/u.test(path)) + return undefined; + return origin.origin + path; + } catch { + return undefined; + } +} + +function sampleVersions( + rows: (NodeRecord | NodeMasterView)[], + key: 'panelVersion' | 'xrayVersion', +) { + return [ + ...new Set(rows.map((row) => row[key]).filter((version): version is string => !!version)), + ]; +} + +function MobileHistory({ node }: { node: NodeRecord }) { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + return ( +
setOpen(event.currentTarget.open)}> + {t('pages.nodes.fleet.history')} + {open && } +
+ ); +} + +const editable = (row: FleetRow) => row.kind === 'remote' && !row.node.transitive; +const canSelect = (row: FleetRow) => + row.kind === 'remote' && !row.node.transitive && isUpdateEligible(row.node); + export default function NodeList({ nodes, + master, + fleet, nodesUpdatedAt, loading = false, isMobile = false, @@ -229,717 +464,517 @@ export default function NodeList({ restartingIds = noRestarts, }: NodeListProps) { const { t } = useTranslation(); + const { token } = theme.useToken(); const relativeTime = useRelativeTime(); - + const [search, setSearch] = useState(''); + const [filter, setFilter] = useState('all'); const [showAddress, setShowAddress] = useState(false); - const [statsNodeId, setStatsNodeId] = useState(null); - const [expandedIds, setExpandedIds] = useState>(new Set()); - - const restartItems = useCallback( - (node: NodeRecord) => - (['xray', 'panel'] as const).map((target) => ({ - key: `restart-${target}`, - icon: , - label: t(`pages.nodes.${target === 'xray' ? 'restartXray' : 'restartPanel'}`), - disabled: !node.enable || !!node.transitive || restartingIds.has(node.id), - onClick: () => onRestart(node, target), - })), - [t, onRestart, restartingIds], + const samples = useMemo( + () => [master?.telemetry, ...nodes.map((node) => node.telemetry)], + [master, nodes], ); + const now = useTelemetryClock(samples, nodesUpdatedAt); - // Map a direct node's GUID to its display name so a transitive sub-node can show - // which parent it is reached through (#4983); the master walks one level only. - const nameByGuid = useMemo(() => { - const m = new Map(); - for (const n of nodes) if (n.guid && !n.transitive) m.set(n.guid, n.name || n.guid); - return m; - }, [nodes]); + const rows = useMemo(() => { + const masterTelemetry = freshTelemetry(master?.telemetry, now, nodesUpdatedAt); + const remote = nodes.map((node): FleetRow & { kind: 'remote' } => ({ + kind: 'remote', + key: node.transitive ? 't-' + node.guid : node.id, + node, + telemetry: + node.enable && node.status === 'online' + ? freshTelemetry(node.telemetry, now, nodesUpdatedAt) + : undefined, + })); + const results: FleetRow[] = []; + if (fleet && nodes.length) { + const reported = remote.filter((row) => reportingSample(row.telemetry)); + const reportedSamples = [masterTelemetry, ...reported.map((row) => row.telemetry)].filter( + reportingSample, + ); + const hosts = [ + ...reported.map((row) => row.node), + ...(master && reportingSample(masterTelemetry) ? [master] : []), + ]; + results.push({ + kind: 'fleet', + key: 'fleet', + counts: fleet, + registered: nodes.length + 1, + reporting: reportedSamples.length, + ...aggregateTelemetry(reportedSamples), + panelVersions: sampleVersions(hosts, 'panelVersion'), + xrayVersions: sampleVersions(hosts, 'xrayVersion'), + }); + } + if (master) + results.push({ kind: 'master', key: 'master', host: master, telemetry: masterTelemetry }); - // Order direct nodes first, each immediately followed by its transitive - // sub-nodes, so the table reads as a parent -> child tree without colliding - // with the per-row history expander (transitive nodes carry id 0). - const dataSource = useMemo(() => { - const toRow = (n: NodeRecord): NodeRow => ({ - ...n, - url: `${n.scheme}://${n.address}:${n.port}${n.basePath || '/'}`, - key: n.transitive ? `t-${n.guid || ''}` : n.id, - }); - const childrenByParent = new Map(); - for (const n of nodes) { - if (n.transitive && n.parentGuid) { - const arr = childrenByParent.get(n.parentGuid) || []; - arr.push(n); - childrenByParent.set(n.parentGuid, arr); + const word = search.trim().toLocaleLowerCase(); + const visible = remote.filter( + ({ node }) => + (filter === 'all' || + (node.enable === false ? 'disabled' : (node.status ?? 'unknown')) === filter) && + (!word || + [node.name, node.remark, ...(showAddress ? [node.address] : [])].some((value) => + value?.toLocaleLowerCase().includes(word), + )), + ); + const children = new Map(); + for (const row of visible) { + if (!row.node.transitive || !row.node.parentGuid) continue; + const group = children.get(row.node.parentGuid) ?? []; + group.push(row); + children.set(row.node.parentGuid, group); + } + const inserted = new Set(); + for (const row of visible) { + if (row.node.transitive) continue; + results.push(row); + if (!row.node.guid) continue; + for (const child of children.get(row.node.guid) ?? []) { + if (inserted.has(child.key)) continue; + results.push(child); + inserted.add(child.key); } } - const ordered: NodeRow[] = []; - const added = new Set(); - const push = (n: NodeRecord) => { - const row = toRow(n); - ordered.push(row); - added.add(String(row.key)); - }; - for (const n of nodes) { - if (n.transitive) continue; - push(n); - if (n.guid) for (const child of childrenByParent.get(n.guid) || []) push(child); - } - // Transitive nodes whose parent isn't in the list still get shown. - for (const n of nodes) { - if (n.transitive && !added.has(`t-${n.guid || ''}`)) push(n); - } - return ordered; - }, [nodes]); + results.push(...visible.filter((row) => row.node.transitive && !inserted.has(row.key))); + return results; + }, [fleet, master, nodes, nodesUpdatedAt, now, search, filter, showAddress]); - const statsNode = - statsNodeId === null - ? undefined - : dataSource.find((node) => !node.transitive && node.id === statsNodeId); + const nameByGuid = useMemo( + () => + new Map(nodes.filter((n) => n.guid && !n.transitive).map((n) => [n.guid, n.name || n.guid])), + [nodes], + ); - function toggleExpanded(id: number) { - setExpandedIds((prev) => { - const next = new Set(prev); - if (next.has(id)) next.delete(id); - else next.add(id); - return next; - }); - } - - const columns = useMemo>( + const columns = useMemo[]>( () => [ { title: t('pages.nodes.actions'), - align: 'center', - width: 190, - render: (_value, record) => - record.transitive ? ( - - } style={{ margin: 0 }}> - {t('pages.nodes.subNode')} - - - ) : ( - - - + + ) : ( + + ), }, { - title: t('pages.nodes.cpu'), - dataIndex: 'cpuPct', - align: 'center', - width: 90, - render: (_value, record) => - formatPct(record.cpuPct, !record.unavailableMetrics?.includes('cpu')), - }, - { - title: t('pages.nodes.mem'), - dataIndex: 'memPct', - align: 'center', - width: 90, - render: (_value, record) => formatPct(record.memPct), + title: t('pages.nodes.fleet.hardware'), + width: '15%', + render: (_, row) => , }, { title: t('pages.nodes.networkSpeed'), - key: 'networkSpeed', - align: 'center', - width: 125, - render: (_value, record) => , + width: '9%', + render: (_, row) => ( + + ), }, { - title: t('pages.nodes.xrayVersion'), - dataIndex: 'xrayVersion', - align: 'center', - render: (_value, record) => record.xrayVersion || '-', + title: t('pages.nodes.fleet.connections'), + width: '10%', + render: (_, row) => , }, { - title: t('pages.nodes.panelVersion') || 'Panel version', - dataIndex: 'panelVersion', - align: 'center', - render: (_value, record) => { + title: t('pages.nodes.fleet.runtime'), + width: '10%', + render: (_, row) => { + if (row.kind === 'fleet') { + const version = (values: string[]) => + values.length > 1 ? t('pages.nodes.fleet.mixed') : values[0] || '—'; + return ( +
+ + {t('pages.nodes.xrayVersion')} · {version(row.xrayVersions)} + + + {t('pages.nodes.panelVersion')} · {version(row.panelVersions)} + +
+ ); + } + const host = row.kind === 'remote' ? row.node : row.host; const canUpdate = - isUpdateEligible(record) && - isPanelUpdateAvailable(latestVersion, record.panelVersion || ''); + row.kind === 'remote' && + !row.node.transitive && + isUpdateEligible(row.node) && + isPanelUpdateAvailable(latestVersion, host.panelVersion || ''); return ( - - {record.panelVersion || '-'} - {canUpdate && ( - - onUpdateNode(record)} - onKeyDown={activateOnKey(() => onUpdateNode(record))} - > - {t('pages.nodes.updateAvailable')} - - +
+ + {t('pages.nodes.xrayVersion')} · {host.xrayVersion || '—'} + + + {t('pages.nodes.panelVersion')} · {host.panelVersion || '—'} + + + {t('pages.nodes.uptime')} ·{' '} + + {formatUptime(row.telemetry?.uptimeSecs, row.telemetry?.uptimeSecs != null)} + + + {canUpdate && row.kind === 'remote' && ( + )} - +
); }, }, - { - title: t('pages.nodes.uptime'), - dataIndex: 'uptimeSecs', - align: 'center', - render: (_value, record) => - formatUptime(record.uptimeSecs, !record.unavailableMetrics?.includes('uptime')), - }, { title: t('clients'), - align: 'center', - width: 180, - render: (_value, record) => ( - - - {record.clientCount || 0} - - {record.activeCount ? ( - - - {record.activeCount} - - - ) : null} - {record.disabledCount ? ( - - - {record.disabledCount} - - - ) : null} - {record.depletedCount ? ( - - - {record.depletedCount} - - - ) : null} - - + width: '8%', + render: (_, row) => ( + ), }, - { - title: t('pages.nodes.latency'), - dataIndex: 'latencyMs', - align: 'center', - width: 100, - render: (_value, record) => - record.latencyMs && record.latencyMs > 0 ? `${record.latencyMs} ms` : '-', - }, - { - title: t('pages.nodes.lastHeartbeat'), - dataIndex: 'lastHeartbeat', - align: 'center', - width: 120, - render: (_value, record) => relativeTime(record.lastHeartbeat), - }, ], [ t, - showAddress, - relativeTime, - latestVersion, - nodesUpdatedAt, - onToggleEnable, - onProbe, - onEdit, - onDelete, - onUpdateNode, - restartItems, nameByGuid, + latestVersion, + onDelete, + onEdit, + onProbe, + onRestart, + onToggleEnable, + onUpdateNode, + relativeTime, + restartingIds, + showAddress, ], ); - // rc-table re-runs every cell renderer whenever the Table re-renders, so keep the - // same element until its inputs change rather than re-rendering all rows each time. + const hasSelectable = rows.some(canSelect); const nodeTable = useMemo( () => ( - - dataSource={dataSource} + + dataSource={rows} columns={columns} + tableLayout="fixed" + className="node-fleet-table" pagination={false} loading={loading} - scroll={{ x: 'max-content' }} - size="middle" + size="small" rowKey="key" + rowClassName={(row) => 'node-row-' + row.kind} rowSelection={ - dataSource.length > 1 + hasSelectable ? { + columnWidth: 32, selectedRowKeys: selectedIds, + renderCell: (_checked, row, _index, checkbox) => (editable(row) ? checkbox : null), + getCheckboxProps: (row) => ({ disabled: !canSelect(row) }), onChange: (keys) => - onSelectionChange(keys.filter((k) => typeof k === 'number') as number[]), - getCheckboxProps: (record) => ({ - disabled: !!record.transitive || !isUpdateEligible(record), - }), + onSelectionChange( + keys.filter( + (key): key is number => + typeof key === 'number' && + rows.some((row) => row.key === key && canSelect(row)), + ), + ), + } + : undefined + } + expandable={ + rows.some(editable) + ? { + columnWidth: 30, + columnTitle: ( + {t('pages.nodes.fleet.history')} + ), + expandedRowRender: (row) => + row.kind === 'remote' && , + rowExpandable: editable, } : undefined } - locale={{ - emptyText: ( -
- -
{t('noData')}
-
- ), - }} - expandable={{ - expandedRowRender: (record) => , - rowExpandable: (record) => !record.transitive, - }} /> ), - [dataSource, columns, loading, selectedIds, onSelectionChange, t], + [columns, hasSelectable, loading, onSelectionChange, rows, selectedIds, t], ); + const addressLabel = t('pages.index.toggleIpVisibility'); + const filterOptions = [ + { value: 'all', label: t('pages.nodes.fleet.allStatuses') }, + { value: 'online', label: t('pages.nodes.statusValues.online') }, + { value: 'offline', label: t('pages.nodes.statusValues.offline') }, + { value: 'disabled', label: t('disabled') }, + { value: 'unknown', label: t('pages.nodes.statusValues.unknown') }, + ]; + return ( - -
- - +
+
+
+ {t('menu.nodes')} + {t('pages.nodes.fleet.subtitle')} +
+ + + + +
+
+ } + aria-label={t('search')} + placeholder={t('search')} + allowClear + value={search} + onChange={(event) => setSearch(event.target.value)} + /> +