fix(traffic): count the first managed Xray sample (#7246)

The traffic poller treated the first stats reply of every core as a baseline and credited none of it, so whatever clients moved between an Xray start and the first poll never reached their committed usage. A restart on the same API port also kept the previous core's last values, which under-credited the new core by that amount, and by all of it when the new counter had not yet passed the old one.

Track the baseline by process identity instead: a core the panel has just started counts from zero, and the poller keeps its own API client so a restart issued by any other service value cannot leave stale values behind. A panel-only reload keeps the same process and is not counted again. A generic API connection to a core with unknown counter history still takes a baseline first.

Fixes #7211
This commit is contained in:
Hamed
2026-11-28 17:43:35 +03:30
committed by GitHub
parent 33cfa52770
commit 9088b8a768
3 changed files with 203 additions and 9 deletions
+18 -4
View File
@@ -89,6 +89,10 @@ type XrayService struct {
settingService SettingService
nodeService NodeService
xrayAPI xray.XrayAPI
trafficMu sync.Mutex
trafficAPI xray.XrayAPI
trafficProcess *xray.Process
}
// IsXrayRunning checks if the Xray process is currently running.
@@ -1384,24 +1388,35 @@ func stripDisabledRules(routerCfg json_util.RawMessage) json_util.RawMessage {
// GetXrayTraffic fetches the current traffic statistics from the running Xray process.
func (s *XrayService) GetXrayTraffic() ([]*xray.Traffic, []*xray.ClientTraffic, error) {
s.trafficMu.Lock()
defer s.trafficMu.Unlock()
process := currentXrayProcess()
if process == nil || !process.IsRunning() {
err := ErrXrayNotRunning
logger.Debug("Attempted to fetch Xray traffic, but Xray is not running:", err)
return nil, nil, err
}
if s.trafficProcess != process {
s.trafficAPI.ResetTrafficForManagedProcess()
s.trafficProcess = process
}
apiPort := process.GetAPIPort()
if err := s.xrayAPI.Init(apiPort); err != nil {
if err := s.trafficAPI.Init(apiPort); err != nil {
logger.Debug("Failed to initialize Xray API:", err)
return nil, nil, err
}
defer s.xrayAPI.Close()
defer s.trafficAPI.Close()
traffic, clientTraffic, err := s.xrayAPI.GetTraffic()
traffic, clientTraffic, err := s.trafficAPI.GetTraffic()
if err != nil {
logger.Debug("Failed to fetch Xray traffic:", err)
return nil, nil, err
}
// A restarted core can reuse this port between the family RPCs.
if currentXrayProcess() != process {
return nil, nil, errors.New("Xray process changed during traffic collection")
}
return traffic, clientTraffic, nil
}
@@ -1582,7 +1597,6 @@ func (s *XrayService) RestartXray(isForce bool) error {
invalidateTuicRelayReadiness(xrayConfig)
process = xray.NewProcess(xrayConfig)
xrayState.replace(process)
s.xrayAPI.StatsLastValues = nil
err = process.Start()
if err != nil {
return err
@@ -0,0 +1,174 @@
package service
import (
"bufio"
"context"
"encoding/binary"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"testing"
"time"
"github.com/google/uuid"
stats "github.com/xtls/xray-core/app/stats/command"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
func TestManagedXrayFirstTrafficAfterStartAndReplacement(t *testing.T) {
bin := os.Getenv("XRAY_E2E_BINARY")
if bin == "" {
t.Skip("set XRAY_E2E_BINARY to run the real-core traffic lifecycle")
}
db := initTrafficTestDB(t)
dir := t.TempDir()
t.Setenv("XUI_BIN_FOLDER", dir)
t.Setenv("XUI_LOG_FOLDER", dir)
t.Cleanup(func() {
if t.Failed() {
data, _ := os.ReadFile(filepath.Join(dir, "error.log"))
t.Log(string(data))
}
})
if err := os.Symlink(bin, filepath.Join(dir, xray.GetBinaryName())); err != nil {
t.Fatal(err)
}
previous, _ := xrayState.snapshot()
t.Cleanup(func() { xrayState.replace(previous) })
const email = "managed-first-traffic@example.test"
clientID := uuid.New()
apiPort, proxyPort := freeLoopbackPort(t), freeLoopbackPort(t)
ib := &model.Inbound{Tag: "traffic-probe", Port: proxyPort, Protocol: model.VLESS, Enable: true, Settings: "{}"}
if err := db.Create(ib).Error; err != nil {
t.Fatal(err)
}
client := &xray.ClientTraffic{InboundId: ib.Id, Email: email, Up: 150, Down: 300, Enable: true}
if err := db.Create(client).Error; err != nil {
t.Fatal(err)
}
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = io.WriteString(w, "traffic fixture")
}))
defer origin.Close()
originPort := origin.Listener.Addr().(*net.TCPAddr).Port
cfg := &xray.Config{
LogConfig: mustJSON(t, map[string]string{"loglevel": "debug", "error": filepath.Join(dir, "error.log"), "access": filepath.Join(dir, "access.log")}),
RouterConfig: []byte(`{"rules":[{"type":"field","inboundTag":["api"],"outboundTag":"api"}]}`),
OutboundConfigs: []byte(`[{"protocol":"freedom","tag":"direct","settings":{"finalRules":[{"action":"allow","ip":["127.0.0.1/32"]}]}}]`),
API: []byte(`{"tag":"api","services":["StatsService"]}`),
Stats: []byte(`{}`),
Policy: []byte(`{"levels":{"0":{"statsUserUplink":true,"statsUserDownlink":true}}}`),
InboundConfigs: []xray.InboundConfig{
{Listen: mustJSON(t, "127.0.0.1"), Port: apiPort, Protocol: "tunnel", Tag: "api", Settings: []byte(`{"rewriteAddress":"127.0.0.1"}`)},
{
Listen: mustJSON(t, "127.0.0.1"), Port: proxyPort, Protocol: "vless", Tag: ib.Tag,
Settings: fmt.Appendf(nil, `{"decryption":"none","clients":[{"id":%q,"email":%q}]}`, clientID.String(), email),
},
},
}
poller := &XrayService{}
wantUp, wantDown := client.Up, client.Down
for _, requests := range []int{1, 2} {
process := xray.NewTestProcess(cfg, filepath.Join(dir, strconv.Itoa(requests)+".json"))
if err := process.Start(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = process.Stop() })
xrayState.replace(process)
probe := &xray.XrayAPI{}
if err := probe.Init(apiPort); err != nil {
t.Fatal(err)
}
t.Cleanup(probe.Close)
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
t.Cleanup(cancel)
var up, down int64
query := func() error {
out, err := (*probe.StatsServiceClient).QueryStats(ctx, &stats.QueryStatsRequest{Pattern: "user>>>"})
if err == nil {
up, down = 0, 0
for _, counter := range out.GetStat() {
switch counter.GetName() {
case "user>>>" + email + ">>>traffic>>>uplink":
up = counter.GetValue()
case "user>>>" + email + ">>>traffic>>>downlink":
down = counter.GetValue()
}
}
}
return err
}
for err := query(); err != nil; err = query() {
if ctx.Err() != nil {
t.Fatalf("stats API did not start: %v", err)
}
time.Sleep(20 * time.Millisecond)
}
for range requests {
sendManagedTrafficProbe(t, clientID, proxyPort, originPort)
}
if err := query(); err != nil || up <= 0 || down <= 0 {
t.Fatalf("non-resetting probe up=%d down=%d err=%v", up, down, err)
}
wantUp, wantDown = wantUp+up, wantDown+down
for range 2 {
inbounds, stats, err := poller.GetXrayTraffic()
if err != nil {
t.Fatal(err)
}
_, _, err = (&InboundService{}).AddXrayTrafficBatch(uuid.NewString(), inbounds, stats)
if err != nil {
t.Fatal(err)
}
if err := db.First(client, client.Id).Error; err != nil {
t.Fatal(err)
}
if client.Up != wantUp || client.Down != wantDown {
t.Fatalf("core %d committed up/down=%d/%d, want %d/%d", requests, client.Up, client.Down, wantUp, wantDown)
}
}
if err := process.Stop(); err != nil {
t.Fatal(err)
}
}
}
func sendManagedTrafficProbe(t *testing.T, clientID uuid.UUID, proxyPort, originPort int) {
t.Helper()
conn, err := net.DialTimeout("tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(proxyPort)), 3*time.Second)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
if err := conn.SetDeadline(time.Now().Add(3 * time.Second)); err != nil {
t.Fatal(err)
}
header := append([]byte{0}, clientID[:]...)
header = append(header, 0, 1) // no addons, TCP
header = binary.BigEndian.AppendUint16(header, uint16(originPort))
header = append(header, 1, 127, 0, 0, 1) // IPv4 loopback
if _, err := conn.Write(append(header, "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"...)); err != nil {
t.Fatal(err)
}
if _, err := io.ReadFull(conn, make([]byte, 2)); err != nil {
t.Fatal(err)
}
resp, err := http.ReadResponse(bufio.NewReader(conn), nil)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil || string(body) != "traffic fixture" {
t.Fatalf("origin response = %q, err=%v", body, err)
}
}
+11 -5
View File
@@ -139,6 +139,15 @@ func (x *XrayAPI) Init(apiPort int) error {
return nil
}
// ResetTrafficForManagedProcess starts counter tracking at zero for a fresh panel-owned core.
func (x *XrayAPI) ResetTrafficForManagedProcess() {
x.StatsLastValues = make(map[string]int64)
x.statsBaselined = make(map[string]bool, len(statsFamilies))
for _, family := range statsFamilies {
x.statsBaselined[family] = true
}
}
// Close closes the gRPC connection and resets the XrayAPI client state.
func (x *XrayAPI) Close() {
if x.grpcClient != nil {
@@ -1123,11 +1132,8 @@ func (x *XrayAPI) RemoveUser(inboundTag, email string) error {
// GetTraffic queries traffic statistics from the Xray core and reports what
// accrued since the previous call; the counters themselves are never reset.
// The first call of a process only records baselines, since it may be reading
// counters that already hold traffic the panel cannot attribute. After that a
// name the panel has not seen — xray creates a counter on a user's first use —
// and a counter that moved backwards because the core restarted both count
// from zero, so no client's traffic is dropped for a whole polling interval.
// An untracked core's first response establishes a baseline. Fresh managed
// cores, new counter names and counters that move backwards count from zero.
func (x *XrayAPI) GetTraffic() ([]*Traffic, []*ClientTraffic, error) {
if x.grpcClient == nil {
return nil, nil, common.NewError("xray api is not initialized")