mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-03 16:04:50 +03:00
Merge remote-tracking branch 'origin/main' into codex/nodes-fleet-7342
This commit is contained in:
@@ -268,7 +268,8 @@ func (a *ClientController) create(c *gin.Context) {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
needRestart, err := a.clientService.Create(&a.inboundService, &payload)
|
||||
clientSvc := a.clientService.TrackNodeApplies()
|
||||
needRestart, err := clientSvc.CreateWithContext(c.Request.Context(), &a.inboundService, &payload)
|
||||
// Flagged before the error check: a partly-applied create leaves clients
|
||||
// committed on the inbounds that succeeded, and those still need the restart.
|
||||
if needRestart {
|
||||
@@ -280,10 +281,10 @@ func (a *ClientController) create(c *gin.Context) {
|
||||
notifyClientsChanged()
|
||||
}
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
jsonMsgObj(c, I18nWeb(c, "somethingWentWrong"), clientSvc.NodeApplyResponse(), err)
|
||||
return
|
||||
}
|
||||
jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), pendingNodeObj(a.inboundService.AnyNodePending(payload.InboundIds)), nil)
|
||||
jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), clientSvc.NodeApplyResponse(), nil)
|
||||
}
|
||||
|
||||
func (a *ClientController) update(c *gin.Context) {
|
||||
@@ -297,7 +298,8 @@ func (a *ClientController) update(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
inboundFilter := parseInboundIdsQuery(c.Query("inboundIds"))
|
||||
needRestart, err := a.clientService.UpdateByEmailJSON(&a.inboundService, email, body, inboundFilter...)
|
||||
clientSvc := a.clientService.TrackNodeApplies()
|
||||
needRestart, err := clientSvc.UpdateByEmailJSON(&a.inboundService, email, body, inboundFilter...)
|
||||
// Flagged before the error check: a partly-applied edit leaves the change
|
||||
// committed on the inbounds that succeeded, and those still need the restart.
|
||||
if needRestart {
|
||||
@@ -309,10 +311,10 @@ func (a *ClientController) update(c *gin.Context) {
|
||||
notifyClientsChanged()
|
||||
}
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
jsonMsgObj(c, I18nWeb(c, "somethingWentWrong"), clientSvc.NodeApplyResponse(), err)
|
||||
return
|
||||
}
|
||||
jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientUpdateSuccess"), pendingNodeObj(a.clientService.HasPendingNode(&a.inboundService, email)), nil)
|
||||
jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientUpdateSuccess"), clientSvc.NodeApplyResponse(), nil)
|
||||
}
|
||||
|
||||
func (a *ClientController) delete(c *gin.Context) {
|
||||
@@ -321,7 +323,8 @@ func (a *ClientController) delete(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
keepTraffic := c.Query("keepTraffic") == "1"
|
||||
needRestart, err := a.clientService.DeleteByEmail(&a.inboundService, email, keepTraffic)
|
||||
clientSvc := a.clientService.TrackNodeApplies()
|
||||
needRestart, err := clientSvc.DeleteByEmail(&a.inboundService, email, keepTraffic)
|
||||
// Flagged before the error check: a partly-applied delete already removed
|
||||
// the client from the inbounds that succeeded, and those need the restart.
|
||||
if needRestart {
|
||||
@@ -333,10 +336,10 @@ func (a *ClientController) delete(c *gin.Context) {
|
||||
notifyClientsChanged()
|
||||
}
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
jsonMsgObj(c, I18nWeb(c, "somethingWentWrong"), clientSvc.NodeApplyResponse(), err)
|
||||
return
|
||||
}
|
||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), nil)
|
||||
jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), clientSvc.NodeApplyResponse(), nil)
|
||||
}
|
||||
|
||||
type attachDetachBody struct {
|
||||
@@ -354,7 +357,8 @@ func (a *ClientController) attach(c *gin.Context) {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
needRestart, err := a.clientService.AttachByEmail(&a.inboundService, email, body.InboundIds)
|
||||
clientSvc := a.clientService.TrackNodeApplies()
|
||||
needRestart, err := clientSvc.AttachByEmail(&a.inboundService, email, body.InboundIds)
|
||||
if needRestart {
|
||||
a.xrayService.SetToNeedRestart()
|
||||
}
|
||||
@@ -364,10 +368,10 @@ func (a *ClientController) attach(c *gin.Context) {
|
||||
notifyClientsChanged()
|
||||
}
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
jsonMsgObj(c, I18nWeb(c, "somethingWentWrong"), clientSvc.NodeApplyResponse(), err)
|
||||
return
|
||||
}
|
||||
jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), pendingNodeObj(a.inboundService.AnyNodePending(body.InboundIds)), nil)
|
||||
jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), clientSvc.NodeApplyResponse(), nil)
|
||||
}
|
||||
|
||||
func (a *ClientController) setExternalLinks(c *gin.Context) {
|
||||
@@ -414,6 +418,7 @@ func (a *ClientController) bulkAdjust(c *gin.Context) {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
clientSvc := a.clientService.TrackNodeApplies()
|
||||
var result service.BulkAdjustResult
|
||||
var needRestart bool
|
||||
var err error
|
||||
@@ -424,12 +429,15 @@ func (a *ClientController) bulkAdjust(c *gin.Context) {
|
||||
}
|
||||
result, err = a.clientService.BulkAppendExternalLinks(req.Emails, req.ExternalLinks)
|
||||
} else {
|
||||
result, needRestart, err = a.clientService.BulkAdjust(&a.inboundService, req.Emails, req.AddDays, req.AddBytes, req.Flow, req.LimitHwid, req.AdTag)
|
||||
result, needRestart, err = clientSvc.BulkAdjust(&a.inboundService, req.Emails, req.AddDays, req.AddBytes, req.Flow, req.LimitHwid, req.AdTag)
|
||||
}
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
if report := clientSvc.NodeApplyResponse(); report != nil {
|
||||
result.ClientNodeApplyResponse = *report
|
||||
}
|
||||
jsonObj(c, result, nil)
|
||||
if needRestart {
|
||||
a.xrayService.SetToNeedRestart()
|
||||
@@ -462,11 +470,15 @@ func (a *ClientController) bulkAttach(c *gin.Context) {
|
||||
a.beginBulkAttach(c, req.InboundIds, *req.Selection)
|
||||
return
|
||||
}
|
||||
result, needRestart, err := a.clientService.BulkAttach(&a.inboundService, req.Emails, req.InboundIds)
|
||||
clientSvc := a.clientService.TrackNodeApplies()
|
||||
result, needRestart, err := clientSvc.BulkAttach(&a.inboundService, req.Emails, req.InboundIds)
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
if report := clientSvc.NodeApplyResponse(); report != nil {
|
||||
result.ClientNodeApplyResponse = *report
|
||||
}
|
||||
jsonObj(c, result, nil)
|
||||
if needRestart {
|
||||
a.xrayService.SetToNeedRestart()
|
||||
@@ -485,11 +497,15 @@ func (a *ClientController) bulkDetach(c *gin.Context) {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
result, needRestart, err := a.clientService.BulkDetach(&a.inboundService, req.Emails, req.InboundIds)
|
||||
clientSvc := a.clientService.TrackNodeApplies()
|
||||
result, needRestart, err := clientSvc.BulkDetach(&a.inboundService, req.Emails, req.InboundIds)
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
if report := clientSvc.NodeApplyResponse(); report != nil {
|
||||
result.ClientNodeApplyResponse = *report
|
||||
}
|
||||
jsonObj(c, result, nil)
|
||||
if needRestart {
|
||||
a.xrayService.SetToNeedRestart()
|
||||
@@ -503,11 +519,15 @@ func (a *ClientController) bulkDelete(c *gin.Context) {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
result, needRestart, err := a.clientService.BulkDelete(&a.inboundService, req.Emails, req.KeepTraffic)
|
||||
clientSvc := a.clientService.TrackNodeApplies()
|
||||
result, needRestart, err := clientSvc.BulkDelete(&a.inboundService, req.Emails, req.KeepTraffic)
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
if report := clientSvc.NodeApplyResponse(); report != nil {
|
||||
result.ClientNodeApplyResponse = *report
|
||||
}
|
||||
jsonObj(c, result, nil)
|
||||
if needRestart {
|
||||
a.xrayService.SetToNeedRestart()
|
||||
@@ -533,11 +553,15 @@ func (a *ClientController) bulkSetEnable(c *gin.Context, enable bool) {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
result, needRestart, err := a.clientService.BulkSetEnable(&a.inboundService, req.Emails, enable)
|
||||
clientSvc := a.clientService.TrackNodeApplies()
|
||||
result, needRestart, err := clientSvc.BulkSetEnable(&a.inboundService, req.Emails, enable)
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
if report := clientSvc.NodeApplyResponse(); report != nil {
|
||||
result.ClientNodeApplyResponse = *report
|
||||
}
|
||||
jsonObj(c, result, nil)
|
||||
if needRestart {
|
||||
a.xrayService.SetToNeedRestart()
|
||||
@@ -551,11 +575,15 @@ func (a *ClientController) bulkCreate(c *gin.Context) {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
result, needRestart, err := a.clientService.BulkCreate(&a.inboundService, payloads)
|
||||
clientSvc := a.clientService.TrackNodeApplies()
|
||||
result, needRestart, err := clientSvc.BulkCreate(&a.inboundService, payloads)
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
if report := clientSvc.NodeApplyResponse(); report != nil {
|
||||
result.ClientNodeApplyResponse = *report
|
||||
}
|
||||
jsonObj(c, result, nil)
|
||||
if needRestart {
|
||||
a.xrayService.SetToNeedRestart()
|
||||
@@ -811,7 +839,8 @@ func (a *ClientController) detach(c *gin.Context) {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
return
|
||||
}
|
||||
needRestart, err := a.clientService.DetachByEmailMany(&a.inboundService, email, body.InboundIds)
|
||||
clientSvc := a.clientService.TrackNodeApplies()
|
||||
needRestart, err := clientSvc.DetachByEmailMany(&a.inboundService, email, body.InboundIds)
|
||||
// Flagged before the error check: a partly-applied detach already removed
|
||||
// the client from the inbounds that succeeded, and those need the restart.
|
||||
if needRestart {
|
||||
@@ -823,10 +852,10 @@ func (a *ClientController) detach(c *gin.Context) {
|
||||
notifyClientsChanged()
|
||||
}
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
||||
jsonMsgObj(c, I18nWeb(c, "somethingWentWrong"), clientSvc.NodeApplyResponse(), err)
|
||||
return
|
||||
}
|
||||
jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), pendingNodeObj(a.inboundService.AnyNodePending(body.InboundIds)), nil)
|
||||
jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), clientSvc.NodeApplyResponse(), nil)
|
||||
}
|
||||
|
||||
type bulkResetRequest struct {
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"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/web/runtime"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
||||
)
|
||||
|
||||
func TestClientUpdateReportsTimedOutOnlineNodeAndKeepsLocalSave(t *testing.T) {
|
||||
dbtest.InitDB(t, filepath.Join(t.TempDir(), "master.db"))
|
||||
service.StartTrafficWriter()
|
||||
t.Cleanup(service.StopTrafficWriter)
|
||||
runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}}))
|
||||
t.Cleanup(func() { runtime.SetManager(nil) })
|
||||
|
||||
const email = "partial-node@example.test"
|
||||
db := database.GetDB()
|
||||
var nodes []model.Node
|
||||
var inbounds []model.Inbound
|
||||
const (
|
||||
timeout = iota
|
||||
downstream
|
||||
recovered
|
||||
)
|
||||
var slowMode atomic.Int32
|
||||
slowStarted := make(chan struct{}, 1)
|
||||
healthyApplied := make(chan struct{}, 1)
|
||||
for index, slow := range []bool{false, true} {
|
||||
tag := fmt.Sprintf("in-%d", 15110+index)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if strings.HasSuffix(r.URL.Path, "/inbounds/list") {
|
||||
fmt.Fprintf(w, "{\"success\":true,\"obj\":[{\"id\":1,\"tag\":%q}]}", tag)
|
||||
} else if strings.Contains(r.URL.Path, "/clients/update/") {
|
||||
if slow {
|
||||
switch slowMode.Load() {
|
||||
case timeout:
|
||||
_, _ = io.Copy(io.Discard, r.Body)
|
||||
slowStarted <- struct{}{}
|
||||
<-r.Context().Done()
|
||||
return
|
||||
case downstream:
|
||||
fmt.Fprint(w, "{\"success\":true,\"obj\":{\"nodePending\":true}}")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
select {
|
||||
case healthyApplied <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
fmt.Fprint(w, "{\"success\":true}")
|
||||
} else {
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
parsed, err := url.Parse(srv.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
port, err := strconv.Atoi(parsed.Port())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
node := model.Node{
|
||||
Name: fmt.Sprintf("slow=%t", slow), Address: parsed.Hostname(), Port: port,
|
||||
Scheme: "http", BasePath: "/", ApiToken: "fixture", TlsVerifyMode: "verify",
|
||||
AllowPrivateAddress: true, Enable: true, Status: "online",
|
||||
}
|
||||
if err := db.Create(&node).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inbound := model.Inbound{
|
||||
UserId: 1, Enable: true, Tag: tag, Port: 15110 + index,
|
||||
Protocol: model.VLESS, Settings: "{\"clients\":[],\"decryption\":\"none\"}", StreamSettings: "{\"network\":\"tcp\",\"security\":\"none\"}",
|
||||
}
|
||||
if err := db.Create(&inbound).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nodes = append(nodes, node)
|
||||
inbounds = append(inbounds, inbound)
|
||||
}
|
||||
clientSvc, inboundSvc := &service.ClientService{}, &service.InboundService{}
|
||||
if _, err := clientSvc.Create(inboundSvc, &service.ClientCreatePayload{
|
||||
Client: model.Client{Email: email, ID: "11111111-2222-4333-8444-555555555555", Enable: true},
|
||||
InboundIds: []int{inbounds[0].Id, inbounds[1].Id},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, inbound := range inbounds {
|
||||
if err := db.Model(&model.Inbound{}).Where("id = ?", inbound.Id).Update("node_id", nodes[i].Id).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
NewClientController(router.Group("/panel/api/clients"))
|
||||
type applyEnvelope struct {
|
||||
Success bool
|
||||
Obj service.ClientNodeApplyResponse
|
||||
}
|
||||
request := func(comment string) *httptest.ResponseRecorder {
|
||||
body := fmt.Sprintf("{\"comment\":%q}", comment)
|
||||
req := httptest.NewRequest(http.MethodPost, "/panel/api/clients/update/"+email, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, req)
|
||||
return response
|
||||
}
|
||||
decode := func(response *httptest.ResponseRecorder) applyEnvelope {
|
||||
t.Helper()
|
||||
var msg applyEnvelope
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !msg.Success || len(msg.Obj.NodeResults) != 2 {
|
||||
t.Fatalf("expected local success and both node results, got %s", response.Body.String())
|
||||
}
|
||||
return msg
|
||||
}
|
||||
started := time.Now()
|
||||
done := make(chan *httptest.ResponseRecorder, 1)
|
||||
finished := make(chan struct{})
|
||||
go func() {
|
||||
defer close(finished)
|
||||
done <- request("saved locally")
|
||||
}()
|
||||
t.Cleanup(func() { <-finished })
|
||||
wait := func(ch <-chan struct{}) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-ch:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("expected RPC did not start before the slow node's deadline")
|
||||
}
|
||||
}
|
||||
wait(slowStarted)
|
||||
wait(healthyApplied)
|
||||
writerStarted := time.Now()
|
||||
if _, _, err := inboundSvc.AddTraffic(nil, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("fixture writer barrier while RPC in flight: %s", time.Since(writerStarted))
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatal("unrelated writer work was held behind the slow RPC")
|
||||
default:
|
||||
}
|
||||
msg := decode(<-done)
|
||||
t.Logf("fixture timed-out request: %s", time.Since(started))
|
||||
if got := msg.Obj.NodeResults[0]; got.NodeID != nodes[0].Id || got.Status != "applied" {
|
||||
t.Fatalf("healthy node outcome: %+v", got)
|
||||
}
|
||||
if got := msg.Obj.NodeResults[1]; !msg.Obj.NodePending || got.NodeID != nodes[1].Id || got.Status != "pending" || got.Reason != "timeout" {
|
||||
t.Fatalf("slow node outcome: %+v", got)
|
||||
}
|
||||
if stored, err := clientSvc.GetRecordByEmail(nil, email); err != nil || stored.Comment != "saved locally" {
|
||||
t.Fatalf("local edit not persisted: record=%+v error=%v", stored, err)
|
||||
}
|
||||
if err := db.First(&nodes[1], nodes[1].Id).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !nodes[1].ConfigDirty || nodes[1].Status != "online" {
|
||||
t.Fatalf("timed-out online node lost its durable reconcile flag: %+v", nodes[1])
|
||||
}
|
||||
|
||||
slowMode.Store(downstream)
|
||||
msg = decode(request("downstream pending"))
|
||||
if got := msg.Obj.NodeResults[1]; !msg.Obj.NodePending || got.Status != "pending" || got.Reason != "downstream_pending" {
|
||||
t.Fatalf("forwarded pending result was lost: %+v", msg.Obj)
|
||||
}
|
||||
|
||||
slowMode.Store(recovered)
|
||||
started = time.Now()
|
||||
msg = decode(request("both acknowledged"))
|
||||
t.Logf("fixture healthy request: %s", time.Since(started))
|
||||
if got := msg.Obj.NodeResults[1]; msg.Obj.NodePending || got.Status != "applied" || got.Reason != "" {
|
||||
t.Fatalf("recovered node outcome: %+v", msg.Obj)
|
||||
}
|
||||
}
|
||||
@@ -39,18 +39,22 @@ func NewInboundController(g *gin.RouterGroup) *InboundController {
|
||||
// Mirrors the same heuristic used by the periodic traffic job.
|
||||
const broadcastInboundsUpdateClientLimit = 5000
|
||||
|
||||
// broadcastInboundsUpdate fetches and broadcasts the inbound list for userId.
|
||||
// At scale (10k+ clients) the marshaled JSON exceeds the WS payload ceiling,
|
||||
// so we send an invalidate signal instead — frontend re-fetches via REST.
|
||||
// Skipped entirely when no WebSocket clients are connected.
|
||||
// broadcastInboundsUpdate sends either a small snapshot or an invalidate.
|
||||
// Skip all snapshot work when no WebSocket clients are connected.
|
||||
func (a *InboundController) broadcastInboundsUpdate(userId int) {
|
||||
if !websocket.HasClients() {
|
||||
return
|
||||
}
|
||||
overLimit, err := a.inboundService.InboundClientStatsOverLimit(userId, broadcastInboundsUpdateClientLimit)
|
||||
if err != nil || overLimit {
|
||||
websocket.BroadcastInvalidate(websocket.MessageTypeInbounds)
|
||||
return
|
||||
}
|
||||
inbounds, err := a.inboundService.GetInbounds(userId)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// Stats can grow between the probe and the snapshot read.
|
||||
totalClients := 0
|
||||
for _, ib := range inbounds {
|
||||
totalClients += len(ib.ClientStats)
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/robfig/cron/v3"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"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/web/entity"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/global"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/session"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/websocket"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
type inboundBroadcastServer struct{ hub *websocket.Hub }
|
||||
|
||||
func (s inboundBroadcastServer) GetWSHub() any { return s.hub }
|
||||
func (inboundBroadcastServer) GetCtx() context.Context { return context.Background() }
|
||||
func (inboundBroadcastServer) GetCron() *cron.Cron { return nil }
|
||||
|
||||
func TestInboundMutationSkipsSnapshotReadsAboveWebSocketCutoff(t *testing.T) {
|
||||
dbtest.InitDB(t, filepath.Join(t.TempDir(), "panel.db"))
|
||||
db := database.GetDB()
|
||||
seed := func(userID, port, count int) model.Inbound {
|
||||
t.Helper()
|
||||
row := model.Inbound{UserId: userID, Port: port, Tag: fmt.Sprintf("in-%d", port), Protocol: model.VLESS, Settings: `{"clients":[],"decryption":"none"}`}
|
||||
if err := db.Create(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stats := make([]xray.ClientTraffic, count)
|
||||
for i := range stats {
|
||||
stats[i] = xray.ClientTraffic{InboundId: row.Id, Email: fmt.Sprintf("client-%d-%d", port, i)}
|
||||
}
|
||||
if count > 0 {
|
||||
if err := db.CreateInBatches(&stats, 100).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return row
|
||||
}
|
||||
const limit = broadcastInboundsUpdateClientLimit
|
||||
owned := seed(1, 29100, limit-1)
|
||||
sibling := seed(1, 29101, 0)
|
||||
seed(2, 29102, limit+1)
|
||||
attach := func(inbound model.Inbound, statsIndex int) {
|
||||
t.Helper()
|
||||
row := model.ClientRecord{Email: fmt.Sprintf("client-%d-%d", owned.Port, statsIndex)}
|
||||
if err := db.Create(&row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
link := model.ClientInbound{ClientId: row.Id, InboundId: inbound.Id}
|
||||
if err := db.Create(&link).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
attach(sibling, 0)
|
||||
attach(owned, 1)
|
||||
|
||||
snapshotReads, probes := 0, 0
|
||||
if err := db.Callback().Query().After("gorm:query").Register("test:inbound_snapshot", func(tx *gorm.DB) {
|
||||
sql := tx.Statement.SQL.String()
|
||||
if _, ok := tx.Statement.Dest.(*[]*model.Inbound); ok &&
|
||||
strings.Contains(sql, "WHERE user_id =") && strings.HasSuffix(sql, "ORDER BY id ASC") {
|
||||
snapshotReads++
|
||||
}
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Callback().Row().After("gorm:row").Register("test:inbound_stats_probe", func(tx *gorm.DB) {
|
||||
if strings.Contains(tx.Statement.SQL.String(), "AS candidate_stats") {
|
||||
probes++
|
||||
}
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
router := gin.New()
|
||||
group := router.Group("/panel/api/inbounds", func(c *gin.Context) {
|
||||
session.SetAPIAuthUser(c, &model.User{Id: 1})
|
||||
})
|
||||
NewInboundController(group)
|
||||
previous := global.GetWebServer()
|
||||
t.Cleanup(func() { global.SetWebServer(previous) })
|
||||
|
||||
for i, tc := range []struct {
|
||||
name string
|
||||
ws bool
|
||||
wantType websocket.MessageType
|
||||
reads int
|
||||
prepare func()
|
||||
}{
|
||||
{name: "no subscribers"},
|
||||
{name: "at cutoff with shared traffic and unrelated user", ws: true, wantType: websocket.MessageTypeInbounds, reads: 1},
|
||||
{name: "above cutoff from sibling counter", ws: true, wantType: websocket.MessageTypeInvalidate, prepare: func() { attach(sibling, 2) }},
|
||||
{name: "above cutoff from direct traffic", ws: true, wantType: websocket.MessageTypeInvalidate, prepare: func() { seed(1, 29110, 2) }},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var subscriber *websocket.Client
|
||||
if tc.ws {
|
||||
hub := websocket.NewHub()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
hub.Run()
|
||||
}()
|
||||
t.Cleanup(func() { hub.Stop(); <-done })
|
||||
global.SetWebServer(inboundBroadcastServer{hub})
|
||||
subscriber = websocket.NewClient("test")
|
||||
hub.Register(subscriber)
|
||||
for deadline := time.Now().Add(2 * time.Second); hub.GetClientCount() == 0; {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("subscriber did not register")
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
} else {
|
||||
global.SetWebServer(nil)
|
||||
}
|
||||
if tc.prepare != nil {
|
||||
tc.prepare()
|
||||
}
|
||||
snapshotReads, probes = 0, 0
|
||||
port := 29103 + i
|
||||
body := fmt.Sprintf(`{"protocol":"vless","enable":false,"remark":"created","port":%d,"settings":"{\"clients\":[],\"decryption\":\"none\"}","streamSettings":"{\"network\":\"tcp\",\"security\":\"none\"}"}`, port)
|
||||
req := httptest.NewRequest(http.MethodPost, "/panel/api/inbounds/add", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
var response entity.Msg
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil || !response.Success {
|
||||
t.Fatalf("add failed: %s (%v)", rec.Body, err)
|
||||
}
|
||||
if snapshotReads != tc.reads {
|
||||
t.Errorf("full inbound snapshot reads = %d, want %d", snapshotReads, tc.reads)
|
||||
}
|
||||
wantProbes := 0
|
||||
if tc.ws {
|
||||
wantProbes = 1
|
||||
}
|
||||
if probes != wantProbes {
|
||||
t.Errorf("snapshot size probes = %d, want %d", probes, wantProbes)
|
||||
}
|
||||
if subscriber == nil {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case data := <-subscriber.Send:
|
||||
var event struct {
|
||||
Type websocket.MessageType
|
||||
Payload json.RawMessage
|
||||
}
|
||||
if err := json.Unmarshal(data, &event); err != nil || event.Type != tc.wantType {
|
||||
t.Fatalf("unexpected WebSocket type %q: %v, want %q", event.Type, err, tc.wantType)
|
||||
}
|
||||
if tc.wantType == websocket.MessageTypeInbounds {
|
||||
var rows []model.Inbound
|
||||
if err := json.Unmarshal(event.Payload, &rows); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
total, created := 0, false
|
||||
for _, row := range rows {
|
||||
if row.Port == 29102 {
|
||||
t.Fatal("snapshot contains another user's inbound")
|
||||
}
|
||||
total += len(row.ClientStats)
|
||||
created = created || row.Port == port
|
||||
}
|
||||
if !created || total != limit {
|
||||
t.Fatalf("snapshot missing updated state: created=%t client stats=%d", created, total)
|
||||
}
|
||||
} else if string(event.Payload) != `{"type":"inbounds"}` {
|
||||
t.Fatalf("unexpected invalidation payload %s", event.Payload)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("mutation did not publish an inbound event")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -241,7 +241,7 @@ func (a *SettingController) restartPanel(c *gin.Context) {
|
||||
}
|
||||
answer.NextPort, _ = a.settingService.GetListenPort()
|
||||
err := a.panelService.RestartPanel(time.Second * 3)
|
||||
jsonMsgObj(c, I18nWeb(c, "pages.settings.restartPanelSuccess"), answer, err)
|
||||
jsonMsgObj(c, I18nWeb(c, "pages.settings.restartPanelAccepted"), answer, err)
|
||||
}
|
||||
|
||||
// getDefaultXrayConfig retrieves the default Xray configuration.
|
||||
|
||||
@@ -102,16 +102,6 @@ func jsonMsgObj(c *gin.Context, msg string, obj any, err error) {
|
||||
c.JSON(http.StatusOK, m)
|
||||
}
|
||||
|
||||
// pendingNodeObj returns a response object flagging that the save committed
|
||||
// locally but a backing node was offline/disabled, so the change will be
|
||||
// mirrored to the node once it reconnects. Returns nil when nothing is pending.
|
||||
func pendingNodeObj(pending bool) any {
|
||||
if pending {
|
||||
return gin.H{"nodePending": true}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// pureJsonMsg sends a pure JSON message response with custom status code.
|
||||
func pureJsonMsg(c *gin.Context, statusCode int, success bool, msg string) {
|
||||
c.JSON(statusCode, entity.Msg{
|
||||
|
||||
Reference in New Issue
Block a user