mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-29 22:14:50 +03:00
feat(traffic): make the external traffic inform interval configurable (#7266)
The external traffic webhook was sent from inside the 5-second accounting job: its cadence could not be changed, and a slow receiver held up accounting. Add an interval setting (5 to 3600 seconds, default 5). The accounting poll only sums each tick's deltas per client email and per inbound or outbound tag; once the interval has passed, the batch is posted from its own goroutine. Accounting, quota enforcement and online updates keep their 5-second cadence. Delivery semantics are unchanged: each batch is posted once. A failure drops it, warns once with the reason (never the URI) and reports when deliveries resume. Destinations are checked at dial time and redirects are refused. A settings client that omits the interval keeps the stored value. Fixes #7028
This commit is contained in:
@@ -157,3 +157,18 @@ These have their own settings groups and pages:
|
||||
Email (SMTP) notifications are also configurable (host, port, encryption,
|
||||
recipients) with the same event types as the Telegram bot.
|
||||
</Callout>
|
||||
|
||||
### External traffic notifications
|
||||
|
||||
The **External traffic inform interval** controls how often the panel sends the
|
||||
external webhook. It defaults to 5 seconds and accepts values from 5 to 3600
|
||||
seconds. Traffic accounting, quota enforcement and online updates keep their
|
||||
five-second poll. Each webhook carries the deltas summed since the previous
|
||||
one, per client email and per inbound or outbound tag.
|
||||
|
||||
The request is sent outside the accounting poll, so a slow receiver cannot
|
||||
delay accounting. Each batch is sent once. If the receiver does not answer with
|
||||
a 2xx status within 3 seconds, the panel drops that batch, logs one warning
|
||||
with the reason, and logs again when deliveries resume. Deltas waiting for the
|
||||
next send are held in memory: disabling the webhook or a panel process exit
|
||||
discards them.
|
||||
|
||||
@@ -75,6 +75,10 @@
|
||||
"externalTrafficInformEnable": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"externalTrafficInformInterval": {
|
||||
"example": 5,
|
||||
"type": "integer"
|
||||
},
|
||||
"externalTrafficInformURI": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -700,6 +704,7 @@
|
||||
"expireDiff",
|
||||
"externalSubUserAgent",
|
||||
"externalTrafficInformEnable",
|
||||
"externalTrafficInformInterval",
|
||||
"externalTrafficInformURI",
|
||||
"happLinkEnable",
|
||||
"ipLimitAllowlist",
|
||||
@@ -938,6 +943,10 @@
|
||||
"externalTrafficInformEnable": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"externalTrafficInformInterval": {
|
||||
"example": 5,
|
||||
"type": "integer"
|
||||
},
|
||||
"externalTrafficInformURI": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -1593,6 +1602,7 @@
|
||||
"expireDiff",
|
||||
"externalSubUserAgent",
|
||||
"externalTrafficInformEnable",
|
||||
"externalTrafficInformInterval",
|
||||
"externalTrafficInformURI",
|
||||
"happLinkEnable",
|
||||
"hasApiToken",
|
||||
|
||||
@@ -75,6 +75,10 @@
|
||||
"externalTrafficInformEnable": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"externalTrafficInformInterval": {
|
||||
"example": 5,
|
||||
"type": "integer"
|
||||
},
|
||||
"externalTrafficInformURI": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -700,6 +704,7 @@
|
||||
"expireDiff",
|
||||
"externalSubUserAgent",
|
||||
"externalTrafficInformEnable",
|
||||
"externalTrafficInformInterval",
|
||||
"externalTrafficInformURI",
|
||||
"happLinkEnable",
|
||||
"ipLimitAllowlist",
|
||||
@@ -938,6 +943,10 @@
|
||||
"externalTrafficInformEnable": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"externalTrafficInformInterval": {
|
||||
"example": 5,
|
||||
"type": "integer"
|
||||
},
|
||||
"externalTrafficInformURI": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -1593,6 +1602,7 @@
|
||||
"expireDiff",
|
||||
"externalSubUserAgent",
|
||||
"externalTrafficInformEnable",
|
||||
"externalTrafficInformInterval",
|
||||
"externalTrafficInformURI",
|
||||
"happLinkEnable",
|
||||
"hasApiToken",
|
||||
|
||||
@@ -15,6 +15,7 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"expireDiff": 0,
|
||||
"externalSubUserAgent": "",
|
||||
"externalTrafficInformEnable": false,
|
||||
"externalTrafficInformInterval": 5,
|
||||
"externalTrafficInformURI": "",
|
||||
"happLinkEnable": false,
|
||||
"ipLimitAllowlist": "",
|
||||
@@ -217,6 +218,7 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"expireDiff": 0,
|
||||
"externalSubUserAgent": "",
|
||||
"externalTrafficInformEnable": false,
|
||||
"externalTrafficInformInterval": 5,
|
||||
"externalTrafficInformURI": "",
|
||||
"happLinkEnable": false,
|
||||
"hasApiToken": false,
|
||||
|
||||
@@ -49,6 +49,10 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"externalTrafficInformEnable": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"externalTrafficInformInterval": {
|
||||
"example": 5,
|
||||
"type": "integer"
|
||||
},
|
||||
"externalTrafficInformURI": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -674,6 +678,7 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"expireDiff",
|
||||
"externalSubUserAgent",
|
||||
"externalTrafficInformEnable",
|
||||
"externalTrafficInformInterval",
|
||||
"externalTrafficInformURI",
|
||||
"happLinkEnable",
|
||||
"ipLimitAllowlist",
|
||||
@@ -912,6 +917,10 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"externalTrafficInformEnable": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"externalTrafficInformInterval": {
|
||||
"example": 5,
|
||||
"type": "integer"
|
||||
},
|
||||
"externalTrafficInformURI": {
|
||||
"type": "string"
|
||||
},
|
||||
@@ -1567,6 +1576,7 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"expireDiff",
|
||||
"externalSubUserAgent",
|
||||
"externalTrafficInformEnable",
|
||||
"externalTrafficInformInterval",
|
||||
"externalTrafficInformURI",
|
||||
"happLinkEnable",
|
||||
"hasApiToken",
|
||||
|
||||
@@ -20,6 +20,7 @@ export interface AllSetting {
|
||||
expireDiff: number;
|
||||
externalSubUserAgent: string;
|
||||
externalTrafficInformEnable: boolean;
|
||||
externalTrafficInformInterval: number;
|
||||
externalTrafficInformURI: string;
|
||||
happLinkEnable: boolean;
|
||||
ipLimitAllowlist: string;
|
||||
@@ -223,6 +224,7 @@ export interface AllSettingView {
|
||||
expireDiff: number;
|
||||
externalSubUserAgent: string;
|
||||
externalTrafficInformEnable: boolean;
|
||||
externalTrafficInformInterval: number;
|
||||
externalTrafficInformURI: string;
|
||||
happLinkEnable: boolean;
|
||||
hasApiToken: boolean;
|
||||
|
||||
@@ -30,6 +30,7 @@ export const AllSettingSchema = z.object({
|
||||
expireDiff: z.number().int().min(0),
|
||||
externalSubUserAgent: z.string(),
|
||||
externalTrafficInformEnable: z.boolean(),
|
||||
externalTrafficInformInterval: z.number().int(),
|
||||
externalTrafficInformURI: z.string(),
|
||||
happLinkEnable: z.boolean(),
|
||||
ipLimitAllowlist: z.string(),
|
||||
@@ -234,6 +235,7 @@ export const AllSettingViewSchema = z.object({
|
||||
expireDiff: z.number().int().min(0),
|
||||
externalSubUserAgent: z.string(),
|
||||
externalTrafficInformEnable: z.boolean(),
|
||||
externalTrafficInformInterval: z.number().int(),
|
||||
externalTrafficInformURI: z.string(),
|
||||
happLinkEnable: z.boolean(),
|
||||
hasApiToken: z.boolean(),
|
||||
|
||||
@@ -75,6 +75,7 @@ export class AllSetting {
|
||||
subClashPath = '/clash/';
|
||||
subDomain = '';
|
||||
externalTrafficInformEnable = false;
|
||||
externalTrafficInformInterval = 5;
|
||||
externalTrafficInformURI = '';
|
||||
restartXrayOnClientDisable = true;
|
||||
mcpEnable = false;
|
||||
|
||||
@@ -517,6 +517,19 @@ export default function GeneralTab({ allSetting, updateSetting }: GeneralTabProp
|
||||
onChange={(e) => updateSetting({ externalTrafficInformURI: e.target.value })}
|
||||
/>
|
||||
</SettingListItem>
|
||||
<SettingListItem
|
||||
paddings="small"
|
||||
title={t('pages.settings.externalTrafficInformInterval')}
|
||||
>
|
||||
<InputNumber
|
||||
min={5}
|
||||
max={3600}
|
||||
precision={0}
|
||||
aria-label={t('pages.settings.externalTrafficInformInterval')}
|
||||
value={allSetting.externalTrafficInformInterval}
|
||||
onChange={onNumber((v) => updateSetting({ externalTrafficInformInterval: v }))}
|
||||
/>
|
||||
</SettingListItem>
|
||||
</>
|
||||
),
|
||||
},
|
||||
|
||||
@@ -87,6 +87,7 @@ export const AllSettingFieldsSchema = z
|
||||
subDomain: z.string().optional(),
|
||||
externalTrafficInformEnable: z.boolean().optional(),
|
||||
externalTrafficInformURI: z.string().optional(),
|
||||
externalTrafficInformInterval: z.number().int().min(5).max(3600).optional(),
|
||||
restartXrayOnClientDisable: z.boolean().optional(),
|
||||
mcpEnable: z.boolean().optional(),
|
||||
subCertFile: z.string().optional(),
|
||||
|
||||
@@ -145,6 +145,7 @@ type AllSetting struct {
|
||||
SubRateLimit int `json:"subRateLimit" form:"subRateLimit" validate:"gte=1,lte=1000"`
|
||||
ExternalTrafficInformEnable bool `json:"externalTrafficInformEnable" form:"externalTrafficInformEnable"`
|
||||
ExternalTrafficInformURI string `json:"externalTrafficInformURI" form:"externalTrafficInformURI"`
|
||||
TrafficInformInterval int `json:"externalTrafficInformInterval" form:"externalTrafficInformInterval" example:"5"`
|
||||
RestartXrayOnClientDisable bool `json:"restartXrayOnClientDisable" form:"restartXrayOnClientDisable"`
|
||||
SubEncrypt bool `json:"subEncrypt" form:"subEncrypt"`
|
||||
SubURI string `json:"subURI" form:"subURI"`
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
package job
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
const externalInformTimeout = 3 * time.Second
|
||||
|
||||
var externalInformClient = &http.Client{
|
||||
Timeout: externalInformTimeout,
|
||||
Transport: &http.Transport{DialContext: netsafe.SSRFGuardedDialContext, IdleConnTimeout: time.Minute, MaxIdleConnsPerHost: 1},
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}
|
||||
|
||||
type informTrafficKey struct {
|
||||
inbound, outbound bool
|
||||
tag string
|
||||
}
|
||||
|
||||
type trafficInformBatch struct {
|
||||
clients map[string]xray.ClientTraffic
|
||||
traffic map[informTrafficKey]xray.Traffic
|
||||
}
|
||||
|
||||
func (b *trafficInformBatch) add(traffics []*xray.Traffic, clients []*xray.ClientTraffic) {
|
||||
for _, row := range clients {
|
||||
if row == nil {
|
||||
continue
|
||||
}
|
||||
sum := b.clients[row.Email]
|
||||
b.clients[row.Email] = xray.ClientTraffic{Email: row.Email, Up: sum.Up + row.Up, Down: sum.Down + row.Down}
|
||||
}
|
||||
for _, row := range traffics {
|
||||
if row == nil {
|
||||
continue
|
||||
}
|
||||
key := informTrafficKey{row.IsInbound, row.IsOutbound, row.Tag}
|
||||
sum := b.traffic[key]
|
||||
b.traffic[key] = xray.Traffic{IsInbound: row.IsInbound, IsOutbound: row.IsOutbound, Tag: row.Tag, Up: sum.Up + row.Up, Down: sum.Down + row.Down}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *trafficInformBatch) body() ([]byte, error) {
|
||||
clients := slices.SortedFunc(maps.Values(b.clients), func(x, y xray.ClientTraffic) int { return cmp.Compare(x.Email, y.Email) })
|
||||
traffic := slices.SortedFunc(maps.Values(b.traffic), func(x, y xray.Traffic) int {
|
||||
return cmp.Or(cmp.Compare(x.Tag, y.Tag), cmp.Compare(fmt.Sprint(x.IsInbound, x.IsOutbound), fmt.Sprint(y.IsInbound, y.IsOutbound)))
|
||||
})
|
||||
return json.Marshal(struct {
|
||||
Clients []xray.ClientTraffic `json:"clientTraffics"`
|
||||
Traffic []xray.Traffic `json:"inboundTraffics"`
|
||||
}{slices.Clip(append([]xray.ClientTraffic{}, clients...)), slices.Clip(append([]xray.Traffic{}, traffic...))})
|
||||
}
|
||||
|
||||
// externalTrafficInform sums deltas between sends and posts each batch exactly once:
|
||||
// a receiver that does not deduplicate would count a repeated batch twice.
|
||||
type externalTrafficInform struct {
|
||||
settingService service.SettingService
|
||||
|
||||
mu sync.Mutex
|
||||
pending *trafficInformBatch
|
||||
nextSend time.Time
|
||||
problem string
|
||||
lost int
|
||||
}
|
||||
|
||||
// collect adds one accounting poll's deltas and hands out the batch once its interval has passed.
|
||||
// now is when the poll fired, not when its accounting finished.
|
||||
func (j *externalTrafficInform) collect(now time.Time, traffics []*xray.Traffic, clients []*xray.ClientTraffic) (due *trafficInformBatch, uri string) {
|
||||
cfg, err := j.settingService.GetExternalTrafficInformConfig()
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
switch {
|
||||
case err != nil:
|
||||
j.noteProblem("settings", "Skipping external traffic notification: settings are unavailable: "+err.Error())
|
||||
return nil, ""
|
||||
case !cfg.Enabled:
|
||||
j.pending, j.nextSend, j.problem, j.lost = nil, time.Time{}, "", 0
|
||||
return nil, ""
|
||||
case cfg.SkipReason != "":
|
||||
j.noteProblem(cfg.SkipReason, "Skipping external traffic notification: "+cfg.SkipReason)
|
||||
return nil, ""
|
||||
}
|
||||
if len(traffics) > 0 || len(clients) > 0 {
|
||||
if j.pending == nil {
|
||||
j.pending = &trafficInformBatch{clients: make(map[string]xray.ClientTraffic), traffic: make(map[informTrafficKey]xray.Traffic)}
|
||||
}
|
||||
j.pending.add(traffics, clients)
|
||||
}
|
||||
if j.pending == nil || now.Before(j.nextSend) {
|
||||
return nil, ""
|
||||
}
|
||||
due, j.pending = j.pending, nil
|
||||
// Polls fire on whole seconds, each a few milliseconds late: without the truncation
|
||||
// the next poll lands just before nextSend and a 5s interval sends every 10s.
|
||||
j.nextSend = now.Truncate(time.Second).Add(cfg.Interval)
|
||||
return due, cfg.URI
|
||||
}
|
||||
|
||||
// deliver posts one batch once. A failure is reported and the batch is dropped, as it always was.
|
||||
func (j *externalTrafficInform) deliver(batch *trafficInformBatch, uri string) {
|
||||
reason := postTrafficInform(batch, uri)
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
if reason != "" {
|
||||
j.noteProblem("delivery", "External traffic notification was not delivered: "+reason)
|
||||
return
|
||||
}
|
||||
if j.lost > 0 {
|
||||
logger.Infof("External traffic notifications resumed after %d undelivered batch(es)", j.lost)
|
||||
}
|
||||
j.problem, j.lost = "", 0
|
||||
}
|
||||
|
||||
// noteProblem warns when a problem starts or changes, not on every batch it costs (#7261).
|
||||
func (j *externalTrafficInform) noteProblem(problem, warning string) {
|
||||
j.lost++
|
||||
if j.problem != problem {
|
||||
j.problem = problem
|
||||
logger.Warning(warning)
|
||||
}
|
||||
}
|
||||
|
||||
func postTrafficInform(batch *trafficInformBatch, uri string) (failure string) {
|
||||
body, err := batch.body()
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, uri, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return "the request could not be built"
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
|
||||
resp, err := externalInformClient.Do(req)
|
||||
if err != nil {
|
||||
// url.Error repeats the full URI, which may carry a token in its query.
|
||||
var wrapped *url.Error
|
||||
if errors.As(err, &wrapped) {
|
||||
err = wrapped.Err
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||
return fmt.Sprintf("the receiver answered HTTP %d", resp.StatusCode)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -1,100 +1,194 @@
|
||||
package job
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/valyala/fasthttp"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
func stallingListener(t *testing.T) (addr string, release func()) {
|
||||
// routeExternalInformTo sends every notification to server, whatever public host the URI names.
|
||||
func routeExternalInformTo(t *testing.T, server *httptest.Server) {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
old := externalInformClient
|
||||
externalInformClient = &http.Client{
|
||||
Timeout: externalInformTimeout,
|
||||
Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return new(net.Dialer).DialContext(ctx, "tcp", server.Listener.Addr().String())
|
||||
}},
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
for {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func(c net.Conn) {
|
||||
<-done
|
||||
_ = c.Close()
|
||||
}(conn)
|
||||
go func(c net.Conn) { _, _ = io.Copy(io.Discard, c) }(conn)
|
||||
t.Cleanup(func() {
|
||||
externalInformClient.CloseIdleConnections()
|
||||
externalInformClient = old
|
||||
})
|
||||
}
|
||||
|
||||
func enableExternalInform(t *testing.T, inform *externalTrafficInform, uri string, intervalSeconds int) {
|
||||
t.Helper()
|
||||
if err := inform.settingService.SetExternalTrafficInformEnable(true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := inform.settingService.SetExternalTrafficInformURI(uri); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if intervalSeconds > 0 {
|
||||
row := model.Setting{Key: "externalTrafficInformInterval", Value: strconv.Itoa(intervalSeconds)}
|
||||
if err := database.GetDB().Create(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}()
|
||||
return ln.Addr().String(), func() {
|
||||
_ = ln.Close()
|
||||
<-done
|
||||
}
|
||||
}
|
||||
|
||||
func TestExternalInformClient_StalledReceiverTimesOut(t *testing.T) {
|
||||
addr, release := stallingListener(t)
|
||||
defer release()
|
||||
// informLogLines returns what follows marker in every matching log line, oldest first.
|
||||
func informLogLines(level, marker string) []string {
|
||||
var lines []string
|
||||
logs := logger.GetLogs(10240, level)
|
||||
for i := len(logs) - 1; i >= 0; i-- {
|
||||
if _, text, found := strings.Cut(logs[i], marker); found {
|
||||
lines = append(lines, text)
|
||||
}
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
request := fasthttp.AcquireRequest()
|
||||
defer fasthttp.ReleaseRequest(request)
|
||||
request.Header.SetMethod("POST")
|
||||
request.Header.SetContentType("application/json; charset=UTF-8")
|
||||
request.SetBody([]byte(`{"clientTraffics":[],"inboundTraffics":[]}`))
|
||||
request.SetRequestURI("http://" + addr + "/inform")
|
||||
request.Header.SetConnectionClose()
|
||||
type informReport struct {
|
||||
Clients []xray.ClientTraffic `json:"clientTraffics"`
|
||||
Traffic []xray.Traffic `json:"inboundTraffics"`
|
||||
}
|
||||
|
||||
response := fasthttp.AcquireResponse()
|
||||
defer fasthttp.ReleaseResponse(response)
|
||||
func TestExternalInformSumsDeltasUntilTheIntervalPasses(t *testing.T) {
|
||||
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
|
||||
inform := new(externalTrafficInform)
|
||||
enableExternalInform(t, inform, "http://192.0.2.1/traffic", 60)
|
||||
reports := make(chan informReport, 4)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var report informReport
|
||||
if err := json.NewDecoder(r.Body).Decode(&report); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
reports <- report
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
routeExternalInformTo(t, server)
|
||||
|
||||
start := time.Now()
|
||||
err := externalInformClient.DoTimeout(request, response, externalInformTimeout)
|
||||
elapsed := time.Since(start)
|
||||
first, uri := inform.collect(start, nil, []*xray.ClientTraffic{{Email: "x@test", Up: 1}})
|
||||
if first == nil || uri != "http://192.0.2.1/traffic" {
|
||||
t.Fatalf("the first batch was held back: batch=%v uri=%q", first, uri)
|
||||
}
|
||||
inform.deliver(first, uri)
|
||||
<-reports
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("a receiver that never answers must produce an error, not a completed request")
|
||||
for _, tick := range []struct {
|
||||
after time.Duration
|
||||
traffic []*xray.Traffic
|
||||
clients []*xray.ClientTraffic
|
||||
}{
|
||||
{5 * time.Second, []*xray.Traffic{{Tag: "shared", IsInbound: true, Up: 3}}, []*xray.ClientTraffic{{Email: "x@test", Up: 8}}},
|
||||
{10 * time.Second, []*xray.Traffic{{Tag: "shared", IsOutbound: true, Down: 4}}, []*xray.ClientTraffic{{Email: "x@test", Up: 6, Down: 2}, {Email: "y@test", Down: 9}}},
|
||||
{59 * time.Second, []*xray.Traffic{{Tag: "shared", IsInbound: true, Up: 2}}, nil},
|
||||
} {
|
||||
if batch, _ := inform.collect(start.Add(tick.after), tick.traffic, tick.clients); batch != nil {
|
||||
t.Fatalf("a batch was handed out %s into a 60s interval", tick.after)
|
||||
}
|
||||
}
|
||||
if !errors.Is(err, fasthttp.ErrTimeout) {
|
||||
t.Errorf("want a timeout error, got %v", err)
|
||||
// An idle tick still flushes what the interval collected.
|
||||
batch, uri := inform.collect(start.Add(60*time.Second), nil, nil)
|
||||
if batch == nil {
|
||||
t.Fatal("no batch was due once the interval had passed")
|
||||
}
|
||||
if elapsed > externalInformTimeout+2*time.Second {
|
||||
t.Errorf("call took %v, must be bounded by %v", elapsed, externalInformTimeout)
|
||||
inform.deliver(batch, uri)
|
||||
got := <-reports
|
||||
wantClients := []xray.ClientTraffic{{Email: "x@test", Up: 14, Down: 2}, {Email: "y@test", Down: 9}}
|
||||
wantTraffic := []xray.Traffic{{Tag: "shared", IsOutbound: true, Down: 4}, {Tag: "shared", IsInbound: true, Up: 5}}
|
||||
if len(got.Clients) != 2 || got.Clients[0] != wantClients[0] || got.Clients[1] != wantClients[1] {
|
||||
t.Errorf("client deltas = %+v, want %+v", got.Clients, wantClients)
|
||||
}
|
||||
if len(got.Traffic) != 2 || got.Traffic[0] != wantTraffic[0] || got.Traffic[1] != wantTraffic[1] {
|
||||
t.Errorf("tag deltas = %+v, want %+v", got.Traffic, wantTraffic)
|
||||
}
|
||||
if len(reports) != 0 {
|
||||
t.Errorf("%d extra reports were sent", len(reports))
|
||||
}
|
||||
}
|
||||
|
||||
func TestExternalInformClient_HasDeadlines(t *testing.T) {
|
||||
if externalInformClient.ReadTimeout <= 0 || externalInformClient.WriteTimeout <= 0 {
|
||||
t.Fatal("the traffic-notify client must carry read and write deadlines")
|
||||
}
|
||||
if externalInformTimeout >= 5*time.Second {
|
||||
t.Errorf("the call budget (%v) must stay under the 5s traffic poll cadence", externalInformTimeout)
|
||||
func TestExternalInformKeepsPaceWithTheAccountingPoll(t *testing.T) {
|
||||
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
|
||||
inform := new(externalTrafficInform)
|
||||
enableExternalInform(t, inform, "http://192.0.2.1/traffic", 0)
|
||||
// The poll fires on whole seconds, each time a few milliseconds late by a different amount.
|
||||
base := time.Date(2026, 11, 29, 13, 38, 0, 0, time.UTC)
|
||||
for i, lateness := range []time.Duration{12 * time.Millisecond, 9 * time.Millisecond, 4 * time.Millisecond, 30 * time.Millisecond} {
|
||||
tick := base.Add(time.Duration(i)*5*time.Second + lateness)
|
||||
if batch, _ := inform.collect(tick, nil, []*xray.ClientTraffic{{Email: "x@test", Up: 1}}); batch == nil {
|
||||
t.Fatalf("poll %d at +%s was held back: the default interval must send on every poll", i+1, tick.Sub(base))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInformSkippedWhenNothingToReport(t *testing.T) {
|
||||
j := &XrayTrafficJob{}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
j.informTrafficToExternalAPI(nil, nil)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("an empty payload must return before touching settings or the network")
|
||||
func TestExternalInformSendsAFailedBatchOnlyOnce(t *testing.T) {
|
||||
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
|
||||
inform := new(externalTrafficInform)
|
||||
enableExternalInform(t, inform, "http://192.0.2.1/traffic?token=synthetic-secret", 0)
|
||||
var bodies []string
|
||||
var healthy atomic.Bool
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
bodies = append(bodies, string(body))
|
||||
if !healthy.Load() {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
routeExternalInformTo(t, server)
|
||||
const failed, resumed = "External traffic notification was not delivered: ", "External traffic notifications resumed after "
|
||||
failuresBefore, resumesBefore := len(informLogLines("WARNING", failed)), len(informLogLines("INFO", resumed))
|
||||
|
||||
now := time.Now()
|
||||
for i, email := range []string{"first@test", "second@test", "third@test", "fourth@test"} {
|
||||
healthy.Store(i == 3)
|
||||
batch, uri := inform.collect(now.Add(time.Duration(i)*5*time.Second), nil, []*xray.ClientTraffic{{Email: email, Up: 1}})
|
||||
if batch == nil {
|
||||
t.Fatalf("batch %d was not due at the default 5s interval", i+1)
|
||||
}
|
||||
inform.deliver(batch, uri)
|
||||
}
|
||||
if len(bodies) != 4 {
|
||||
t.Fatalf("the receiver saw %d requests for 4 batches, want one each", len(bodies))
|
||||
}
|
||||
for i, email := range []string{"first@test", "second@test", "third@test", "fourth@test"} {
|
||||
var report informReport
|
||||
if err := json.Unmarshal([]byte(bodies[i]), &report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(report.Clients) != 1 || report.Clients[0].Email != email || report.Clients[0].Up != 1 {
|
||||
t.Errorf("request %d carried %s, want only %s: a refused batch must not be sent again", i+1, bodies[i], email)
|
||||
}
|
||||
}
|
||||
failures := informLogLines("WARNING", failed)[failuresBefore:]
|
||||
if len(failures) != 1 || failures[0] != "the receiver answered HTTP 503" {
|
||||
t.Errorf("failure warnings = %q, want one naming HTTP 503", failures)
|
||||
}
|
||||
resumes := informLogLines("INFO", resumed)[resumesBefore:]
|
||||
if len(resumes) != 1 || resumes[0] != "3 undelivered batch(es)" {
|
||||
t.Errorf("recovery lines = %q, want one counting 3 undelivered batches", resumes)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,28 +199,17 @@ func TestXrayTrafficSkipsInvalidExternalInformWithoutLosingCommittedDeltas(t *te
|
||||
if err := db.Create(&client).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var dials atomic.Int32
|
||||
oldClient := externalInformClient
|
||||
externalInformClient = &fasthttp.Client{Dial: func(string) (net.Conn, error) {
|
||||
externalInformClient = &http.Client{Transport: &http.Transport{DialContext: func(context.Context, string, string) (net.Conn, error) {
|
||||
dials.Add(1)
|
||||
return nil, errors.New("unexpected notification dial")
|
||||
}}
|
||||
return nil, net.ErrClosed
|
||||
}}}
|
||||
t.Cleanup(func() { externalInformClient = oldClient })
|
||||
|
||||
job := NewXrayTrafficJob()
|
||||
const warning = "Skipping external traffic notification: "
|
||||
skipWarnings := func() []string {
|
||||
var reasons []string
|
||||
for _, line := range logger.GetLogs(10240, "WARNING") {
|
||||
if _, reason, found := strings.Cut(line, warning); found {
|
||||
reasons = append(reasons, reason)
|
||||
}
|
||||
}
|
||||
return reasons
|
||||
}
|
||||
countWarnings := func() int { return len(skipWarnings()) }
|
||||
before := countWarnings()
|
||||
const skipped = "Skipping external traffic notification: "
|
||||
before := len(informLogLines("WARNING", skipped))
|
||||
run := func(enabled bool, uri, sampleID string) {
|
||||
t.Helper()
|
||||
if err := job.settingService.SetExternalTrafficInformEnable(enabled); err != nil {
|
||||
@@ -139,24 +222,23 @@ func TestXrayTrafficSkipsInvalidExternalInformWithoutLosingCommittedDeltas(t *te
|
||||
job.Run()
|
||||
}
|
||||
run(true, "https://user:synthetic-secret@example.test:bad/traffic", "malformed")
|
||||
run(true, "https://user:synthetic-secret@example.test:bad/traffic", "malformed-again")
|
||||
run(true, " \t ", "whitespace")
|
||||
run(true, "", "empty")
|
||||
if got := countWarnings() - before; got != 1 {
|
||||
t.Errorf("warnings during one invalid episode = %d, want 1", got)
|
||||
}
|
||||
|
||||
run(false, "", "disabled")
|
||||
run(true, "http://127.0.0.1/traffic", "blocked")
|
||||
if got := countWarnings() - before; got != 2 {
|
||||
t.Errorf("warnings across two invalid episodes = %d, want 2", got)
|
||||
run(true, "", "empty-again")
|
||||
want := []string{
|
||||
"ExternalTrafficInformURI is not a valid http(s) URL",
|
||||
"ExternalTrafficInformURI is empty",
|
||||
"ExternalTrafficInformURI is empty",
|
||||
}
|
||||
// GetLogs returns newest first: a rejected destination must say why it was rejected.
|
||||
if reasons := skipWarnings(); len(reasons) == 0 || reasons[0] != "blocked private/internal address 127.0.0.1" {
|
||||
t.Errorf("blocked destination warning = %q, want the private-address reason", reasons)
|
||||
got := informLogLines("WARNING", skipped)[before:]
|
||||
if strings.Join(got, "|") != strings.Join(want, "|") {
|
||||
t.Errorf("skip warnings = %q, want one per problem and one more after re-enabling: %q", got, want)
|
||||
}
|
||||
for _, line := range logger.GetLogs(32, "WARNING") {
|
||||
if strings.Contains(line, "ExternalTrafficInformURI") && strings.Contains(line, "synthetic-secret") {
|
||||
t.Error("external inform diagnostic disclosed the synthetic credential")
|
||||
for _, line := range logger.GetLogs(10240, "WARNING") {
|
||||
if strings.Contains(line, "synthetic-secret") {
|
||||
t.Errorf("a warning disclosed the URI's credential: %s", line)
|
||||
}
|
||||
}
|
||||
if got := dials.Load(); got != 0 {
|
||||
@@ -165,7 +247,74 @@ func TestXrayTrafficSkipsInvalidExternalInformWithoutLosingCommittedDeltas(t *te
|
||||
if err := db.First(&client, client.Id).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if client.Up != 55 || client.Down != 35 || client.LastOnline <= 0 {
|
||||
t.Errorf("stored counters and activity = (%d, %d, %d), want (55, 35, positive last online)", client.Up, client.Down, client.LastOnline)
|
||||
if client.Up != 66 || client.Down != 42 || client.LastOnline <= 0 {
|
||||
t.Errorf("stored counters and activity = (%d, %d, %d), want (66, 42, positive last online)", client.Up, client.Down, client.LastOnline)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExternalInformRefusesAPrivateDestinationAtDialTime(t *testing.T) {
|
||||
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
inform := new(externalTrafficInform)
|
||||
enableExternalInform(t, inform, "http://"+listener.Addr().String()+"/traffic", 0)
|
||||
const failed = "External traffic notification was not delivered: "
|
||||
before := len(informLogLines("WARNING", failed))
|
||||
|
||||
batch, uri := inform.collect(time.Now(), nil, []*xray.ClientTraffic{{Email: "x@test", Up: 1}})
|
||||
if batch == nil {
|
||||
t.Fatal("a well-formed URI must reach the dial-time check")
|
||||
}
|
||||
inform.deliver(batch, uri)
|
||||
reasons := informLogLines("WARNING", failed)[before:]
|
||||
if len(reasons) != 1 || !strings.Contains(reasons[0], "127.0.0.1") || strings.Contains(reasons[0], "/traffic") {
|
||||
t.Errorf("failure warnings = %q, want one naming the blocked address and not the URI", reasons)
|
||||
}
|
||||
_ = listener.(*net.TCPListener).SetDeadline(time.Now().Add(100 * time.Millisecond))
|
||||
if conn, err := listener.Accept(); err == nil {
|
||||
_ = conn.Close()
|
||||
t.Fatal("the notification dialed a loopback listener")
|
||||
}
|
||||
}
|
||||
|
||||
func TestXrayTrafficRunDoesNotWaitForAStalledReceiver(t *testing.T) {
|
||||
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
|
||||
release := make(chan struct{})
|
||||
reached := make(chan struct{}, 1)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
|
||||
reached <- struct{}{}
|
||||
select {
|
||||
case <-release:
|
||||
case <-r.Context().Done():
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
t.Cleanup(func() { close(release) })
|
||||
routeExternalInformTo(t, server)
|
||||
|
||||
job := NewXrayTrafficJob()
|
||||
enableExternalInform(t, &job.externalInform, "http://192.0.2.1/traffic", 0)
|
||||
job.pending = &xrayTrafficSample{id: "stalled", clients: []*xray.ClientTraffic{{Email: "x@test", Up: 1}}}
|
||||
started := time.Now()
|
||||
job.Run()
|
||||
if elapsed := time.Since(started); elapsed > time.Second {
|
||||
t.Fatalf("the accounting tick took %s while the receiver stalled", elapsed)
|
||||
}
|
||||
select {
|
||||
case <-reached:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("the report never left the panel")
|
||||
}
|
||||
const failed = "External traffic notification was not delivered: "
|
||||
before := len(informLogLines("WARNING", failed))
|
||||
deadline := time.Now().Add(externalInformTimeout + 2*time.Second)
|
||||
for len(informLogLines("WARNING", failed)) == before {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("a stalled receiver was not given up on within %s", externalInformTimeout)
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
package job
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service/outbound"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/websocket"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
|
||||
"github.com/valyala/fasthttp"
|
||||
)
|
||||
|
||||
// XrayTrafficJob collects and processes traffic statistics from Xray, updating the database and optionally informing external APIs.
|
||||
@@ -24,8 +22,7 @@ type XrayTrafficJob struct {
|
||||
outboundService outbound.OutboundService
|
||||
runMu sync.Mutex
|
||||
pending *xrayTrafficSample
|
||||
|
||||
externalInformInvalidLogged bool
|
||||
externalInform externalTrafficInform
|
||||
}
|
||||
|
||||
type xrayTrafficSample struct {
|
||||
@@ -73,15 +70,6 @@ func splitMovedClientTraffics(clientTraffics []*xray.ClientTraffic) ([]*xray.Cli
|
||||
return moved, emails, active
|
||||
}
|
||||
|
||||
const externalInformTimeout = 3 * time.Second
|
||||
|
||||
var externalInformClient = &fasthttp.Client{
|
||||
ReadTimeout: externalInformTimeout,
|
||||
WriteTimeout: externalInformTimeout,
|
||||
MaxIdleConnDuration: time.Minute,
|
||||
MaxConnsPerHost: 4,
|
||||
}
|
||||
|
||||
// NewXrayTrafficJob creates a new traffic collection job instance.
|
||||
func NewXrayTrafficJob() *XrayTrafficJob {
|
||||
return new(XrayTrafficJob)
|
||||
@@ -109,6 +97,7 @@ func (j *XrayTrafficJob) pollTraffic(collect func() ([]*xray.Traffic, []*xray.Cl
|
||||
// real-time updates over WebSocket using compact delta payloads — no REST
|
||||
// fallback, scales to 10k–20k+ clients per inbound.
|
||||
func (j *XrayTrafficJob) Run() {
|
||||
polledAt := time.Now()
|
||||
j.runMu.Lock()
|
||||
defer j.runMu.Unlock()
|
||||
if j.pending == nil && !j.xrayService.IsXrayRunning() {
|
||||
@@ -137,12 +126,9 @@ func (j *XrayTrafficJob) Run() {
|
||||
if needRestart {
|
||||
j.xrayService.SetToNeedRestartFrom(service.XrayOriginTrafficAccounting)
|
||||
}
|
||||
if enabled, err := j.settingService.GetExternalTrafficInformEnable(); err != nil {
|
||||
logger.Warning("get ExternalTrafficInformEnable failed:", err)
|
||||
} else if enabled {
|
||||
j.informTrafficToExternalAPI(traffics, clientTraffics)
|
||||
} else {
|
||||
j.externalInformInvalidLogged = false
|
||||
if batch, uri := j.externalInform.collect(polledAt, traffics, clientTraffics); batch != nil {
|
||||
// Off the accounting tick: a slow receiver must not delay the next poll.
|
||||
common.GoRecover("external-traffic-inform", func() { j.externalInform.deliver(batch, uri) })
|
||||
}
|
||||
|
||||
// Live online statistics require a running core. The committed sample does not.
|
||||
@@ -265,56 +251,3 @@ func (j *XrayTrafficJob) Run() {
|
||||
logger.Warning("get all outbounds for websocket failed:", err)
|
||||
}
|
||||
}
|
||||
|
||||
// externalInformDestination never echoes a malformed URI: url.Parse errors quote it,
|
||||
// credentials included. Destination checks name only the host, so those pass through.
|
||||
func externalInformDestination(raw string) (destination, skipReason string) {
|
||||
clean, err := service.SanitizeHTTPURL(raw)
|
||||
if err != nil {
|
||||
return "", "ExternalTrafficInformURI is not a valid http(s) URL"
|
||||
}
|
||||
if clean == "" {
|
||||
return "", "ExternalTrafficInformURI is empty"
|
||||
}
|
||||
if clean, err = service.SanitizePublicHTTPURL(clean, false); err != nil {
|
||||
return "", err.Error()
|
||||
}
|
||||
return clean, ""
|
||||
}
|
||||
|
||||
func (j *XrayTrafficJob) informTrafficToExternalAPI(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) {
|
||||
if len(inboundTraffics) == 0 && len(clientTraffics) == 0 {
|
||||
return
|
||||
}
|
||||
informURL, err := j.settingService.GetExternalTrafficInformURI()
|
||||
if err != nil {
|
||||
logger.Warning("get ExternalTrafficInformURI failed:", err)
|
||||
return
|
||||
}
|
||||
informURL, skipReason := externalInformDestination(informURL)
|
||||
if skipReason != "" {
|
||||
if !j.externalInformInvalidLogged {
|
||||
logger.Warning("Skipping external traffic notification: " + skipReason)
|
||||
j.externalInformInvalidLogged = true
|
||||
}
|
||||
return
|
||||
}
|
||||
j.externalInformInvalidLogged = false
|
||||
requestBody, err := json.Marshal(map[string]any{"clientTraffics": clientTraffics, "inboundTraffics": inboundTraffics})
|
||||
if err != nil {
|
||||
logger.Warning("parse client/inbound traffic failed:", err)
|
||||
return
|
||||
}
|
||||
request := fasthttp.AcquireRequest()
|
||||
defer fasthttp.ReleaseRequest(request)
|
||||
request.Header.SetMethod("POST")
|
||||
request.Header.SetContentType("application/json; charset=UTF-8")
|
||||
request.SetBody(requestBody)
|
||||
request.SetRequestURI(informURL)
|
||||
request.Header.SetConnectionClose()
|
||||
response := fasthttp.AcquireResponse()
|
||||
defer fasthttp.ReleaseResponse(response)
|
||||
if err := externalInformClient.DoTimeout(request, response, externalInformTimeout); err != nil {
|
||||
logger.Warning("POST ExternalTrafficInformURI failed:", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/valyala/fasthttp"
|
||||
stats "github.com/xtls/xray-core/app/stats/command"
|
||||
"google.golang.org/grpc"
|
||||
"gorm.io/gorm"
|
||||
@@ -90,9 +89,9 @@ func TestXrayTrafficRunFinishesCommittedSampleWhileStopped(t *testing.T) {
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
oldClient := externalInformClient
|
||||
externalInformClient = &fasthttp.Client{Dial: func(string) (net.Conn, error) {
|
||||
return net.DialTimeout("tcp", server.Listener.Addr().String(), time.Second)
|
||||
}}
|
||||
externalInformClient = &http.Client{Transport: &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return new(net.Dialer).DialContext(ctx, "tcp", server.Listener.Addr().String())
|
||||
}}}
|
||||
t.Cleanup(func() { externalInformClient = oldClient })
|
||||
|
||||
hub := websocket.NewHub()
|
||||
@@ -144,10 +143,17 @@ func TestXrayTrafficRunFinishesCommittedSampleWhileStopped(t *testing.T) {
|
||||
if !job.xrayService.IsNeedRestartAndSetFalse() {
|
||||
t.Error("restart was not queued after disabling a client with Xray stopped")
|
||||
}
|
||||
if len(informs) != 1 {
|
||||
t.Errorf("sent %d external reports, want 1", len(informs))
|
||||
} else if report := <-informs; len(report.Clients) != 1 || report.Clients[0].Email != client.Email || report.Clients[0].Up != 10 {
|
||||
t.Errorf("external report did not include the committed delta: %+v", report)
|
||||
// The report leaves the accounting tick on its own goroutine, and the idle second run adds none.
|
||||
select {
|
||||
case report := <-informs:
|
||||
if len(report.Clients) != 1 || report.Clients[0].Email != client.Email || report.Clients[0].Up != 10 {
|
||||
t.Errorf("external report did not include the committed delta: %+v", report)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Error("the committed delta was never reported")
|
||||
}
|
||||
if len(informs) != 0 {
|
||||
t.Errorf("sent %d extra external reports, want exactly 1", len(informs))
|
||||
}
|
||||
select {
|
||||
case data := <-listener.Send:
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
)
|
||||
|
||||
const (
|
||||
externalTrafficInformIntervalKey = "externalTrafficInformInterval"
|
||||
minExternalTrafficInformInterval = 5
|
||||
maxExternalTrafficInformInterval = 3600
|
||||
)
|
||||
|
||||
// ExternalTrafficInformConfig is one committed snapshot of the webhook settings.
|
||||
type ExternalTrafficInformConfig struct {
|
||||
Enabled bool
|
||||
URI string
|
||||
Interval time.Duration
|
||||
// SkipReason says why an enabled webhook cannot be sent; it never quotes the stored URI.
|
||||
SkipReason string
|
||||
}
|
||||
|
||||
func (s *SettingService) GetExternalTrafficInformConfig() (ExternalTrafficInformConfig, error) {
|
||||
keys := []string{"externalTrafficInformEnable", "externalTrafficInformURI", externalTrafficInformIntervalKey}
|
||||
var rows []model.Setting
|
||||
if err := database.GetDB().Where("key IN ?", keys).Find(&rows).Error; err != nil {
|
||||
return ExternalTrafficInformConfig{}, err
|
||||
}
|
||||
stored := make(map[string]string, len(rows))
|
||||
for _, row := range rows {
|
||||
stored[row.Key] = row.Value
|
||||
}
|
||||
effective := func(key string) string { return effectiveSettingValue(key, stored[key]) }
|
||||
if effective("externalTrafficInformEnable") != "true" {
|
||||
return ExternalTrafficInformConfig{}, nil
|
||||
}
|
||||
seconds, err := strconv.Atoi(effective(externalTrafficInformIntervalKey))
|
||||
if err != nil || !validExternalTrafficInformInterval(seconds) {
|
||||
seconds = minExternalTrafficInformInterval
|
||||
}
|
||||
cfg := ExternalTrafficInformConfig{Enabled: true, Interval: time.Duration(seconds) * time.Second}
|
||||
// A url.Parse error quotes the URI, credentials included, so it is not passed on.
|
||||
switch uri, err := SanitizeHTTPURL(stored["externalTrafficInformURI"]); {
|
||||
case err != nil:
|
||||
cfg.SkipReason = "ExternalTrafficInformURI is not a valid http(s) URL"
|
||||
case uri == "":
|
||||
cfg.SkipReason = "ExternalTrafficInformURI is empty"
|
||||
default:
|
||||
cfg.URI = uri
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func validExternalTrafficInformInterval(seconds int) bool {
|
||||
return seconds >= minExternalTrafficInformInterval && seconds <= maxExternalTrafficInformInterval
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
|
||||
)
|
||||
|
||||
func TestExternalTrafficInformIntervalSurvivesLegacySave(t *testing.T) {
|
||||
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
|
||||
service := new(SettingService)
|
||||
all, err := service.GetAllSetting()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if all.TrafficInformInterval != 5 {
|
||||
t.Fatalf("default interval = %d, want 5s", all.TrafficInformInterval)
|
||||
}
|
||||
all.ExternalTrafficInformEnable = true
|
||||
all.ExternalTrafficInformURI = "https://example.test/traffic"
|
||||
all.TrafficInformInterval = 60
|
||||
if err := service.UpdateAllSetting(all, SecretClears{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
all.TrafficInformInterval = 0
|
||||
if err := service.UpdateAllSetting(all, SecretClears{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
all.TrafficInformInterval = 3601
|
||||
if err := service.UpdateAllSetting(all, SecretClears{}); err == nil || err.Error() != "external traffic inform interval must be between 5 and 3600 seconds" {
|
||||
t.Fatalf("invalid interval save = %v", err)
|
||||
}
|
||||
cfg, err := service.GetExternalTrafficInformConfig()
|
||||
if err != nil || cfg.Interval != time.Minute || cfg.URI != "https://example.test/traffic" {
|
||||
t.Fatalf("effective configuration = %+v, error = %v", cfg, err)
|
||||
}
|
||||
}
|
||||
@@ -224,10 +224,13 @@ var defaultValueMap = map[string]string{
|
||||
"pia": "",
|
||||
"externalTrafficInformEnable": "false",
|
||||
"externalTrafficInformURI": "",
|
||||
"restartXrayOnClientDisable": "true",
|
||||
"xrayOutboundTestUrl": "https://www.google.com/generate_204",
|
||||
"panelOutbound": "",
|
||||
"devChannelEnable": "false",
|
||||
|
||||
externalTrafficInformIntervalKey: "5",
|
||||
|
||||
"restartXrayOnClientDisable": "true",
|
||||
"xrayOutboundTestUrl": "https://www.google.com/generate_204",
|
||||
"panelOutbound": "",
|
||||
"devChannelEnable": "false",
|
||||
|
||||
// LDAP defaults
|
||||
"ldapEnable": "false",
|
||||
@@ -1758,6 +1761,9 @@ type SecretClears struct {
|
||||
|
||||
func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting, clears SecretClears) error {
|
||||
preserveTrafficSelection := allSetting.NetworkTrafficMode == ""
|
||||
if seconds := allSetting.TrafficInformInterval; seconds != 0 && !validExternalTrafficInformInterval(seconds) {
|
||||
return errors.New("external traffic inform interval must be between 5 and 3600 seconds")
|
||||
}
|
||||
if err := validateNetworkTrafficSettings(allSetting); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1840,6 +1846,9 @@ func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting, clears
|
||||
if preserveTrafficSelection && (key == "networkTrafficMode" || key == "networkTrafficInterface") {
|
||||
continue
|
||||
}
|
||||
if key == externalTrafficInformIntervalKey && allSetting.TrafficInformInterval == 0 {
|
||||
continue
|
||||
}
|
||||
fieldV := v.FieldByName(field.Name)
|
||||
value := fmt.Sprint(fieldV.Interface())
|
||||
if st, ok := byKey[key]; ok {
|
||||
|
||||
@@ -1518,6 +1518,7 @@
|
||||
"externalTrafficInformEnableDesc": "إخطار واجهة API خارجية بكل تحديث لحركة المرور.",
|
||||
"externalTrafficInformURI": "مسار تنبيه الترافيك الخارجي",
|
||||
"externalTrafficInformURIDesc": "تحديثات الترافيك هتتبعت للمسار ده.",
|
||||
"externalTrafficInformInterval": "فاصل إرسال بيانات المرور الخارجية (بالثواني)",
|
||||
"restartXrayOnClientDisable": "إعادة تشغيل Xray بعد تعطيل العميل",
|
||||
"restartXrayOnClientDisableDesc": "عندما يتوقف تقديم الخدمة للعميل — بتعطيل تلقائي بسبب انتهاء الصلاحية أو حد حركة المرور، أو بتعطيل أو حذف يدوي — أعد تشغيل Xray لإنهاء اتصالاته النشطة.",
|
||||
"fragment": "تجزئة",
|
||||
|
||||
@@ -1643,6 +1643,7 @@
|
||||
"externalTrafficInformEnableDesc": "Inform external API on every traffic update.",
|
||||
"externalTrafficInformURI": "External Traffic Inform URI",
|
||||
"externalTrafficInformURIDesc": "Traffic updates are sent to this URI.",
|
||||
"externalTrafficInformInterval": "External traffic inform interval (seconds)",
|
||||
"restartXrayOnClientDisable": "Restart Xray After Client Disable",
|
||||
"restartXrayOnClientDisableDesc": "When a client stops being served - auto-disabled by expiration or traffic limit, or disabled or deleted by hand - restart Xray so its live connections end.",
|
||||
"fragment": "Fragmentation",
|
||||
|
||||
@@ -1518,6 +1518,7 @@
|
||||
"externalTrafficInformEnableDesc": "Informar a una API externa en cada actualización de tráfico.",
|
||||
"externalTrafficInformURI": "URI de información de tráfico externo",
|
||||
"externalTrafficInformURIDesc": "Las actualizaciones de tráfico se envían a este URI.",
|
||||
"externalTrafficInformInterval": "Intervalo de aviso de tráfico externo (segundos)",
|
||||
"restartXrayOnClientDisable": "Reiniciar Xray al desactivar un cliente",
|
||||
"restartXrayOnClientDisableDesc": "Cuando un cliente deja de atenderse — desactivado automáticamente por vencimiento o límite de tráfico, o desactivado o eliminado a mano — reiniciar Xray para que terminen sus conexiones activas.",
|
||||
"fragment": "Fragmentación",
|
||||
|
||||
@@ -1522,6 +1522,7 @@
|
||||
"externalTrafficInformEnableDesc": "به API خارجی در هر بهروزرسانی ترافیک اطلاع بده.",
|
||||
"externalTrafficInformURI": "لینک اطلاع رسانی خارجی مصرف ترافیک",
|
||||
"externalTrafficInformURIDesc": "ترافیک های مصرفی به این لینک هم ارسال می شود",
|
||||
"externalTrafficInformInterval": "فاصلهٔ ارسال گزارش ترافیک خارجی (ثانیه)",
|
||||
"restartXrayOnClientDisable": "ریاستارت Xray پس از غیرفعالسازی کلاینت",
|
||||
"restartXrayOnClientDisableDesc": "وقتی دیگر به کاربر سرویس داده نمیشود — غیرفعال شدن خودکار بهخاطر اتمام زمان یا محدودیت ترافیک، یا غیرفعال/حذف دستی — Xray ریاستارت شود تا اتصالهای فعالش بسته شوند.",
|
||||
"fragment": "فرگمنت",
|
||||
|
||||
@@ -1518,6 +1518,7 @@
|
||||
"externalTrafficInformEnableDesc": "Beritahu API eksternal setiap kali ada pembaruan trafik.",
|
||||
"externalTrafficInformURI": "Lalu Lintas Eksternal Menginformasikan URI",
|
||||
"externalTrafficInformURIDesc": "Pembaruan lalu lintas dikirim ke URI ini.",
|
||||
"externalTrafficInformInterval": "Interval pemberitahuan lalu lintas eksternal (detik)",
|
||||
"restartXrayOnClientDisable": "Nyalakan Ulang Xray Setelah Klien Dinonaktifkan",
|
||||
"restartXrayOnClientDisableDesc": "Saat klien berhenti dilayani — dinonaktifkan otomatis karena kedaluwarsa atau batas trafik, atau dinonaktifkan maupun dihapus secara manual — mulai ulang Xray agar koneksi aktifnya berakhir.",
|
||||
"fragment": "Fragmentasi",
|
||||
|
||||
@@ -1518,6 +1518,7 @@
|
||||
"externalTrafficInformEnableDesc": "トラフィック更新ごとに外部 API に通知。",
|
||||
"externalTrafficInformURI": "外部トラフィック通知 URI",
|
||||
"externalTrafficInformURIDesc": "トラフィックの更新ごとに外部 API に通知します。",
|
||||
"externalTrafficInformInterval": "外部トラフィック通知間隔(秒)",
|
||||
"restartXrayOnClientDisable": "クライアント無効化後に Xray を再起動",
|
||||
"restartXrayOnClientDisableDesc": "クライアントがサービス対象でなくなったとき(有効期限や通信量上限による自動無効化、または手動での無効化・削除)、接続を終わらせるため Xray を再起動します。",
|
||||
"fragment": "フラグメント",
|
||||
|
||||
@@ -1518,6 +1518,7 @@
|
||||
"externalTrafficInformEnableDesc": "Informar API externa a cada atualização de tráfego.",
|
||||
"externalTrafficInformURI": "URI de informação de tráfego externo",
|
||||
"externalTrafficInformURIDesc": "As atualizações de tráfego são enviadas para este URI.",
|
||||
"externalTrafficInformInterval": "Intervalo de notificação externa de tráfego (segundos)",
|
||||
"restartXrayOnClientDisable": "Reiniciar Xray Após Desativar um Cliente",
|
||||
"restartXrayOnClientDisableDesc": "Quando um cliente deixa de ser atendido — desativado automaticamente por expiração ou limite de tráfego, ou desativado ou excluído manualmente — reinicie o Xray para encerrar suas conexões ativas.",
|
||||
"fragment": "Fragmentação",
|
||||
|
||||
@@ -1518,6 +1518,7 @@
|
||||
"externalTrafficInformEnableDesc": "Уведомлять внешний API при каждом обновлении трафика.",
|
||||
"externalTrafficInformURI": "URI информации о внешнем трафике",
|
||||
"externalTrafficInformURIDesc": "Обновления трафика отправляются на этот URI",
|
||||
"externalTrafficInformInterval": "Интервал внешних уведомлений о трафике (секунды)",
|
||||
"restartXrayOnClientDisable": "Перезапускать Xray после отключения клиента",
|
||||
"restartXrayOnClientDisableDesc": "Когда клиент перестаёт обслуживаться — автоматически (по сроку или лимиту трафика) или вручную — перезапускать Xray, чтобы его активные соединения оборвались.",
|
||||
"fragment": "Фрагментация",
|
||||
|
||||
@@ -1643,6 +1643,7 @@
|
||||
"externalTrafficInformEnableDesc": "Pri každej aktualizácii spotreby informovať externé API.",
|
||||
"externalTrafficInformURI": "URI externého hlásenia spotreby",
|
||||
"externalTrafficInformURIDesc": "Na túto URI sa posielajú aktualizácie spotreby.",
|
||||
"externalTrafficInformInterval": "Interval externých upozornení o prevádzke (sekundy)",
|
||||
"restartXrayOnClientDisable": "Reštartovať Xray po vypnutí klienta",
|
||||
"restartXrayOnClientDisableDesc": "Keď klient stratí prístup pre skončenú platnosť alebo vyčerpaný limit, prípadne ho správca vypne či odstráni, reštartovať Xray a ukončiť jeho existujúce spojenia.",
|
||||
"fragment": "Fragmentácia",
|
||||
|
||||
@@ -1518,6 +1518,7 @@
|
||||
"externalTrafficInformEnableDesc": "Her trafik güncellemesinde harici API'yi bilgilendirir.",
|
||||
"externalTrafficInformURI": "Harici Trafik Bilgisi URI'si",
|
||||
"externalTrafficInformURIDesc": "Trafik güncellemeleri bu URI'ye gönderilir.",
|
||||
"externalTrafficInformInterval": "Harici trafik bildirim aralığı (saniye)",
|
||||
"restartXrayOnClientDisable": "İstemci Devre Dışı Bırakıldığında Xray'i Yeniden Başlat",
|
||||
"restartXrayOnClientDisableDesc": "Bir istemci artık sunulmadığında — süre dolumu veya trafik limiti nedeniyle otomatik, ya da elle devre dışı bırakıldığında veya silindiğinde — açık bağlantıları bitsin diye Xray'i yeniden başlatır.",
|
||||
"fragment": "Parçalama",
|
||||
|
||||
@@ -1518,6 +1518,7 @@
|
||||
"externalTrafficInformEnableDesc": "Повідомляти зовнішній API про кожне оновлення трафіку.",
|
||||
"externalTrafficInformURI": "Інформаційний URI зовнішнього трафіку",
|
||||
"externalTrafficInformURIDesc": "Оновлення трафіку надсилаються на цей URI.",
|
||||
"externalTrafficInformInterval": "Інтервал зовнішніх сповіщень про трафік (секунди)",
|
||||
"restartXrayOnClientDisable": "Перезапускати Xray після вимкнення клієнта",
|
||||
"restartXrayOnClientDisableDesc": "Коли клієнт перестає обслуговуватися — автоматично (через термін дії чи ліміт трафіку) або вручну — перезапускати Xray, щоб його активні з'єднання обірвалися.",
|
||||
"fragment": "Фрагментація",
|
||||
|
||||
@@ -1518,6 +1518,7 @@
|
||||
"externalTrafficInformEnableDesc": "Thông báo API ngoài mỗi khi cập nhật lưu lượng.",
|
||||
"externalTrafficInformURI": "URI thông báo lưu lượng truy cập bên ngoài",
|
||||
"externalTrafficInformURIDesc": "Cập nhật lưu lượng truy cập được gửi tới URI này.",
|
||||
"externalTrafficInformInterval": "Khoảng thời gian thông báo lưu lượng ra ngoài (giây)",
|
||||
"restartXrayOnClientDisable": "Khởi Động Lại Xray Sau Khi Vô Hiệu Hóa Máy Khách",
|
||||
"restartXrayOnClientDisableDesc": "Khi một máy khách không còn được phục vụ — bị vô hiệu hóa tự động do hết hạn hoặc giới hạn lưu lượng, hoặc bị vô hiệu hóa hay xóa thủ công — hãy khởi động lại Xray để các kết nối đang mở của nó kết thúc.",
|
||||
"fragment": "Sự phân mảnh",
|
||||
|
||||
@@ -1518,6 +1518,7 @@
|
||||
"externalTrafficInformEnableDesc": "每次流量更新时通知外部 API。",
|
||||
"externalTrafficInformURI": "外部流量通知 URI",
|
||||
"externalTrafficInformURIDesc": "流量更新将发送到此 URI",
|
||||
"externalTrafficInformInterval": "外部流量通知间隔(秒)",
|
||||
"restartXrayOnClientDisable": "客户端被禁用后重启 Xray",
|
||||
"restartXrayOnClientDisableDesc": "当客户端不再被服务时——因到期或流量超限被自动禁用,或被手动禁用、删除——重启 Xray 以断开其活动连接。",
|
||||
"fragment": "分片",
|
||||
|
||||
@@ -1518,6 +1518,7 @@
|
||||
"externalTrafficInformEnableDesc": "每次流量更新時通知外部 API。",
|
||||
"externalTrafficInformURI": "外部流量通知 URI",
|
||||
"externalTrafficInformURIDesc": "流量更新將會傳送到此 URI",
|
||||
"externalTrafficInformInterval": "外部流量通知間隔(秒)",
|
||||
"restartXrayOnClientDisable": "用戶被停用後重新啟動 Xray",
|
||||
"restartXrayOnClientDisableDesc": "當用戶不再被服務時——因到期或流量上限被自動停用,或被手動停用、刪除——重新啟動 Xray 以中斷其作用中的連線。",
|
||||
"fragment": "分片",
|
||||
|
||||
Reference in New Issue
Block a user