Files
3x-ui/internal/web/service/client_group_node_sync_test.go
T
mrchatam 6f7a305239 fix(node): stop stale expiry sync from undoing client extensions (#6228) (#6231)
* fix(node): stop stale expiry sync from undoing client extensions (#6228)

After an expired client is extended on the master, a lagging node could
overwrite client_traffics with an older absolute expiry and latch
enable=false. Reject older absolute expiries on merge, ignore
expiry-stale disables when the master is not over quota, lift stale
lifecycle fields out of adopted settings, stamp reconcile fingerprints
from the pre-lift node blob, and mark the node dirty so the next tick
re-pushes.

* fix(node): lockstep client_traffics expiry/enable SQL with review fixes (#6228)

Make expiry merge keep any master absolute (node only activates when master
is unset/duration). Include this tick's up/down deltas in the enable
stale-disable quota check so a crossing-tick disable is not dropped.

* fix(node): add settings absolute helper for renew/lift guards (#6228)

Expose settingsClientAbsoluteExpiry so traffic merge can tell a real
node auto-renew (settings+stats later) from lagging ClientStats after a
master shorten. Trim lift godoc to the invariant.

* fix(node): authority-aware lifecycle merge for multi-node sync (#6228)

While config_dirty, accumulate traffic only — do not adopt node
expiry/enable/total/reset (and preserve dipped baselines so a false
renew cannot fire after clear). On clean ticks, master absolute expiry
wins; node auto-renew still goes through nodeClientRenewed when settings
also show the later deadline. Defer settings lifecycle lift until after
traffic deltas land, align SyncInbound via applyMasterClientLifecycle,
and avoid re-MarkNodeDirty when already dirty.

* fix(node): clear config_dirty only after the post-reconcile traffic merge (#6228)

After a successful ReconcileNode, keep the node dirty through the same
tick's SetRemoteTraffic so lagging ClientStats cannot clobber the
just-pushed master lifecycle, then ClearNodeDirty.

* test(node): cover dirty-gate, master-absolute, and renew false-positives (#6228)

Add regressions for extend/shorten while dirty, clean-sibling shorten,
settings vs lagging disable, renew recovery after dirty, renew with
matching settings, and shorten+Reset lagging stats not treated as renew.

* fix(node): address the review findings on the lifecycle merge (#6228)

The automated review on #6231 flagged a blocking regression and six smaller
issues. All of them are fixed here.

Blocking: making the master's absolute expiry always win left nodeClientRenewed
as the only channel for a node-side auto-renew, and that required a counter dip.
A client that used no traffic in the period never dips, so its renewal was
dropped, the master kept the expired deadline and disableInvalidClients removed
it with no way back (master-side autoRenewClients skips node inbounds). The node
bumps reset_count on every renewal, so that counter is now an independent
renewal signal and is persisted with the renewal so it keeps converging.

The deferred ClearNodeDirty made every reconcile-success tick merge in dirty
mode, which suppressed inbound adoption, new client_traffics rows, the orphan
sweeps and the whole SyncInbound record loop -- and left the node dirty forever
whenever SetRemoteTraffic errored. The clear goes back to where it was; a
separate justPushed flag now freezes only the client lifecycle merge for the
tick whose push just landed.

staleNodeDisable only recognised a lagging disable by an older expiry, so a
quota top-up (raise totalGB, leave the expiry alone) was re-latched to disabled
by the next lagging snapshot -- the #6228 symptom on a second axis. The
reviewer's suggestion of dropping the expiry precondition outright fails
TestNodeQuotaDisable_SameExpiryStillLatches, because the master's own counters
legitimately sit below a node's after a seeded-at-zero adoption. nodeDisableIsStale
instead compares the limits the node judged the client against with the master's
own: matching limits mean a genuine verdict that still latches (#4917), differing
limits mean the node has not seen the master's change yet. It also now measures
the master deadline against wall-clock now, so an expired master row no longer
looks "extended" merely because the node's copy is older still.

Also: the settings lift now writes enable in both directions, so a blob fetched
before a master disable cannot carry enable=true back into central settings and
on to the node; the renewal guard parses the inbound settings once per inbound
instead of once per renewing client; the adoption loop only writes settings when
they actually changed; and two comments that described mechanisms the code does
not use were corrected.

The test deadlines are now relative to the run: the merge compares against now,
so fixed timestamps would have rotted into the wrong side of it.

---------

Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-08-23 23:17:56 +02:00

194 lines
5.8 KiB
Go

package service
import (
"path/filepath"
"strings"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
)
func TestSetRemoteTraffic_PreservesPanelLocalGroupAndComment(t *testing.T) {
dbDir := t.TempDir()
t.Setenv("XUI_DB_FOLDER", dbDir)
if err := database.InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
t.Fatalf("InitDB: %v", err)
}
t.Cleanup(func() { _ = database.CloseDB() })
db := database.GetDB()
const nodeID = 1
const email = "node-user@example.com"
const uid = "ce8d33df-3a64-4f10-8f9b-91c3a8e0c003"
const wantGroup = "vip"
const wantComment = "renewed manually"
id := nodeID
central := &model.Inbound{
UserId: 1,
NodeID: &id,
Tag: "n1-vless",
Enable: true,
Port: 20001,
Protocol: model.VLESS,
Settings: `{"clients":[{"email":"` + email + `","id":"` + uid + `","enable":true,"group":"` + wantGroup + `","comment":"` + wantComment + `"}]}`,
}
if err := db.Create(central).Error; err != nil {
t.Fatalf("create node inbound: %v", err)
}
if err := db.Create(&model.ClientRecord{
Email: email,
UUID: uid,
Enable: true,
Group: wantGroup,
Comment: wantComment,
}).Error; err != nil {
t.Fatalf("create client record: %v", err)
}
snap := &runtime.TrafficSnapshot{
Inbounds: []*model.Inbound{
{
Tag: "n1-vless",
Enable: true,
Port: 20001,
Protocol: model.VLESS,
Settings: `{"clients":[{"email":"` + email + `","id":"` + uid + `","enable":true}]}`,
},
},
}
svc := InboundService{}
if _, err := svc.setRemoteTrafficLocked(nodeID, snap, false, false); err != nil {
t.Fatalf("setRemoteTrafficLocked: %v", err)
}
var row model.ClientRecord
if err := db.Where("email = ?", email).First(&row).Error; err != nil {
t.Fatalf("lookup client row after sync: %v", err)
}
if row.Group != wantGroup {
t.Errorf("group was wiped by node snapshot sync: got %q, want %q", row.Group, wantGroup)
}
if row.Comment != wantComment {
t.Errorf("comment was wiped by node snapshot sync: got %q, want %q", row.Comment, wantComment)
}
}
func TestSyncInbound_KeepsGroupWhenIncomingEmpty(t *testing.T) {
dbDir := t.TempDir()
t.Setenv("XUI_DB_FOLDER", dbDir)
if err := database.InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
t.Fatalf("InitDB: %v", err)
}
t.Cleanup(func() { _ = database.CloseDB() })
db := database.GetDB()
ib := &model.Inbound{Tag: "vless-grp", Enable: true, Port: 20002, Protocol: model.VLESS}
if err := db.Create(ib).Error; err != nil {
t.Fatalf("create inbound: %v", err)
}
svc := ClientService{}
const email = "grp-user@example.com"
const uid = "ce8d33df-3a64-4f10-8f9b-91c3a8e0c004"
const wantGroup = "vip"
withGroup := model.Client{Email: email, ID: uid, Enable: true, Group: wantGroup}
if err := svc.SyncInbound(nil, ib.Id, []model.Client{withGroup}); err != nil {
t.Fatalf("SyncInbound (set group): %v", err)
}
noGroup := model.Client{Email: email, ID: uid, Enable: true, Group: ""}
if err := svc.SyncInbound(nil, ib.Id, []model.Client{noGroup}); err != nil {
t.Fatalf("SyncInbound (group-less rebuild): %v", err)
}
var row model.ClientRecord
if err := db.Where("email = ?", email).First(&row).Error; err != nil {
t.Fatalf("lookup client row: %v", err)
}
if row.Group != wantGroup {
t.Errorf("group must survive a group-less settings rebuild (it is managed via the Groups page, not Xray settings): got %q, want %q", row.Group, wantGroup)
}
}
// Removing the group in the client editor and saving must clear group_name and
// drop the settings "group" key, even though SyncInbound preserves a group on a
// group-less rebuild. The editor round-trips the field, so ClientService.Update
// applies it explicitly.
func TestClientUpdate_ClearsGroup(t *testing.T) {
dbDir := t.TempDir()
t.Setenv("XUI_DB_FOLDER", dbDir)
if err := database.InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
t.Fatalf("InitDB: %v", err)
}
t.Cleanup(func() { _ = database.CloseDB() })
db := database.GetDB()
const email = "grp-clear@example.com"
const uid = "ce8d33df-3a64-4f10-8f9b-91c3a8e0c005"
const wantGroup = "vip"
ib := &model.Inbound{
UserId: 1,
Tag: "vless-clear",
Enable: true,
Port: 20003,
Protocol: model.VLESS,
Settings: `{"clients":[{"email":"` + email + `","id":"` + uid + `","enable":true,"group":"` + wantGroup + `"}]}`,
}
if err := db.Create(ib).Error; err != nil {
t.Fatalf("create inbound: %v", err)
}
svc := ClientService{}
inboundSvc := &InboundService{}
// Seed the client record + inbound link from the settings.
seedClients, err := inboundSvc.GetClients(ib)
if err != nil {
t.Fatalf("GetClients: %v", err)
}
if err := svc.SyncInbound(nil, ib.Id, seedClients); err != nil {
t.Fatalf("seed SyncInbound: %v", err)
}
var rec model.ClientRecord
if err := db.Where("email = ?", email).First(&rec).Error; err != nil {
t.Fatalf("lookup seeded record: %v", err)
}
if rec.Group != wantGroup {
t.Fatalf("setup: group not seeded, got %q", rec.Group)
}
// Edit the client and remove the group.
updated := *rec.ToClient()
updated.Group = ""
if _, err := svc.Update(inboundSvc, rec.Id, updated, 0); err != nil {
t.Fatalf("Update (clear group): %v", err)
}
var after model.ClientRecord
if err := db.Where("email = ?", email).First(&after).Error; err != nil {
t.Fatalf("lookup record after update: %v", err)
}
if after.Group != "" {
t.Errorf("group not cleared after editor removed it: got %q, want empty", after.Group)
}
var ibAfter model.Inbound
if err := db.First(&ibAfter, ib.Id).Error; err != nil {
t.Fatalf("lookup inbound after update: %v", err)
}
if strings.Contains(ibAfter.Settings, `"group"`) {
t.Errorf("inbound settings still carry a group key after removal: %s", ibAfter.Settings)
}
}