mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-02 23:45:11 +03:00
e80af331eb
Reserve node apply turns in database commit order and release the inbound mutation lock before waiting or calling the remote runtime. Keep lifecycle updates and full reconciliation in the same sequence, preserve dirty generations across overlapping writes, and invalidate fingerprints after uncertain or superseded remote state.
516 lines
17 KiB
Go
516 lines
17 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"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"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
|
)
|
|
|
|
type blockedClientPushRuntime struct {
|
|
fakeNodeRuntime
|
|
calls chan string
|
|
release <-chan struct{}
|
|
blockedEmail string
|
|
waitForTimeout bool
|
|
expired atomic.Bool
|
|
}
|
|
|
|
func (r *blockedClientPushRuntime) AddClient(ctx context.Context, _ *model.Inbound, client model.Client) error {
|
|
r.calls <- "add " + client.Email
|
|
if client.Email != r.blockedEmail {
|
|
return nil
|
|
}
|
|
if r.waitForTimeout {
|
|
select {
|
|
case <-ctx.Done():
|
|
r.expired.Store(errors.Is(ctx.Err(), context.DeadlineExceeded))
|
|
return ctx.Err()
|
|
case <-time.After(nodeClientPushTimeout + 2*time.Second):
|
|
return errors.New("push timeout was not enforced")
|
|
}
|
|
}
|
|
select {
|
|
case <-r.release:
|
|
return nil
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
}
|
|
}
|
|
|
|
func (r *blockedClientPushRuntime) UpdateUser(_ context.Context, _ *model.Inbound, email string, client model.Client) error {
|
|
r.calls <- "update " + email + " " + client.Comment
|
|
return nil
|
|
}
|
|
|
|
func (r *blockedClientPushRuntime) DeleteUser(_ context.Context, _ *model.Inbound, email string) error {
|
|
r.calls <- "detach " + email
|
|
return nil
|
|
}
|
|
|
|
func (r *blockedClientPushRuntime) UpdateInbound(_ context.Context, _ *model.Inbound, inbound *model.Inbound) error {
|
|
r.calls <- "lifecycle " + inbound.Tag
|
|
return nil
|
|
}
|
|
|
|
func setupClientNodeOrderDB(t *testing.T) {
|
|
t.Helper()
|
|
cleanup, err := testpg.IsolatePackage("client_node_order")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(cleanup)
|
|
setupBulkDB(t)
|
|
startSerializedWriter(t)
|
|
}
|
|
|
|
func TestNodeClientMutationsCommitWhileAnEarlierPushIsBlocked(t *testing.T) {
|
|
for _, tc := range []struct {
|
|
name string
|
|
timeout bool
|
|
}{
|
|
{name: "successful push"},
|
|
{name: "ambiguous timeout", timeout: true},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
setupClientNodeOrderDB(t)
|
|
nodeID, _ := setupNodeRuntime(t)
|
|
release := make(chan struct{})
|
|
unblock := sync.OnceFunc(func() { close(release) })
|
|
const email = "ordered@example.test"
|
|
blocked := &blockedClientPushRuntime{
|
|
calls: make(chan string, 8), release: release, blockedEmail: email, waitForTimeout: tc.timeout,
|
|
}
|
|
mgr := runtime.GetManager()
|
|
mgr.SetRuntimeOverride(nodeID, blocked)
|
|
ib := nodeInbound(t, nodeID, 46001, nil)
|
|
siblingInbound := nodeInbound(t, nodeID, 46003, nil)
|
|
controlNode := model.Node{Name: "control", Address: "127.0.0.1", Port: 2097, ApiToken: "token", Enable: true, Status: "online"}
|
|
if err := database.GetDB().Create(&controlNode).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
control := &fakeNodeRuntime{}
|
|
mgr.SetRuntimeOverride(controlNode.Id, control)
|
|
other := nodeInbound(t, controlNode.Id, 46002, nil)
|
|
clientSvc, inboundSvc := &ClientService{}, &InboundService{}
|
|
client := model.Client{Email: email, ID: uuid.NewString(), Enable: true}
|
|
changed := client
|
|
changed.Comment = "committed update"
|
|
sibling := model.Client{Email: "control@example.test", ID: uuid.NewString(), Enable: true}
|
|
sameNode := model.Client{Email: "same-node@example.test", ID: uuid.NewString(), Enable: true}
|
|
data := func(inbound *model.Inbound, client model.Client) *model.Inbound {
|
|
return &model.Inbound{Id: inbound.Id, Protocol: inbound.Protocol, Settings: clientsSettings(t, []model.Client{client})}
|
|
}
|
|
addData, updateData, controlData := data(ib, client), data(ib, changed), data(other, sibling)
|
|
siblingData := data(siblingInbound, sameNode)
|
|
|
|
var wg sync.WaitGroup
|
|
t.Cleanup(func() {
|
|
unblock()
|
|
wg.Wait()
|
|
})
|
|
async := func(operation func() (bool, error)) <-chan error {
|
|
done := make(chan error, 1)
|
|
wg.Go(func() {
|
|
restart, err := operation()
|
|
if restart {
|
|
err = errors.Join(err, errors.New("requested a local restart for a remote mutation"))
|
|
}
|
|
done <- err
|
|
})
|
|
return done
|
|
}
|
|
expectCall := func(want string) {
|
|
t.Helper()
|
|
select {
|
|
case got := <-blocked.calls:
|
|
if got != want {
|
|
t.Fatalf("node operation = %q, want %q", got, want)
|
|
}
|
|
case <-time.After(nodeClientPushTimeout + time.Second):
|
|
t.Fatalf("node never received %q", want)
|
|
}
|
|
}
|
|
waitSettings := func(id int, contains string, present bool) {
|
|
t.Helper()
|
|
start := time.Now()
|
|
for {
|
|
current, err := inboundSvc.GetInbound(id)
|
|
if err == nil && strings.Contains(current.Settings, contains) == present {
|
|
t.Logf("local commit observed after %s while first RPC was blocked", time.Since(start))
|
|
return
|
|
}
|
|
if time.Since(start) >= time.Second {
|
|
t.Fatalf("local settings did not reach %q present=%t while first RPC was blocked (last read err=%v)", contains, present, err)
|
|
}
|
|
time.Sleep(5 * time.Millisecond)
|
|
}
|
|
}
|
|
|
|
add := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, addData) })
|
|
expectCall("add " + client.Email)
|
|
start := time.Now()
|
|
locked := make(chan time.Duration, 1)
|
|
wg.Go(func() {
|
|
start := time.Now()
|
|
lockInbound(ib.Id).Unlock()
|
|
locked <- time.Since(start)
|
|
})
|
|
select {
|
|
case took := <-locked:
|
|
t.Logf("inbound mutation lock acquired in %s while first RPC was blocked", took)
|
|
case <-time.After(time.Second):
|
|
t.Fatal("first RPC still holds the inbound mutation lock")
|
|
}
|
|
writerStart := time.Now()
|
|
if err := runSerializedTx(func(*gorm.DB) error { return nil }); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Logf("independent writer turn took %s while first RPC was blocked", time.Since(writerStart))
|
|
update := async(func() (bool, error) { return clientSvc.UpdateInboundClient(inboundSvc, updateData, client.Email) })
|
|
waitSettings(ib.Id, changed.Comment, true)
|
|
detach := async(func() (bool, error) {
|
|
return clientSvc.DelInboundClientByEmail(inboundSvc, ib.Id, client.Email, true, false)
|
|
})
|
|
waitSettings(ib.Id, client.Email, false)
|
|
sameNodeDone := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, siblingData) })
|
|
waitSettings(siblingInbound.Id, sameNode.Email, true)
|
|
controlDone := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, controlData) })
|
|
select {
|
|
case err := <-controlDone:
|
|
if err != nil || control.addClient.Load() != 1 {
|
|
t.Fatalf("control inbound did not complete independently: %v (pushes=%d)", err, control.addClient.Load())
|
|
}
|
|
case <-time.After(time.Second):
|
|
t.Fatal("control inbound waited for unrelated node")
|
|
}
|
|
select {
|
|
case got := <-blocked.calls:
|
|
t.Fatalf("%q overtook the first RPC", got)
|
|
default:
|
|
}
|
|
unblock()
|
|
expectCall("update " + client.Email + " " + changed.Comment)
|
|
t.Logf("first RPC held its dispatch turn for %s", time.Since(start))
|
|
if tc.timeout && !blocked.expired.Load() {
|
|
t.Fatal("the first push did not finish through its deadline")
|
|
}
|
|
expectCall("detach " + client.Email)
|
|
expectCall("add " + sameNode.Email)
|
|
for i, done := range []<-chan error{add, update, detach, sameNodeDone} {
|
|
select {
|
|
case err := <-done:
|
|
if err != nil {
|
|
t.Fatal(fmt.Errorf("operation %d reported %w after commit", i, err))
|
|
}
|
|
case <-time.After(time.Second):
|
|
t.Fatalf("operation %d did not complete", i)
|
|
}
|
|
}
|
|
if _, _, dirty, _, err := (&NodeService{}).NodeSyncState(nodeID); err != nil || !dirty {
|
|
t.Fatalf("node dirty=%t error=%v after committed client batch", dirty, err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestTrafficDepletionWaitsForEarlierNodeClientPush(t *testing.T) {
|
|
setupClientNodeOrderDB(t)
|
|
nodeID, _ := setupNodeRuntime(t)
|
|
mgr := runtime.GetManager()
|
|
release := make(chan struct{})
|
|
unblock := sync.OnceFunc(func() { close(release) })
|
|
const email = "depleted-while-pushing@example.test"
|
|
blocked := &blockedClientPushRuntime{calls: make(chan string, 4), release: release, blockedEmail: email}
|
|
mgr.SetRuntimeOverride(nodeID, blocked)
|
|
ib := nodeInbound(t, nodeID, 46012, nil)
|
|
inboundSvc := &InboundService{}
|
|
client := model.Client{Email: email, ID: uuid.NewString(), Enable: true, TotalGB: 5}
|
|
add := &model.Inbound{Id: ib.Id, Protocol: ib.Protocol, Settings: clientsSettings(t, []model.Client{client})}
|
|
var wg sync.WaitGroup
|
|
t.Cleanup(func() {
|
|
unblock()
|
|
wg.Wait()
|
|
})
|
|
addDone := make(chan error, 1)
|
|
wg.Go(func() {
|
|
_, err := (&ClientService{}).AddInboundClient(inboundSvc, add)
|
|
addDone <- err
|
|
})
|
|
select {
|
|
case got := <-blocked.calls:
|
|
if got != "add "+client.Email {
|
|
t.Fatalf("first node operation = %q", got)
|
|
}
|
|
case <-time.After(3 * time.Second):
|
|
t.Fatal("node did not receive the add")
|
|
}
|
|
depletionDone := make(chan error, 1)
|
|
wg.Go(func() {
|
|
_, disabled, err := inboundSvc.AddTraffic(nil, []*xray.ClientTraffic{{Email: client.Email, Up: 10}})
|
|
if !disabled {
|
|
err = errors.Join(err, errors.New("traffic did not disable the depleted client"))
|
|
}
|
|
depletionDone <- err
|
|
})
|
|
deadline := time.Now().Add(time.Second)
|
|
for readTraffic(t, database.GetDB(), client.Email).Enable {
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("depletion did not commit while the add was blocked")
|
|
}
|
|
time.Sleep(5 * time.Millisecond)
|
|
}
|
|
select {
|
|
case got := <-blocked.calls:
|
|
t.Fatalf("node operation %q overtook the pending add", got)
|
|
case <-time.After(100 * time.Millisecond):
|
|
}
|
|
unblock()
|
|
select {
|
|
case got := <-blocked.calls:
|
|
if got != "lifecycle "+ib.Tag {
|
|
t.Fatalf("second node operation = %q, want the depletion update", got)
|
|
}
|
|
case <-time.After(time.Second):
|
|
t.Fatal("node did not receive the depletion update")
|
|
}
|
|
for _, done := range []<-chan error{addDone, depletionDone} {
|
|
if err := waitTrafficWriterErr(t, done); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestReconcileDoesNotOvertakeCommittedClientState(t *testing.T) {
|
|
setupClientNodeOrderDB(t)
|
|
mgr := useTestRuntimeManager(t)
|
|
const tag = "in-46011"
|
|
listStarted := make(chan struct{})
|
|
releaseList := make(chan struct{})
|
|
release := sync.OnceFunc(func() { close(releaseList) })
|
|
var lists atomic.Int32
|
|
pushedSettings := make(chan string, 4)
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
var obj any
|
|
switch r.URL.Path {
|
|
case "/panel/api/inbounds/list":
|
|
if lists.Add(1) == 1 {
|
|
close(listStarted)
|
|
select {
|
|
case <-r.Context().Done():
|
|
return
|
|
case <-releaseList:
|
|
}
|
|
}
|
|
obj = []map[string]any{{"id": 1, "tag": tag}}
|
|
case "/panel/api/inbounds/update/1":
|
|
if err := r.ParseForm(); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
pushedSettings <- r.Form.Get("settings")
|
|
default:
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": obj})
|
|
}))
|
|
t.Cleanup(server.Close)
|
|
t.Cleanup(release)
|
|
|
|
node := reconcileTestNode(t, server, "reconcile-overlap", "all", nil)
|
|
remote := runtime.NewRemote(node, nil)
|
|
fast := &fakeNodeRuntime{}
|
|
mgr.SetRuntimeOverride(node.Id, fast)
|
|
ib := nodeInbound(t, node.Id, 46011, nil)
|
|
clientSvc, inboundSvc, nodeSvc := &ClientService{}, &InboundService{}, &NodeService{}
|
|
// Exercise generation ordering even when the previous timestamp is ahead of the clock.
|
|
oldGeneration := time.Now().Add(time.Minute).UnixMilli()
|
|
if err := database.GetDB().Model(node).Updates(map[string]any{
|
|
"config_dirty": true, "config_dirty_at": oldGeneration,
|
|
}).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
|
|
defer cancel()
|
|
reconciled := make(chan error, 1)
|
|
go func() { reconciled <- inboundSvc.ReconcileNode(ctx, remote, node) }()
|
|
waitTrafficWriterSignal(t, listStarted, "reconcile never reached the remote list")
|
|
|
|
client := model.Client{Email: "during-reconcile@example.test", ID: uuid.NewString(), Enable: true}
|
|
if needRestart, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{
|
|
Id: ib.Id, Protocol: ib.Protocol, Settings: clientsSettings(t, []model.Client{client}),
|
|
}); needRestart || err != nil {
|
|
t.Fatalf("add during reconcile: restart=%t err=%v", needRestart, err)
|
|
}
|
|
if got := fast.addClient.Load(); got != 0 {
|
|
t.Fatalf("%d incremental pushes overlapped a reconcile of older settings", got)
|
|
}
|
|
release()
|
|
if err := waitTrafficWriterErr(t, reconciled); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
select {
|
|
case pushed := <-pushedSettings:
|
|
if strings.Contains(pushed, client.Email) {
|
|
t.Fatalf("first reconcile should still carry the pre-add settings, got %s", pushed)
|
|
}
|
|
default:
|
|
t.Fatal("first reconcile did not push the captured configuration")
|
|
}
|
|
|
|
if err := nodeSvc.ClearNodeDirty(node.Id, oldGeneration); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
_, _, dirty, generation, err := nodeSvc.NodeSyncState(node.Id)
|
|
if err != nil || !dirty || generation <= oldGeneration {
|
|
t.Fatalf("new generation lost after stale reconcile: dirty=%t generation=%d previous=%d err=%v", dirty, generation, oldGeneration, err)
|
|
}
|
|
if err := inboundSvc.ReconcileNode(ctx, remote, node); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
select {
|
|
case pushed := <-pushedSettings:
|
|
if !strings.Contains(pushed, client.Email) {
|
|
t.Fatalf("next reconcile did not deliver the committed client: %s", pushed)
|
|
}
|
|
default:
|
|
t.Fatal("next reconcile did not push the new configuration")
|
|
}
|
|
}
|
|
|
|
func TestNodeWideDeleteInvalidatesSettingsSentByQueuedReconcile(t *testing.T) {
|
|
setupClientNodeOrderDB(t)
|
|
mgr := useTestRuntimeManager(t)
|
|
const primaryTag, blockerTag = "in-46013", "in-46014"
|
|
const email = "recreated@example.test"
|
|
firstPush := make(chan struct{})
|
|
releaseFirstPush := make(chan struct{})
|
|
release := sync.OnceFunc(func() { close(releaseFirstPush) })
|
|
var hasClient atomic.Bool
|
|
hasClient.Store(true)
|
|
var adds, deletes atomic.Int32
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
var obj any
|
|
switch r.URL.Path {
|
|
case "/panel/api/inbounds/list":
|
|
obj = []map[string]any{{"id": 1, "tag": primaryTag}, {"id": 2, "tag": blockerTag}}
|
|
case "/panel/api/clients/add":
|
|
if adds.Add(1) == 1 {
|
|
close(firstPush)
|
|
select {
|
|
case <-r.Context().Done():
|
|
return
|
|
case <-releaseFirstPush:
|
|
}
|
|
}
|
|
case "/panel/api/inbounds/update/1":
|
|
if err := r.ParseForm(); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
hasClient.Store(strings.Contains(r.Form.Get("settings"), "recreated configuration"))
|
|
case "/panel/api/inbounds/update/2":
|
|
case "/panel/api/clients/del/" + email:
|
|
deletes.Add(1)
|
|
hasClient.Store(false)
|
|
default:
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": obj})
|
|
}))
|
|
t.Cleanup(server.Close)
|
|
var wg sync.WaitGroup
|
|
t.Cleanup(func() {
|
|
release()
|
|
wg.Wait()
|
|
})
|
|
|
|
node := reconcileTestNode(t, server, "reconcile-full-delete", "all", nil)
|
|
remote := runtime.NewRemote(node, nil)
|
|
mgr.SetRuntimeOverride(node.Id, remote)
|
|
client := model.Client{Email: email, ID: uuid.NewString(), SubID: "reconcile-recreated", Enable: true}
|
|
inbound := nodeInbound(t, node.Id, 46013, []model.Client{client})
|
|
blocker := nodeInbound(t, node.Id, 46014, nil)
|
|
inboundSvc, clientSvc := &InboundService{}, &ClientService{}
|
|
addPayload := &model.Inbound{Id: blocker.Id, Protocol: model.VLESS, Settings: clientsSettings(t, []model.Client{{
|
|
Email: "first-push@example.test", ID: uuid.NewString(), Enable: true,
|
|
}})}
|
|
async := func(run func() error) <-chan error {
|
|
done := make(chan error, 1)
|
|
wg.Go(func() { done <- run() })
|
|
return done
|
|
}
|
|
waitUntil := func(message string, ready func() bool) {
|
|
t.Helper()
|
|
deadline := time.Now().Add(time.Second)
|
|
for !ready() {
|
|
if time.Now().After(deadline) {
|
|
t.Fatal(message)
|
|
}
|
|
time.Sleep(5 * time.Millisecond)
|
|
}
|
|
}
|
|
|
|
added := async(func() error {
|
|
_, err := clientSvc.AddInboundClient(inboundSvc, addPayload)
|
|
return err
|
|
})
|
|
waitTrafficWriterSignal(t, firstPush, "first AddClient never reached the node")
|
|
ctx, cancel := context.WithTimeout(t.Context(), 6*time.Second)
|
|
defer cancel()
|
|
reconciled := async(func() error { return inboundSvc.ReconcileNode(ctx, remote, node) })
|
|
waitUntil("reconcile did not queue behind the first add", func() bool {
|
|
nodeConfigDispatchMu.Lock()
|
|
defer nodeConfigDispatchMu.Unlock()
|
|
queue := nodeConfigDispatch[node.Id]
|
|
return queue != nil && queue.reconciles > 0
|
|
})
|
|
deleted := async(func() error {
|
|
_, err := clientSvc.DelInboundClientByEmail(inboundSvc, inbound.Id, email, true, true)
|
|
return err
|
|
})
|
|
waitUntil("full delete did not commit behind the reconcile", func() bool {
|
|
current, err := inboundSvc.GetInbound(inbound.Id)
|
|
return err == nil && !strings.Contains(current.Settings, email)
|
|
})
|
|
client.Comment = "recreated configuration"
|
|
if _, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{
|
|
Id: inbound.Id, Protocol: inbound.Protocol, Settings: clientsSettings(t, []model.Client{client}),
|
|
}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
release()
|
|
for _, done := range []<-chan error{added, reconciled, deleted} {
|
|
if err := waitTrafficWriterErr(t, done); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if adds.Load() != 1 || deletes.Load() != 1 || hasClient.Load() {
|
|
t.Fatalf("expected one add then reconcile and full delete, got adds=%d deletes=%d client=%t", adds.Load(), deletes.Load(), hasClient.Load())
|
|
}
|
|
if err := inboundSvc.ReconcileNode(ctx, remote, node); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !hasClient.Load() {
|
|
t.Fatal("stale fingerprint caused reconcile to skip restoring the recreated client")
|
|
}
|
|
}
|