mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 16:34:52 +03:00
315 lines
12 KiB
Go
315 lines
12 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/testpg"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
|
|
)
|
|
|
|
func setupFrozenGroupBulkDB(t *testing.T) {
|
|
t.Helper()
|
|
cleanup, err := testpg.IsolatePackage("frozen_group_bulk")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(cleanup)
|
|
setupBulkDB(t)
|
|
}
|
|
|
|
func TestFrozenGroupBulkRejectsIdentityAndMembershipChanges(t *testing.T) {
|
|
for _, operation := range []string{"adjust", "delete"} {
|
|
for _, change := range []string{"replace", "move"} {
|
|
t.Run(operation+"/"+change, func(t *testing.T) {
|
|
setupFrozenGroupBulkDB(t)
|
|
db := database.GetDB()
|
|
svc, inboundSvc := &ClientService{}, &InboundService{}
|
|
client := model.Client{Email: "frozen@example.test", Group: "staff", ID: "11111111-1111-1111-1111-111111111111", TotalGB: 1024, Enable: true}
|
|
ib := mkInbound(t, 41001, model.VLESS, clientsSettings(t, []model.Client{client}))
|
|
if err := svc.SyncInbound(nil, ib.Id, []model.Client{client}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
mkTraffic(t, ib.Id, client.Email, 1, 0, 1024, 0, true)
|
|
before, err := svc.GetRecordByEmail(nil, client.Email)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
page, err := svc.ListGroupClients(t.Context(), GroupClientPageParams{Group: "staff", Mode: "remove", Freeze: true})
|
|
if err != nil || page.Total != 1 {
|
|
t.Fatalf("freeze: %+v, %v", page, err)
|
|
}
|
|
scope, err := ResolveGroupBulkScope(t.Context(), "staff", page.ScopeToken)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
// The operation can only proceed once the other writer has committed.
|
|
done := make(chan error, 1)
|
|
wantID := before.Id
|
|
go func() {
|
|
done <- runSerializedTx(func(tx *gorm.DB) error {
|
|
if change == "move" {
|
|
return tx.Model(before).Update("group_name", "outside").Error
|
|
}
|
|
if err := tx.Where("client_id = ?", before.Id).Delete(&model.ClientInbound{}).Error; err != nil {
|
|
return err
|
|
}
|
|
if err := tx.Delete(before).Error; err != nil {
|
|
return err
|
|
}
|
|
next := *before
|
|
next.Id = 0
|
|
if err := tx.Create(&next).Error; err != nil {
|
|
return err
|
|
}
|
|
if next.Id <= page.MaxID {
|
|
return fmt.Errorf("replacement %d is within cutoff %d", next.Id, page.MaxID)
|
|
}
|
|
wantID = next.Id
|
|
return tx.Create(&model.ClientInbound{ClientId: next.Id, InboundId: ib.Id}).Error
|
|
})
|
|
}()
|
|
if err := <-done; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
if operation == "adjust" {
|
|
res, _, err := svc.BulkAdjustGroup(inboundSvc, scope, 0, 1024, "", nil, "")
|
|
if err != nil || res.Adjusted != 0 || len(res.Skipped) != 1 || res.Skipped[0].Reason != scope.skipReason() {
|
|
t.Fatalf("adjust: %+v, %v", res, err)
|
|
}
|
|
// Also exercise the guard with a plan made before the other writer.
|
|
plan := map[string]*bulkAdjustEntry{client.Email: {record: before, applyTotal: true, newTotal: 2048}}
|
|
part := svc.bulkAdjustInboundClients(inboundSvc, ib.Id, []string{client.Email}, plan, scope, "", "")
|
|
if part.perEmailSkipped[client.Email] != scope.skipReason() {
|
|
t.Fatalf("stale inbound adjust: %+v", part)
|
|
}
|
|
} else {
|
|
res, _, err := svc.BulkDeleteGroup(inboundSvc, scope, false)
|
|
if err != nil || res.Deleted != 0 || len(res.Skipped) != 1 || res.Skipped[0].Reason != scope.skipReason() {
|
|
t.Fatalf("delete: %+v, %v", res, err)
|
|
}
|
|
part := svc.bulkDelInboundClients(inboundSvc, ib.Id, []string{client.Email}, map[string]*model.ClientRecord{client.Email: before}, scope, false)
|
|
if part.perEmailSkipped[client.Email] != scope.skipReason() || isClientEmailTombstoned(client.Email) {
|
|
t.Fatalf("stale inbound delete: %+v", part)
|
|
}
|
|
}
|
|
got, err := svc.GetRecordByEmail(nil, client.Email)
|
|
if err != nil || got.Id != wantID || got.TotalGB != 1024 {
|
|
t.Fatalf("protected record: %+v, %v", got, err)
|
|
}
|
|
if got := trafficOf(t, client.Email); got.Total != 1024 || got.Up != 1 {
|
|
t.Fatalf("protected traffic: %+v", got)
|
|
}
|
|
var settings string
|
|
if err := db.Model(ib).Select("settings").Find(&settings).Error; err != nil || settings != ib.Settings {
|
|
t.Fatalf("protected settings changed: %s (%v)", settings, err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestFrozenGroupBulkAppliesLinkedTargets(t *testing.T) {
|
|
setupFrozenGroupBulkDB(t)
|
|
svc, inboundSvc := &ClientService{}, &InboundService{}
|
|
client := model.Client{Email: "linked-group@example.test", Group: "staff", ID: "11111111-1111-1111-1111-111111111111", TotalGB: 1024, Enable: true}
|
|
ib := mkInbound(t, 41001, model.VLESS, clientsSettings(t, []model.Client{client}))
|
|
if err := svc.SyncInbound(nil, ib.Id, []model.Client{client}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
mkTraffic(t, ib.Id, client.Email, 1, 0, 1024, 0, true)
|
|
page, err := svc.ListGroupClients(t.Context(), GroupClientPageParams{Group: "staff", Mode: "remove", Freeze: true})
|
|
if err != nil || page.Total != 1 {
|
|
t.Fatalf("freeze: %+v, %v", page, err)
|
|
}
|
|
scope, err := ResolveGroupBulkScope(t.Context(), "staff", page.ScopeToken)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
adjust, _, err := svc.BulkAdjustGroup(inboundSvc, scope, 0, 1024, "", nil, "")
|
|
if err != nil || adjust.Adjusted != 1 || len(adjust.Skipped) != 0 {
|
|
t.Fatalf("adjust: %+v, %v", adjust, err)
|
|
}
|
|
if got := trafficOf(t, client.Email); got.Total != 2048 {
|
|
t.Fatalf("adjusted traffic: %+v", got)
|
|
}
|
|
del, _, err := svc.BulkDeleteGroup(inboundSvc, scope, false)
|
|
if err != nil || del.Deleted != 1 || len(del.Skipped) != 0 {
|
|
t.Fatalf("delete: %+v, %v", del, err)
|
|
}
|
|
var rows int64
|
|
if err := database.GetDB().Model(&model.ClientRecord{}).Where("email = ?", client.Email).Count(&rows).Error; err != nil || rows != 0 {
|
|
t.Fatalf("deleted client still present: %d (%v)", rows, err)
|
|
}
|
|
}
|
|
|
|
type groupAdjustBarrierRuntime struct {
|
|
fakeNodeRuntime
|
|
entered chan struct{}
|
|
release chan struct{}
|
|
}
|
|
|
|
func (r *groupAdjustBarrierRuntime) UpdateUser(ctx context.Context, _ *model.Inbound, _ string, _ model.Client) (runtime.ClientApplyResult, error) {
|
|
select {
|
|
case r.entered <- struct{}{}:
|
|
default:
|
|
}
|
|
select {
|
|
case <-r.release:
|
|
return runtime.ClientApplyResult{}, nil
|
|
case <-ctx.Done():
|
|
return runtime.ClientApplyResult{}, ctx.Err()
|
|
}
|
|
}
|
|
|
|
func TestFrozenGroupBulkAdjustSurvivesMembershipMoveAfterCommit(t *testing.T) {
|
|
setupClientNodeOrderDB(t)
|
|
nodeID, _ := setupNodeRuntime(t)
|
|
barrier := &groupAdjustBarrierRuntime{entered: make(chan struct{}, 1), release: make(chan struct{})}
|
|
runtime.GetManager().SetRuntimeOverride(nodeID, barrier)
|
|
|
|
const originalTotal = 1024
|
|
const newTotal = 2048
|
|
oldExpiry := time.Now().Add(48 * time.Hour).UnixMilli()
|
|
newExpiry := oldExpiry + reenableDay
|
|
client := model.Client{
|
|
Email: "moving@example.test",
|
|
Group: "staff",
|
|
ID: "11111111-1111-1111-1111-111111111111",
|
|
TotalGB: originalTotal,
|
|
ExpiryTime: oldExpiry,
|
|
}
|
|
svc, inboundSvc := &ClientService{}, &InboundService{}
|
|
remote := nodeInbound(t, nodeID, 41001, []model.Client{client})
|
|
local := mkInbound(t, 41002, model.VLESS, clientsSettings(t, []model.Client{client}))
|
|
if err := svc.SyncInbound(nil, local.Id, []model.Client{client}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
mkTraffic(t, remote.Id, client.Email, originalTotal, 0, originalTotal, oldExpiry, false)
|
|
page, err := svc.ListGroupClients(t.Context(), GroupClientPageParams{Group: "staff", Mode: "remove", Freeze: true})
|
|
if err != nil || page.Total != 1 {
|
|
t.Fatalf("freeze: %+v, %v", page, err)
|
|
}
|
|
scope, err := ResolveGroupBulkScope(t.Context(), "staff", page.ScopeToken)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
siblingLock := lockInbound(local.Id)
|
|
unlockSibling := sync.OnceFunc(siblingLock.Unlock)
|
|
releaseNode := sync.OnceFunc(func() { close(barrier.release) })
|
|
type outcome struct {
|
|
result BulkAdjustResult
|
|
err error
|
|
}
|
|
done := make(chan outcome, 1)
|
|
var operation sync.WaitGroup
|
|
t.Cleanup(func() {
|
|
unlockSibling()
|
|
releaseNode()
|
|
operation.Wait()
|
|
})
|
|
operation.Go(func() {
|
|
res, _, err := svc.BulkAdjustGroup(inboundSvc, scope, 1, newTotal-originalTotal, "", nil, "")
|
|
done <- outcome{res, err}
|
|
})
|
|
select {
|
|
case <-barrier.entered:
|
|
case <-time.After(nodeClientPushTimeout):
|
|
t.Fatal("adjustment never reached post-commit node delivery")
|
|
}
|
|
|
|
if got := trafficOf(t, client.Email); got.Total != newTotal || got.ExpiryTime != newExpiry {
|
|
t.Errorf("traffic limits at the post-commit barrier: %+v", got)
|
|
}
|
|
if moved, err := svc.AddToGroup([]string{client.Email}, "new-group"); err != nil || moved != 1 {
|
|
t.Fatalf("move while node apply waits: %d (%v)", moved, err)
|
|
}
|
|
unlockSibling()
|
|
releaseNode()
|
|
|
|
applied := <-done
|
|
if got := trafficOf(t, client.Email); got.Total != newTotal || got.ExpiryTime != newExpiry || got.Up != originalTotal || !got.Enable {
|
|
t.Errorf("traffic after committed adjust and group move: %+v", got)
|
|
}
|
|
record, err := svc.GetRecordByEmail(nil, client.Email)
|
|
if err != nil || record.Group != "new-group" || record.TotalGB != newTotal || record.ExpiryTime != newExpiry || !record.Enable {
|
|
t.Errorf("record after committed adjust and group move: %+v (%v)", record, err)
|
|
}
|
|
for _, attached := range []*model.Inbound{remote, local} {
|
|
inbound, err := inboundSvc.GetInbound(attached.Id)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
list, err := inboundSvc.GetClients(inbound)
|
|
if err != nil || len(list) != 1 || list[0].Group != "new-group" || list[0].TotalGB != newTotal || list[0].ExpiryTime != newExpiry || !list[0].Enable {
|
|
t.Errorf("inbound %d after committed adjust and group move: %+v (%v)", attached.Id, list, err)
|
|
}
|
|
}
|
|
if applied.err != nil || applied.result.Adjusted != 1 || len(applied.result.Skipped) != 0 {
|
|
t.Errorf("adjust result: %+v (%v)", applied.result, applied.err)
|
|
}
|
|
}
|
|
|
|
func TestFrozenGroupBulkAdjustRollsBackWhenTrafficWriteFails(t *testing.T) {
|
|
setupFrozenGroupBulkDB(t)
|
|
db := database.GetDB()
|
|
svc, inboundSvc := &ClientService{}, &InboundService{}
|
|
client := model.Client{
|
|
Email: "rollback@example.test",
|
|
Group: "rollback-group",
|
|
ID: "11111111-1111-1111-1111-111111111111",
|
|
TotalGB: 1024,
|
|
Enable: true,
|
|
}
|
|
inbound := mkInbound(t, 41003, model.VLESS, clientsSettings(t, []model.Client{client}))
|
|
if err := svc.SyncInbound(nil, inbound.Id, []model.Client{client}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
mkTraffic(t, inbound.Id, client.Email, 1, 0, 1024, 0, true)
|
|
page, err := svc.ListGroupClients(t.Context(), GroupClientPageParams{Group: client.Group, Mode: "remove", Freeze: true})
|
|
if err != nil || page.Total != 1 {
|
|
t.Fatalf("freeze: %+v, %v", page, err)
|
|
}
|
|
scope, err := ResolveGroupBulkScope(t.Context(), client.Group, page.ScopeToken)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
const callback = "test:fail_adjust_traffic_write"
|
|
writeErr := errors.New("injected client traffic write failure")
|
|
if err := db.Callback().Update().Before("gorm:update").Register(callback, func(tx *gorm.DB) {
|
|
if tx.Statement.Table == "client_traffics" {
|
|
_ = tx.AddError(writeErr)
|
|
}
|
|
}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = db.Callback().Update().Remove(callback) })
|
|
|
|
result, _, err := svc.BulkAdjustGroup(inboundSvc, scope, 0, 1024, "", nil, "")
|
|
if err != nil || result.Adjusted != 0 || len(result.Skipped) != 1 || result.Skipped[0].Reason != writeErr.Error() {
|
|
t.Fatalf("expected a rolled-back adjust, got %+v (%v)", result, err)
|
|
}
|
|
record, err := svc.GetRecordByEmail(nil, client.Email)
|
|
if err != nil || record.TotalGB != 1024 {
|
|
t.Errorf("normalized quota after rollback: %+v (%v)", record, err)
|
|
}
|
|
current, err := inboundSvc.GetInbound(inbound.Id)
|
|
if err != nil || current.Settings != inbound.Settings {
|
|
t.Errorf("inbound settings after rollback: %+v (%v)", current, err)
|
|
}
|
|
if got := trafficOf(t, client.Email); got.Total != 1024 || got.Up != 1 {
|
|
t.Errorf("traffic after rollback: %+v", got)
|
|
}
|
|
}
|