feat(nodes): show per-client live speed for clients served by nodes (#7100)

The clients page showed live upload/download speed only for clients the master's own Xray or TUIC served; a client connected through a managed node showed none, although the master already polls that node's counters.

Derive per-client deltas from each node snapshot in the traffic sync job and broadcast them as their own speed source, so they add to local speed instead of overwriting it. A client's diverging per-inbound counter copies fold to the per-field max, the rule the traffic merge applies (#5274).
This commit is contained in:
Bazil Bazikov
2026-11-24 19:37:14 +03:00
committed by GitHub
parent e0c01942ec
commit e65b5cbd65
7 changed files with 262 additions and 37 deletions
+3 -2
View File
@@ -17216,9 +17216,10 @@
"type": "string",
"enum": [
"xray",
"tuic"
"tuic",
"node"
],
"description": "Present for native TUIC samples; omitted Xray samples default to xray."
"description": "Present for native TUIC samples and for clients served by managed nodes; omitted Xray samples default to xray."
},
"clientTrafficIntervalMs": {
"type": "integer",
+3 -2
View File
@@ -17216,9 +17216,10 @@
"type": "string",
"enum": [
"xray",
"tuic"
"tuic",
"node"
],
"description": "Present for native TUIC samples; omitted Xray samples default to xray."
"description": "Present for native TUIC samples and for clients served by managed nodes; omitted Xray samples default to xray."
},
"clientTrafficIntervalMs": {
"type": "integer",
+11 -4
View File
@@ -93,7 +93,7 @@ export interface ClientSpeedEntry {
down: number;
}
type ClientSpeedSource = 'xray' | 'tuic';
type ClientSpeedSource = 'xray' | 'tuic' | 'node';
type ClientStatRow = ClientTraffic & { email?: string };
@@ -300,7 +300,11 @@ export function useClients(options: UseClientsOptions = {}) {
Partial<Record<ClientSpeedSource, Record<string, ClientSpeedEntry>>>
>({});
const clientSpeedExpiryTimers = useRef<Partial<Record<ClientSpeedSource, number>>>({});
const clientSpeedSourceVersions = useRef<Record<ClientSpeedSource, number>>({ xray: 0, tuic: 0 });
const clientSpeedSourceVersions = useRef<Record<ClientSpeedSource, number>>({
xray: 0,
tuic: 0,
node: 0,
});
const clientSpeed = useMemo(() => {
const combined: Record<string, ClientSpeedEntry> = {};
for (const source of Object.values(clientSpeedBySource)) {
@@ -756,7 +760,7 @@ export function useClients(options: UseClientsOptions = {}) {
const p = payload as {
onlineClients?: string[];
clientTraffics?: { email: string; up: number; down: number }[];
clientTrafficSource?: 'xray' | 'tuic';
clientTrafficSource?: ClientSpeedSource;
clientTrafficIntervalMs?: number;
};
if (Array.isArray(p.onlineClients)) {
@@ -769,7 +773,10 @@ export function useClients(options: UseClientsOptions = {}) {
// dropped and an unchanged result returns the previous object — which lets
// React bail out of the update instead of re-rendering the table.
const next: Record<string, ClientSpeedEntry> = {};
const source = p.clientTrafficSource === 'tuic' ? 'tuic' : 'xray';
const source: ClientSpeedSource =
p.clientTrafficSource === 'tuic' || p.clientTrafficSource === 'node'
? p.clientTrafficSource
: 'xray';
const sampleIntervalMs =
typeof p.clientTrafficIntervalMs === 'number' &&
Number.isFinite(p.clientTrafficIntervalMs) &&
@@ -125,8 +125,9 @@ const trafficPayloadSchema = {
clientTraffics: { type: 'array', items: { $ref: '#/components/schemas/ClientTraffic' } },
clientTrafficSource: {
type: 'string',
enum: ['xray', 'tuic'],
description: 'Present for native TUIC samples; omitted Xray samples default to xray.',
enum: ['xray', 'tuic', 'node'],
description:
'Present for native TUIC samples and for clients served by managed nodes; omitted Xray samples default to xray.',
},
clientTrafficIntervalMs: {
type: 'integer',
@@ -155,6 +155,41 @@ describe('client summary always reflects the server, never a client_stats recomp
expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 10, down: 5 });
});
it('keeps node-sourced speeds separate from local Xray samples', async () => {
const result = await loadedHook();
act(() => {
result.current.applyTrafficEvent({
clientTrafficSource: 'node',
clientTrafficIntervalMs: 5_000,
clientTraffics: [{ email: 'shared@example.test', up: 500, down: 1_000 }],
});
});
expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 100, down: 200 });
// A local Xray poll with no movement must not wipe the node sample.
act(() => {
result.current.applyTrafficEvent({ clientTraffics: [] });
});
expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 100, down: 200 });
act(() => {
result.current.applyTrafficEvent({
clientTraffics: [{ email: 'shared@example.test', up: 50, down: 50 }],
});
});
expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 110, down: 210 });
act(() => {
result.current.applyTrafficEvent({
clientTrafficSource: 'node',
clientTrafficIntervalMs: 5_000,
clientTraffics: [],
});
});
expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 10, down: 10 });
});
it('expires stale per-source speeds without clearing the other source', async () => {
const result = await loadedHook();
vi.useFakeTimers();
@@ -0,0 +1,88 @@
package job
import (
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
// A legacy per-inbound row can lag the shared counter (#5274); listed last, it must not win.
func TestNodeClientTotals_FoldsDivergentCopiesToTheHighest(t *testing.T) {
row := xray.ClientTraffic{Email: "a@x", Up: 100, Down: 200}
stale := xray.ClientTraffic{Email: "a@x", Up: 40, Down: 60}
snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{
{Tag: "in-443", ClientStats: []xray.ClientTraffic{row, {Email: "b@x", Up: 1, Down: 2}}},
{Tag: "in-9452", ClientStats: []xray.ClientTraffic{stale}},
nil,
}}
got := nodeClientTotals(snap)
if len(got) != 2 || got["a@x"] != [2]int64{100, 200} || got["b@x"] != [2]int64{1, 2} {
t.Fatalf("unexpected totals: %v", got)
}
}
func TestDiffClientTotals_FirstPollOnlyBaselines(t *testing.T) {
next, deltas := diffClientTotals(nil, map[string][2]int64{"a@x": {10, 20}}, 1000)
if len(deltas) != 0 {
t.Fatalf("first poll must not emit speed, got %v", deltas)
}
if next["a@x"] != (inboundSample{up: 10, down: 20, at: 1000}) {
t.Fatalf("baseline not recorded: %v", next)
}
}
func TestDiffClientTotals_DeltaAndIdle(t *testing.T) {
prev := map[string]inboundSample{
"a@x": {up: 10, down: 20, at: 0},
"b@x": {up: 5, down: 5, at: 0},
}
cur := map[string][2]int64{"a@x": {1010, 5020}, "b@x": {5, 5}}
next, deltas := diffClientTotals(prev, cur, nodeInboundSpeedWindowMs)
if len(deltas) != 1 || deltas[0].Email != "a@x" || deltas[0].Up != 1000 || deltas[0].Down != 5000 {
t.Fatalf("unexpected deltas: %+v", deltas)
}
// Idle client keeps its change timestamp so a later jump averages over the gap.
if next["b@x"].at != 0 {
t.Fatalf("idle client timestamp advanced: %v", next["b@x"])
}
}
func TestDiffClientTotals_GapIsAveraged(t *testing.T) {
prev := map[string]inboundSample{"a@x": {up: 0, down: 0, at: 0}}
// 4000 bytes moved over two windows -> shown as 2000 per window.
_, deltas := diffClientTotals(prev, map[string][2]int64{"a@x": {0, 4000}}, 2*nodeInboundSpeedWindowMs)
if len(deltas) != 1 || deltas[0].Down != 2000 {
t.Fatalf("gap not averaged: %+v", deltas)
}
}
func TestDiffClientTotals_ResetRebaselines(t *testing.T) {
prev := map[string]inboundSample{"a@x": {up: 500, down: 500, at: 0}}
next, deltas := diffClientTotals(prev, map[string][2]int64{"a@x": {0, 0}}, 7000)
if len(deltas) != 0 {
t.Fatalf("reset must not emit speed: %+v", deltas)
}
if next["a@x"] != (inboundSample{up: 0, down: 0, at: 7000}) {
t.Fatalf("reset not rebaselined: %v", next["a@x"])
}
}
func TestRecordNodeClientSpeed_PerNodeBaselinesAndPrune(t *testing.T) {
j := NewNodeTrafficSyncJob()
mk := func(up, down int64) *runtime.TrafficSnapshot {
return &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{
{ClientStats: []xray.ClientTraffic{{Email: "a@x", Up: up, Down: down}}},
}}
}
j.recordNodeClientSpeed(1, mk(0, 0))
j.recordNodeClientSpeed(2, mk(1_000_000, 1_000_000))
if len(j.tickClientSpeed) != 0 || len(j.prevClientTotals) != 2 {
t.Fatalf("baselines: tick=%v prev=%v", j.tickClientSpeed, j.prevClientTotals)
}
j.pruneClientSpeedNodes([]*model.Node{{Id: 1}})
if _, ok := j.prevClientTotals[2]; ok || len(j.prevClientTotals) != 1 {
t.Fatalf("deleted node not pruned: %v", j.prevClientTotals)
}
}
+119 -27
View File
@@ -55,6 +55,12 @@ type NodeTrafficSyncJob struct {
// a per-inbound speed delta — node inbounds have no local Xray poll. Touched
// only from Run (serialized).
prevInboundTotals map[string]inboundSample
// Per-client counterpart keyed node id -> email, so a client on several nodes
// gets a baseline per node; guarded by clientSpeedMu as syncOne runs in parallel.
clientSpeedMu sync.Mutex
prevClientTotals map[int]map[string]inboundSample
// This tick's normalized per-client deltas from every synced node.
tickClientSpeed []*xray.ClientTraffic
}
type atomicBool struct {
@@ -111,6 +117,11 @@ func (j *NodeTrafficSyncJob) Run() {
}
j.ipSyncMu.Unlock()
j.clientSpeedMu.Lock()
j.tickClientSpeed = make([]*xray.ClientTraffic, 0)
j.pruneClientSpeedNodes(nodes)
j.clientSpeedMu.Unlock()
sem := make(chan struct{}, nodeTrafficSyncConcurrency)
var wg sync.WaitGroup
var activeMu sync.Mutex
@@ -223,6 +234,17 @@ func (j *NodeTrafficSyncJob) Run() {
trafficPayload["nodeTraffics"] = inboundSpeed
websocket.BroadcastTraffic(trafficPayload)
// Own source so the clients page adds it to local Xray/TUIC speed instead of
// overwriting it; sent even when empty so idle clients clear.
j.clientSpeedMu.Lock()
clientSpeed := j.tickClientSpeed
j.clientSpeedMu.Unlock()
websocket.BroadcastTraffic(map[string]any{
"clientTraffics": clientSpeed,
"clientTrafficSource": "node",
"clientTrafficIntervalMs": nodeInboundSpeedWindowMs,
})
clientStats := map[string]any{"snapshot": snapshot}
if len(stats) > 0 {
clientStats["clients"] = stats
@@ -263,41 +285,110 @@ func (j *NodeTrafficSyncJob) nodeInboundSpeed() []*xray.Traffic {
next := make(map[string]inboundSample, len(totals))
for tag, cur := range totals {
prev, ok := j.prevInboundTotals[tag]
if !ok {
next[tag] = inboundSample{up: cur[0], down: cur[1], at: now}
continue
}
dUp := cur[0] - prev.up
dDown := cur[1] - prev.down
if dUp <= 0 && dDown <= 0 {
// No movement, or a counter reset: hold the change timestamp so a
// later jump is averaged over the real elapsed window, not shown as a
// spike. Adopt the lower value on a reset.
if cur[0] < prev.up || cur[1] < prev.down {
next[tag] = inboundSample{up: cur[0], down: cur[1], at: now}
} else {
next[tag] = prev
}
continue
}
if dUp < 0 {
dUp = 0
}
if dDown < 0 {
dDown = 0
}
elapsed := max(now-prev.at, nodeInboundSpeedWindowMs)
up := dUp * nodeInboundSpeedWindowMs / elapsed
down := dDown * nodeInboundSpeedWindowMs / elapsed
sample, up, down := speedStep(prev, ok, cur, now)
next[tag] = sample
if up > 0 || down > 0 {
deltas = append(deltas, &xray.Traffic{Tag: tag, IsInbound: true, Up: up, Down: down})
}
next[tag] = inboundSample{up: cur[0], down: cur[1], at: now}
}
j.prevInboundTotals = next
return deltas
}
// speedStep advances one counter's baseline and returns its delta normalized to
// nodeInboundSpeedWindowMs; see nodeInboundSpeed for the idle/gap/reset rules.
func speedStep(prev inboundSample, ok bool, cur [2]int64, now int64) (inboundSample, int64, int64) {
if !ok {
return inboundSample{up: cur[0], down: cur[1], at: now}, 0, 0
}
dUp := cur[0] - prev.up
dDown := cur[1] - prev.down
if dUp <= 0 && dDown <= 0 {
if cur[0] < prev.up || cur[1] < prev.down {
return inboundSample{up: cur[0], down: cur[1], at: now}, 0, 0
}
return prev, 0, 0
}
if dUp < 0 {
dUp = 0
}
if dDown < 0 {
dDown = 0
}
elapsed := max(now-prev.at, nodeInboundSpeedWindowMs)
return inboundSample{up: cur[0], down: cur[1], at: now},
dUp * nodeInboundSpeedWindowMs / elapsed,
dDown * nodeInboundSpeedWindowMs / elapsed
}
// A client on several inbounds of one node shares one counter row, so copies are
// never summed; divergent copies fold to the per-field max, as the merge does (#5274).
func nodeClientTotals(snap *runtime.TrafficSnapshot) map[string][2]int64 {
totals := make(map[string][2]int64)
if snap == nil {
return totals
}
for _, ib := range snap.Inbounds {
if ib == nil {
continue
}
for _, cs := range ib.ClientStats {
if cs.Email == "" {
continue
}
cur := totals[cs.Email]
totals[cs.Email] = [2]int64{max(cur[0], cs.Up), max(cur[1], cs.Down)}
}
}
return totals
}
func diffClientTotals(prev map[string]inboundSample, cur map[string][2]int64, now int64) (map[string]inboundSample, []*xray.ClientTraffic) {
next := make(map[string]inboundSample, len(cur))
var deltas []*xray.ClientTraffic
for email, c := range cur {
p, ok := prev[email]
sample, up, down := speedStep(p, ok, c, now)
next[email] = sample
if up > 0 || down > 0 {
deltas = append(deltas, &xray.ClientTraffic{Email: email, Up: up, Down: down})
}
}
return next, deltas
}
func (j *NodeTrafficSyncJob) recordNodeClientSpeed(nodeID int, snap *runtime.TrafficSnapshot) {
cur := nodeClientTotals(snap)
now := time.Now().UnixMilli()
j.clientSpeedMu.Lock()
defer j.clientSpeedMu.Unlock()
if j.prevClientTotals == nil {
j.prevClientTotals = make(map[int]map[string]inboundSample)
}
next, deltas := diffClientTotals(j.prevClientTotals[nodeID], cur, now)
j.prevClientTotals[nodeID] = next
j.tickClientSpeed = append(j.tickClientSpeed, deltas...)
}
// Offline nodes keep their baselines so the first poll after recovery averages
// over the gap. Caller holds clientSpeedMu.
func (j *NodeTrafficSyncJob) pruneClientSpeedNodes(nodes []*model.Node) {
if len(j.prevClientTotals) == 0 {
return
}
alive := make(map[int]struct{}, len(nodes))
for _, n := range nodes {
if n != nil {
alive[n.Id] = struct{}{}
}
}
for id := range j.prevClientTotals {
if _, ok := alive[id]; !ok {
delete(j.prevClientTotals, id)
}
}
}
// maybePushGlobals broadcasts this panel's aggregated per-client usage to its
// online nodes so each node can display the client's cross-panel total and
// enforce its quota locally (see InboundService.AcceptGlobalTraffic). Scoped
@@ -431,6 +522,7 @@ func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSy
if changed {
j.structural.set()
}
j.recordNodeClientSpeed(n.Id, snap)
if !dirty && n.InboundsAdoptedAt == 0 && syncCanAdopt {
if markErr := j.nodeService.MarkNodeInboundsAdopted(n.Id); markErr != nil {
logger.Warningf("node traffic sync: mark inbounds adopted for %s failed: %v", n.Name, markErr)