mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-28 21:44:50 +03:00
fix(nodes): roll back failed client reconciliation (#7229)
Node sync could commit a rejected inbound's client changes. The cross-inbound TUIC UUID check runs after the shared client record, the inbound links and the flow overrides are written, and the merge used to log the error and commit anyway: a shared client could keep another client's UUID, half-updated links and the node's settings for that inbound. Each inbound's adopted configuration and client sync now run in a savepoint. A refusal rolls that inbound back and the merge goes on, so traffic and the inbounds that synced still commit; the refused inbound stays out of the orphan sweep and a later valid snapshot reconciles it. A node inbound the master sees for the first time is stored with the settings the node reported and stamped as already delivered. Without the row the next reconcile deletes the inbound on the node; with other settings it overwrites the node's clients; and pushing the node's own inconsistent blob back is refused there on every tick, which keeps the node dirty and suspends adoption for all of its inbounds. Run on a real master and node with clients connected: the refused inbound kept serving through a reconcile, the node stayed clean, and the master adopted it once the node's report was consistent. Closes #7219
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
@@ -107,6 +108,24 @@ func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model.
|
||||
return s.syncInboundClients(tx, inboundId, clients, nil, true)
|
||||
}
|
||||
|
||||
// withClientSyncSavepoint lets a caller continue only after a failed sync is undone.
|
||||
// Savepoint errors are fatal to the outer transaction, including release failures.
|
||||
func withClientSyncSavepoint(tx *gorm.DB, sync func() error) (rejected, fatal error) {
|
||||
if err := tx.Exec("SAVEPOINT xui_client_sync").Error; err != nil {
|
||||
return nil, fmt.Errorf("savepoint for client sync: %w", err)
|
||||
}
|
||||
rejected = sync()
|
||||
if rejected != nil {
|
||||
if err := tx.Exec("ROLLBACK TO SAVEPOINT xui_client_sync").Error; err != nil {
|
||||
return nil, errors.Join(rejected, fmt.Errorf("roll back client sync: %w", err))
|
||||
}
|
||||
}
|
||||
if err := tx.Exec("RELEASE SAVEPOINT xui_client_sync").Error; err != nil {
|
||||
return nil, errors.Join(rejected, fmt.Errorf("release client sync savepoint: %w", err))
|
||||
}
|
||||
return rejected, nil
|
||||
}
|
||||
|
||||
// ApplyInboundClientDelta persists only the clients an edit actually changed
|
||||
// plus the emails it detached, leaving every other link on the inbound alone —
|
||||
// the whole point being that a one-client edit must not rewrite the inbound's
|
||||
@@ -253,9 +272,6 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [
|
||||
if err := tx.CreateInBatches(toCreate, 200).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// Whichever API re-created the client, a delete tombstone left standing makes
|
||||
// the next node merge prune it and ReapSyncOrphans delete it.
|
||||
liftTombstonesOnCommit(tx, toCreate)
|
||||
disabledIDs := make([]int, 0)
|
||||
for i, rec := range toCreate {
|
||||
idByEmail[rec.Email] = rec.Id
|
||||
@@ -328,6 +344,8 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [
|
||||
}
|
||||
}
|
||||
|
||||
// A failed validation can roll back the row while the outer transaction commits.
|
||||
liftTombstonesOnCommit(tx, toCreate)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -457,9 +457,8 @@ func (s *InboundService) GetNodeInboundTrafficTotals() (map[string][2]int64, err
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func adoptedWireChanged(c, snapIb *model.Inbound, adoptedSettings string) bool {
|
||||
return c.Settings != adoptedSettings ||
|
||||
c.Enable != snapIb.Enable ||
|
||||
func adoptedWireConfigChanged(c, snapIb *model.Inbound) bool {
|
||||
return c.Enable != snapIb.Enable ||
|
||||
c.Remark != snapIb.Remark ||
|
||||
c.SubSortIndex != normalizeSubSortIndex(snapIb.SubSortIndex) ||
|
||||
c.Listen != snapIb.Listen ||
|
||||
@@ -474,6 +473,31 @@ func adoptedWireChanged(c, snapIb *model.Inbound, adoptedSettings string) bool {
|
||||
(snapIb.PreserveClientTraffic != nil && c.PreservesClientTraffic() != snapIb.PreservesClientTraffic())
|
||||
}
|
||||
|
||||
func nodeInboundConfigUpdates(c, snapIb *model.Inbound) map[string]any {
|
||||
if !adoptedWireConfigChanged(c, snapIb) && c.LastTrafficResetTime == snapIb.LastTrafficResetTime {
|
||||
return nil
|
||||
}
|
||||
updates := map[string]any{
|
||||
"enable": snapIb.Enable,
|
||||
"remark": snapIb.Remark,
|
||||
"sub_sort_index": normalizeSubSortIndex(snapIb.SubSortIndex),
|
||||
"listen": snapIb.Listen,
|
||||
"port": snapIb.Port,
|
||||
"protocol": snapIb.Protocol,
|
||||
"total": snapIb.Total,
|
||||
"expiry_time": snapIb.ExpiryTime,
|
||||
"stream_settings": snapIb.StreamSettings,
|
||||
"sniffing": snapIb.Sniffing,
|
||||
"traffic_reset": snapIb.TrafficReset,
|
||||
"traffic_reset_day": normalizeTrafficResetDay(snapIb.TrafficResetDay),
|
||||
"last_traffic_reset_time": snapIb.LastTrafficResetTime,
|
||||
}
|
||||
if snapIb.PreserveClientTraffic != nil && c.PreservesClientTraffic() != snapIb.PreservesClientTraffic() {
|
||||
updates["preserve_client_traffic"] = snapIb.PreservesClientTraffic()
|
||||
}
|
||||
return updates
|
||||
}
|
||||
|
||||
// adoptedWireInbound is the central inbound as it reads after adopting the
|
||||
// node-reported wire fields — the payload the reconcile fingerprint must track.
|
||||
func adoptedWireInbound(c, snapIb *model.Inbound, adoptedSettings string) *model.Inbound {
|
||||
@@ -731,16 +755,16 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
|
||||
}
|
||||
|
||||
structuralChange := false
|
||||
adoptedSettingsChanged := false
|
||||
lifecycleLifted := false
|
||||
var sweptTags []string
|
||||
|
||||
var adoptedInbounds []*model.Inbound
|
||||
type pendingAdopt struct {
|
||||
central *model.Inbound
|
||||
snapIb *model.Inbound
|
||||
wireSettings string
|
||||
config map[string]any
|
||||
}
|
||||
var pendingAdopts []pendingAdopt
|
||||
pendingAdopts := make(map[int]pendingAdopt)
|
||||
degradedInbounds := map[int]string{}
|
||||
|
||||
newInboundIDs := make(map[int]struct{})
|
||||
@@ -891,6 +915,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
|
||||
}
|
||||
}
|
||||
newInboundIDs[newIb.Id] = struct{}{}
|
||||
pendingAdopts[newIb.Id] = pendingAdopt{wireSettings: snapIb.Settings}
|
||||
mergedCentral[newIb.Id] = struct{}{}
|
||||
structuralChange = true
|
||||
continue
|
||||
@@ -912,30 +937,9 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
|
||||
if !dirty && snapshotDropsEveryHubClient(tx, c.Id, adoptedSettings) {
|
||||
degradedInbounds[c.Id] = c.Tag
|
||||
} else if !dirty {
|
||||
// Defer lifecycle lift until after client_traffics absorbs this tick's
|
||||
// deltas so quota stale-disable matches SQL (#6228).
|
||||
pendingAdopts = append(pendingAdopts, pendingAdopt{
|
||||
central: c, snapIb: snapIb, wireSettings: adoptedSettings,
|
||||
})
|
||||
updates["enable"] = snapIb.Enable
|
||||
updates["remark"] = snapIb.Remark
|
||||
updates["sub_sort_index"] = normalizeSubSortIndex(snapIb.SubSortIndex)
|
||||
updates["listen"] = snapIb.Listen
|
||||
updates["port"] = snapIb.Port
|
||||
updates["protocol"] = snapIb.Protocol
|
||||
updates["total"] = snapIb.Total
|
||||
updates["expiry_time"] = snapIb.ExpiryTime
|
||||
updates["stream_settings"] = snapIb.StreamSettings
|
||||
updates["sniffing"] = snapIb.Sniffing
|
||||
updates["traffic_reset"] = snapIb.TrafficReset
|
||||
updates["traffic_reset_day"] = normalizeTrafficResetDay(snapIb.TrafficResetDay)
|
||||
if snapIb.PreserveClientTraffic != nil && c.PreservesClientTraffic() != snapIb.PreservesClientTraffic() {
|
||||
updates["preserve_client_traffic"] = snapIb.PreservesClientTraffic()
|
||||
structuralChange = true
|
||||
}
|
||||
updates["last_traffic_reset_time"] = snapIb.LastTrafficResetTime
|
||||
pendingAdopts[c.Id] = pendingAdopt{wireSettings: adoptedSettings, config: nodeInboundConfigUpdates(c, snapIb)}
|
||||
}
|
||||
if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
|
||||
if (snapIb.Up != c.Up || snapIb.Down != c.Down) && (!inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down)) {
|
||||
updates["up"] = snapIb.Up
|
||||
updates["down"] = snapIb.Down
|
||||
}
|
||||
@@ -946,15 +950,6 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
|
||||
updates["origin_node_guid"] = og
|
||||
}
|
||||
|
||||
if !dirty && (c.Remark != snapIb.Remark ||
|
||||
c.Listen != snapIb.Listen ||
|
||||
c.Port != snapIb.Port ||
|
||||
c.Total != snapIb.Total ||
|
||||
c.ExpiryTime != snapIb.ExpiryTime ||
|
||||
c.Enable != snapIb.Enable) {
|
||||
structuralChange = true
|
||||
}
|
||||
|
||||
if len(updates) > 0 {
|
||||
if err := tx.Model(model.Inbound{}).
|
||||
Where("id = ?", c.Id).
|
||||
@@ -1320,30 +1315,6 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
|
||||
}
|
||||
var perInboundOld []oldSet
|
||||
syncFailedInbounds := map[int]struct{}{}
|
||||
for _, p := range pendingAdopts {
|
||||
lifted, liftChanged := liftClientLifecycleInSettings(p.wireSettings, statByEmail)
|
||||
adoptedSettings := p.wireSettings
|
||||
if liftChanged {
|
||||
adoptedSettings = lifted
|
||||
lifecycleLifted = true
|
||||
}
|
||||
if p.central.Settings != adoptedSettings {
|
||||
if err := tx.Model(model.Inbound{}).
|
||||
Where("id = ?", p.central.Id).
|
||||
Update("settings", adoptedSettings).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
structuralChange = true
|
||||
// Adopted wire settings feed subscription bodies; drop snapshots
|
||||
// so the adopted rows are served this tick, not after the TTL.
|
||||
InvalidateSubData()
|
||||
}
|
||||
// The fingerprint stamps the un-lifted wire blob on purpose: a lift must leave reconcile
|
||||
// a mismatch to re-push against. A refused claim must not: the push would delete it on the node.
|
||||
if liftChanged || adoptedWireChanged(p.central, p.snapIb, p.wireSettings) {
|
||||
adoptedInbounds = append(adoptedInbounds, adoptedWireInbound(p.central, p.snapIb, p.wireSettings))
|
||||
}
|
||||
}
|
||||
for _, snapIb := range snap.Inbounds {
|
||||
if snapIb == nil {
|
||||
continue
|
||||
@@ -1372,6 +1343,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
|
||||
clients, gcErr := s.GetClients(snapIb)
|
||||
if gcErr != nil {
|
||||
logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr)
|
||||
syncFailedInbounds[c.Id] = struct{}{}
|
||||
continue
|
||||
}
|
||||
csByEmail := make(map[string]xray.ClientTraffic, len(snapIb.ClientStats))
|
||||
@@ -1426,9 +1398,52 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
|
||||
filtered[i].Comment = cmt
|
||||
}
|
||||
}
|
||||
if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
|
||||
logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, err)
|
||||
p := pendingAdopts[c.Id]
|
||||
_, isNew := newInboundIDs[c.Id]
|
||||
adoptedSettings := p.wireSettings
|
||||
liftChanged := false
|
||||
if !isNew {
|
||||
// Use the traffic deltas just applied to this transaction (#6228).
|
||||
if lifted, changed := liftClientLifecycleInSettings(p.wireSettings, statByEmail); changed {
|
||||
adoptedSettings, liftChanged = lifted, true
|
||||
}
|
||||
}
|
||||
updates := p.config
|
||||
settingsChanged := c.Settings != adoptedSettings
|
||||
if settingsChanged {
|
||||
if updates == nil {
|
||||
updates = make(map[string]any, 1)
|
||||
}
|
||||
updates["settings"] = adoptedSettings
|
||||
}
|
||||
rejected, err := withClientSyncSavepoint(tx, func() error {
|
||||
if len(updates) > 0 {
|
||||
if err := tx.Model(model.Inbound{}).Where("id = ?", c.Id).Updates(updates).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return s.clientService.SyncInbound(tx, c.Id, filtered)
|
||||
})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if rejected != nil {
|
||||
logger.Warningf("setRemoteTraffic: sync clients for tag %q failed: %v", snapIb.Tag, rejected)
|
||||
syncFailedInbounds[c.Id] = struct{}{}
|
||||
// The row holds what the node reported: pushing it back gets refused there and keeps the node dirty.
|
||||
if isNew {
|
||||
adoptedInbounds = append(adoptedInbounds, adoptedWireInbound(c, snapIb, p.wireSettings))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if len(updates) > 0 {
|
||||
structuralChange = true
|
||||
}
|
||||
adoptedSettingsChanged = adoptedSettingsChanged || settingsChanged
|
||||
lifecycleLifted = lifecycleLifted || liftChanged
|
||||
// Stamp the un-lifted wire blob so reconciliation can push lifecycle lifts.
|
||||
if !isNew && (liftChanged || c.Settings != p.wireSettings || adoptedWireConfigChanged(c, snapIb)) {
|
||||
adoptedInbounds = append(adoptedInbounds, adoptedWireInbound(c, snapIb, p.wireSettings))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1485,6 +1500,9 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
|
||||
return false, err
|
||||
}
|
||||
committed = true
|
||||
if adoptedSettingsChanged {
|
||||
InvalidateSubData()
|
||||
}
|
||||
|
||||
if len(degradedInbounds) > 0 {
|
||||
if mgr := runtime.GetManager(); mgr != nil {
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
func TestNodeClientReconcileRollback(t *testing.T) {
|
||||
testNodeClientReconcileRollback(t)
|
||||
}
|
||||
|
||||
func TestNodeClientReconcileRollbackPostgres(t *testing.T) {
|
||||
if os.Getenv("XUI_DB_TYPE") != "postgres" || os.Getenv("XUI_DB_DSN") == "" {
|
||||
t.Skip("requires a disposable PostgreSQL database")
|
||||
}
|
||||
testNodeClientReconcileRollback(t)
|
||||
}
|
||||
|
||||
func testNodeClientReconcileRollback(t *testing.T) {
|
||||
t.Helper()
|
||||
db := initTrafficTestDB(t)
|
||||
node := &model.Node{Name: "rollback-7219", Address: "127.0.0.1", Port: 2096, ApiToken: "test", Enable: true}
|
||||
seedNodeRow(t, db, node)
|
||||
svc := &InboundService{}
|
||||
|
||||
newClient := func(email string) model.Client {
|
||||
return model.Client{ID: uuid.NewString(), Email: email, SubID: email, Password: email, Enable: true}
|
||||
}
|
||||
shared := newClient("shared@rollback")
|
||||
shared.Flow = "xtls-rprx-vision"
|
||||
otherTuic := newClient("other-tuic@rollback")
|
||||
removed := newClient("removed@rollback")
|
||||
attempted := newClient("attempted@rollback")
|
||||
healthy := newClient("healthy@rollback")
|
||||
newHealthy := newClient("new-healthy@rollback")
|
||||
|
||||
nodeInbound := func(tag string, port int, protocol model.Protocol, clients ...model.Client) *model.Inbound {
|
||||
return &model.Inbound{Tag: tag, Port: port, Protocol: protocol, Enable: true, Settings: clientsSettings(t, clients)}
|
||||
}
|
||||
merge := func(target *model.Inbound, up int64, siblings ...model.Client) {
|
||||
t.Helper()
|
||||
tuic := nodeInbound("rollback-tuic", 45101, model.TUIC, shared, otherTuic)
|
||||
sibling := nodeInbound("rollback-healthy", 45103, model.VLESS, siblings...)
|
||||
sibling.Up = up
|
||||
sibling.ClientStats = []xray.ClientTraffic{{Email: healthy.Email, Up: up, Enable: true}}
|
||||
snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{tuic, target, sibling}}
|
||||
if _, err := svc.SetRemoteTraffic(node.Id, snap, false, false); err != nil {
|
||||
t.Fatalf("merge snapshot: %v", err)
|
||||
}
|
||||
}
|
||||
loadInbound := func(tag string) model.Inbound {
|
||||
t.Helper()
|
||||
var ib model.Inbound
|
||||
if err := db.Where("node_id = ? AND tag = ?", node.Id, tag).Take(&ib).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ib
|
||||
}
|
||||
loadLinks := func(id int) []model.ClientInbound {
|
||||
t.Helper()
|
||||
var links []model.ClientInbound
|
||||
if err := db.Where("inbound_id = ?", id).Order("client_id").Find(&links).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return links
|
||||
}
|
||||
|
||||
const tag = "rollback-vless"
|
||||
merge(nodeInbound(tag, 45102, model.VLESS, shared, removed), 0, healthy)
|
||||
before := loadInbound(tag)
|
||||
beforeLinks := loadLinks(before.Id)
|
||||
beforeClient := lookupClientRecord(t, shared.Email)
|
||||
if len(beforeLinks) != 2 || linkCount(t, db, shared.Email) != 2 {
|
||||
t.Fatal("fixture requires two VLESS links and a shared VLESS/TUIC identity")
|
||||
}
|
||||
|
||||
collision := shared
|
||||
collision.ID, collision.Flow = otherTuic.ID, ""
|
||||
rejected := nodeInbound(tag, 45102, model.VLESS, collision, attempted)
|
||||
rejected.Remark = "unaccepted config"
|
||||
merge(rejected, 11, healthy, newHealthy)
|
||||
|
||||
gotClient := lookupClientRecord(t, shared.Email)
|
||||
if gotClient.UUID != beforeClient.UUID || gotClient.Flow != beforeClient.Flow {
|
||||
t.Errorf("failed sync persisted shared client UUID=%q flow=%q, want UUID=%q flow=%q",
|
||||
gotClient.UUID, gotClient.Flow, beforeClient.UUID, beforeClient.Flow)
|
||||
}
|
||||
if got := loadLinks(before.Id); !slices.Equal(got, beforeLinks) {
|
||||
t.Errorf("failed sync persisted VLESS links %+v, want %+v", got, beforeLinks)
|
||||
}
|
||||
if got, _ := countClientRows(t, db, attempted.Email); got != 0 {
|
||||
t.Errorf("failed sync persisted %d new client rows, want 0", got)
|
||||
}
|
||||
if got := loadInbound(tag); got.Settings != before.Settings || got.Remark != before.Remark {
|
||||
t.Errorf("failed sync persisted adopted settings or remark for %q", tag)
|
||||
}
|
||||
if got := readOrphanMark(t, db, removed.Email); got != 0 {
|
||||
t.Errorf("failed inbound's client was orphan-marked at %d", got)
|
||||
}
|
||||
|
||||
sibling := loadInbound("rollback-healthy")
|
||||
if sibling.Up != 11 || linkCount(t, db, newHealthy.Email) != 1 {
|
||||
t.Errorf("healthy sibling did not commit its traffic and new client: up=%d", sibling.Up)
|
||||
}
|
||||
var baseline model.NodeClientTraffic
|
||||
if err := db.Where("node_id = ? AND email = ?", node.Id, healthy.Email).Take(&baseline).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var usage xray.ClientTraffic
|
||||
if err := db.Where("email = ?", healthy.Email).Take(&usage).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if baseline.Up != 11 || usage.Up != 11 {
|
||||
t.Errorf("healthy client baseline=%d traffic=%d, want 11/11", baseline.Up, usage.Up)
|
||||
}
|
||||
|
||||
corrected := nodeInbound(tag, 45102, model.VLESS, shared, attempted)
|
||||
corrected.Remark = "accepted config"
|
||||
merge(corrected, 11, healthy, newHealthy)
|
||||
got := loadInbound(tag)
|
||||
if got.Settings != corrected.Settings || got.Remark != corrected.Remark || linkCount(t, db, attempted.Email) != 1 {
|
||||
t.Error("valid follow-up snapshot did not reconcile the previously rejected inbound")
|
||||
}
|
||||
if linkCount(t, db, removed.Email) != 0 || readOrphanMark(t, db, removed.Email) == 0 {
|
||||
t.Error("valid follow-up snapshot did not detach and orphan-mark the removed client")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNodeRefusedFirstAdoptionKeepsNodeSettings(t *testing.T) {
|
||||
testNodeRefusedFirstAdoptionKeepsNodeSettings(t)
|
||||
}
|
||||
|
||||
func TestNodeRefusedFirstAdoptionKeepsNodeSettingsPostgres(t *testing.T) {
|
||||
if os.Getenv("XUI_DB_TYPE") != "postgres" || os.Getenv("XUI_DB_DSN") == "" {
|
||||
t.Skip("requires a disposable PostgreSQL database")
|
||||
}
|
||||
testNodeRefusedFirstAdoptionKeepsNodeSettings(t)
|
||||
}
|
||||
|
||||
func testNodeRefusedFirstAdoptionKeepsNodeSettings(t *testing.T) {
|
||||
t.Helper()
|
||||
db := initTrafficTestDB(t)
|
||||
var nodeCalls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
nodeCalls.Add(1)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"success":true}`))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
host, portString, err := net.SplitHostPort(srv.Listener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
port, err := strconv.Atoi(portString)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
node := &model.Node{
|
||||
Name: "first-adoption-7219", Scheme: "http", Address: host, Port: port, BasePath: "/",
|
||||
ApiToken: "test", Enable: true, AllowPrivateAddress: true,
|
||||
}
|
||||
seedNodeRow(t, db, node)
|
||||
remote := runtime.NewRemote(node, nil)
|
||||
useTestRuntimeManager(t).SetRuntimeOverride(node.Id, remote)
|
||||
svc := &InboundService{}
|
||||
|
||||
newClient := func(email string) model.Client {
|
||||
return model.Client{ID: uuid.NewString(), Email: email, SubID: email, Password: email, Enable: true}
|
||||
}
|
||||
shared := newClient("shared@first-adoption")
|
||||
otherTuic := newClient("other-tuic@first-adoption")
|
||||
attempted := newClient("attempted@first-adoption")
|
||||
healthy := newClient("healthy@first-adoption")
|
||||
|
||||
nodeInbound := func(tag string, port int, protocol model.Protocol, clients ...model.Client) *model.Inbound {
|
||||
return &model.Inbound{
|
||||
Tag: tag, Port: port, Protocol: protocol, Enable: true, Settings: clientsSettings(t, clients),
|
||||
TrafficReset: "never", TrafficResetDay: 1,
|
||||
}
|
||||
}
|
||||
merge := func(up int64, extra ...*model.Inbound) {
|
||||
t.Helper()
|
||||
sibling := nodeInbound("first-healthy", 45113, model.VLESS, healthy)
|
||||
sibling.Up = up
|
||||
sibling.ClientStats = []xray.ClientTraffic{{Email: healthy.Email, Up: up, Enable: true}}
|
||||
inbounds := []*model.Inbound{nodeInbound("first-tuic", 45111, model.TUIC, shared, otherTuic)}
|
||||
inbounds = append(append(inbounds, extra...), sibling)
|
||||
if _, err := svc.SetRemoteTraffic(node.Id, &runtime.TrafficSnapshot{Inbounds: inbounds}, false, false); err != nil {
|
||||
t.Fatalf("merge snapshot: %v", err)
|
||||
}
|
||||
}
|
||||
storedFor := func(tag string) []model.Inbound {
|
||||
t.Helper()
|
||||
var rows []model.Inbound
|
||||
if err := db.Where("node_id = ? AND tag = ?", node.Id, tag).Find(&rows).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
merge(0)
|
||||
const tag = "first-vless"
|
||||
collision := shared
|
||||
collision.ID = otherTuic.ID
|
||||
refused := nodeInbound(tag, 45112, model.VLESS, collision, attempted)
|
||||
sharedBefore := lookupClientRecord(t, shared.Email)
|
||||
merge(11, refused)
|
||||
|
||||
// A reconcile pushes the stored blob, so anything but the node's own would cost it clients.
|
||||
rows := storedFor(tag)
|
||||
if len(rows) != 1 || rows[0].Settings != refused.Settings {
|
||||
t.Fatalf("refused first adoption stored %d rows for %q, want one holding the node's settings", len(rows), tag)
|
||||
}
|
||||
if got, _ := countClientRows(t, db, attempted.Email); got != 0 {
|
||||
t.Errorf("refused first adoption persisted %d client rows, want 0", got)
|
||||
}
|
||||
var links int64
|
||||
if err := db.Model(&model.ClientInbound{}).Where("inbound_id = ?", rows[0].Id).Count(&links).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := lookupClientRecord(t, shared.Email); links != 0 || got.UUID != sharedBefore.UUID {
|
||||
t.Errorf("refused first adoption left %d links and shared UUID %q, want 0 and %q", links, got.UUID, sharedBefore.UUID)
|
||||
}
|
||||
// The node refuses the blob it reported inconsistently, and a failed push keeps it dirty for good.
|
||||
payload, err := svc.buildInboundForNodePush(db, &rows[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nodeCalls.Store(0)
|
||||
pushed, err := remote.ReconcileInbound(t.Context(), payload, true)
|
||||
if err != nil || pushed || nodeCalls.Load() != 0 {
|
||||
t.Errorf("reconcile of the refused inbound pushed=%t err=%v after %d node calls, want nothing sent", pushed, err, nodeCalls.Load())
|
||||
}
|
||||
var sibling model.Inbound
|
||||
if err := db.Where("node_id = ? AND tag = ?", node.Id, "first-healthy").Take(&sibling).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var usage xray.ClientTraffic
|
||||
if err := db.Where("email = ?", healthy.Email).Take(&usage).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sibling.Up != 11 || usage.Up != 11 {
|
||||
t.Errorf("healthy sibling up=%d client up=%d, want 11/11", sibling.Up, usage.Up)
|
||||
}
|
||||
|
||||
corrected := nodeInbound(tag, 45112, model.VLESS, shared, attempted)
|
||||
merge(11, corrected)
|
||||
rows = storedFor(tag)
|
||||
if len(rows) != 1 || rows[0].Settings != corrected.Settings || linkCount(t, db, attempted.Email) != 1 {
|
||||
t.Fatalf("corrected snapshot stored %d rows for %q, want one adopted inbound with its client linked", len(rows), tag)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user