mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-03 16:04:50 +03:00
1e1b32247e
Reduce repeated inbound settings materialization with a protocol-aware preparation projection that retains node_id. Reuse the locked validation/mutation snapshot while preserving the transaction-time settings reread and three-way rebase. Gate effective Create/Attach Flow before grouped payload construction; retain public Add and bulk/copy semantics.
Preserve #7367 grouped Create, intended-payload fingerprint CAS, ordered turns, cancellation, metadata ordering, durable delete/reattachment safeguards, node outcomes and PostgreSQL lock ordering. Add a mandatory PostgreSQL gate for nine read/protocol regressions without weakening the existing 21 ordering/grouped-create cases.
Validation: all 12 CI jobs passed on 9062e5cf94 (run 46971334865), including PostgreSQL 9/9 and 21/21 focused gates, race, and all four version pairings. Author-reported paired PostgreSQL 16 fixture: 44 -> 22 full reads, 64.82 -> 32.41 MiB materialized per local Create, p95 497.0 -> 400.9 ms; contended Create p95 994.2 -> 633.5 ms and Update 1118.4 -> 937.5 ms. Single-node grouped Create stays one RPC. Necessary protocol/Flow reads and Attach preparation remain; no WAL redesign or production latency claim.
Refs #7300
287 lines
10 KiB
Go
287 lines
10 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"slices"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
|
)
|
|
|
|
func TestSlimCreateUsesLockedFlowForGroupedDelivery(t *testing.T) {
|
|
peer, _, inbounds, _ := setupGroupedCreatePeer(t)
|
|
db := database.GetDB()
|
|
first, second := inbounds[0], inbounds[1]
|
|
const tls = `{"network":"tcp","security":"tls"}`
|
|
const reality = `{"network":"tcp","security":"reality"}`
|
|
if err := db.Model(first).Update("stream_settings", tls).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
third := nodeInbound(t, *first.NodeID, 46203, nil)
|
|
peer.tags[third.Tag] = 103
|
|
peer.settings[103] = third.Settings
|
|
if err := db.Model(third).Update("settings", `{"clients":[],"decryption":"mlkem768x25519plus.native.0rtt.test"}`).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var disableFirst, enableSecond sync.Once
|
|
const hook = "test:flow-changes-after-create-preparation-read"
|
|
query := db.Callback().Query()
|
|
if err := query.After("gorm:query").Register(hook, func(tx *gorm.DB) {
|
|
ib, ok := tx.Statement.Dest.(*model.Inbound)
|
|
if !ok || tx.Error != nil {
|
|
return
|
|
}
|
|
switch ib.Id {
|
|
case first.Id:
|
|
disableFirst.Do(func() { _ = tx.AddError(db.Model(first).Update("disable_flow", true).Error) })
|
|
case second.Id:
|
|
enableSecond.Do(func() { _ = tx.AddError(db.Model(second).Update("stream_settings", reality).Error) })
|
|
}
|
|
}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = query.Remove(hook) })
|
|
|
|
const flow = "xtls-rprx-vision"
|
|
client := groupedRecoveryClient("locked-flow@x")
|
|
client.Flow = flow
|
|
if _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{
|
|
Client: client, InboundIds: []int{first.Id, second.Id, third.Id},
|
|
}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
peer.mu.Lock()
|
|
calls := slices.Clone(peer.adds)
|
|
peer.mu.Unlock()
|
|
slices.SortFunc(calls, func(a, b ClientCreatePayload) int { return a.InboundIds[0] - b.InboundIds[0] })
|
|
if len(calls) != 2 || !slices.Equal(calls[0].InboundIds, []int{101}) || calls[0].Client.Flow != "" ||
|
|
!slices.Equal(calls[1].InboundIds, []int{102, 103}) || calls[1].Client.Flow != flow {
|
|
t.Fatalf("peer received %+v, want no flow on 101 and Vision on 102/103", calls)
|
|
}
|
|
for _, ib := range []*model.Inbound{first, second, third} {
|
|
want := flow
|
|
if ib.Id == first.Id {
|
|
want = ""
|
|
}
|
|
if c, ok := settingsClient(t, ib.Id, client.Email); !ok || c.Flow != want {
|
|
t.Fatalf("stored flow for inbound %d = %q, want %q", ib.Id, c.Flow, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestSlimCreateHealthyTargetsProgressWithBlockedPeer(t *testing.T) {
|
|
slow, node, slowTargets, _ := setupGroupedCreatePeer(t)
|
|
healthy := newFakeNodeHTTP(t)
|
|
firstHealthy := realNodeInbound(t, healthy, 46321, nil)
|
|
secondHealthy := nodeInbound(t, *firstHealthy.NodeID, 46322, nil)
|
|
healthy.tags[secondHealthy.Tag] = 122
|
|
for i := range 2 {
|
|
ib := nodeInbound(t, node.Id, 46331+i, nil)
|
|
slow.tags[ib.Tag] = 131 + i
|
|
slow.settings[131+i] = ib.Settings
|
|
slowTargets = append(slowTargets, ib)
|
|
}
|
|
var ids []int
|
|
var locks []*inboundMutationLock
|
|
for _, ib := range slowTargets {
|
|
ids = append(ids, ib.Id)
|
|
locks = append(locks, lockInbound(ib.Id))
|
|
}
|
|
releaseLocks := sync.OnceFunc(func() {
|
|
for _, lock := range locks {
|
|
lock.Unlock()
|
|
}
|
|
})
|
|
ids = append(ids, firstHealthy.Id, secondHealthy.Id)
|
|
healthySent := make(chan struct{})
|
|
releaseRPC := sync.OnceFunc(func() { close(healthySent) })
|
|
slow.respond = func(w http.ResponseWriter, r *http.Request, payload ClientCreatePayload, apply func(int)) {
|
|
select {
|
|
case <-healthySent:
|
|
case <-r.Context().Done():
|
|
return
|
|
}
|
|
apply(len(payload.InboundIds))
|
|
_, _ = w.Write([]byte(`{"success":true}`))
|
|
}
|
|
saved := make(chan int, 2)
|
|
db := database.GetDB()
|
|
const hook = "test:healthy-inbound-write-while-other-inbounds-block"
|
|
updates := db.Callback().Update()
|
|
if err := updates.After("gorm:update").Register(hook, func(tx *gorm.DB) {
|
|
if tx.Statement.Table == "inbounds" && len(tx.Statement.Vars) == 2 {
|
|
if id, ok := tx.Statement.Vars[1].(int); ok && (id == firstHealthy.Id || id == secondHealthy.Id) {
|
|
saved <- id
|
|
}
|
|
}
|
|
}); err != nil {
|
|
releaseLocks()
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = updates.Remove(hook) })
|
|
ctx, cancel := context.WithCancel(t.Context())
|
|
done := make(chan struct{})
|
|
svc := (&ClientService{}).TrackNodeApplies()
|
|
var createErr error
|
|
t.Cleanup(func() { releaseLocks(); releaseRPC(); cancel(); <-done })
|
|
go func() {
|
|
defer close(done)
|
|
_, createErr = svc.CreateWithContext(ctx, &InboundService{}, &ClientCreatePayload{
|
|
Client: groupedRecoveryClient("healthy-node@x"), InboundIds: ids,
|
|
})
|
|
}()
|
|
deadline := time.After(3 * time.Second)
|
|
seen := make(map[int]bool)
|
|
for range 2 {
|
|
select {
|
|
case id := <-saved:
|
|
seen[id] = true
|
|
case <-deadline:
|
|
t.Fatalf("healthy node's writes waited for parked lanes: %v", seen)
|
|
}
|
|
}
|
|
if len(seen) != 2 {
|
|
t.Fatalf("healthy writes seen = %v", seen)
|
|
}
|
|
if err := submitTrafficWrite(func() error { return nil }); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
releaseLocks()
|
|
select {
|
|
case call := <-healthy.clientAddEvents:
|
|
if !slices.Equal(call.InboundIds, []int{121, 122}) {
|
|
t.Fatalf("healthy peer received IDs %v, want 121 and 122 together", call.InboundIds)
|
|
}
|
|
case <-time.After(3 * time.Second):
|
|
t.Fatal("healthy peer waited for the slow peer's RPC")
|
|
}
|
|
releaseRPC()
|
|
select {
|
|
case <-done:
|
|
if createErr != nil {
|
|
t.Fatal(createErr)
|
|
}
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("create did not return")
|
|
}
|
|
result := svc.NodeApplyResponse()
|
|
want := []ClientNodeApplyOutcome{{NodeID: node.Id, Status: "applied"}, {NodeID: *firstHealthy.NodeID, Status: "applied"}}
|
|
if result == nil || result.NodePending || !slices.Equal(result.NodeResults, want) {
|
|
t.Fatalf("node outcomes = %+v, want %v", result, want)
|
|
}
|
|
}
|
|
|
|
func TestSlimCreateProjectionPreservesNodeIDAndProtocolSettings(t *testing.T) {
|
|
setupClientNodeOrderDB(t)
|
|
fake := newFakeNodeHTTP(t)
|
|
remote := realNodeInbound(t, fake, 46341, nil)
|
|
local := seedInboundSettingsReadTest(t, 46342, model.VLESS, `{"clients":[]}`)
|
|
mtproto := seedInboundSettingsReadTest(t, 46343, model.MTProto, `{"clients":[],"fakeTlsDomain":"front.example.test"}`)
|
|
for _, tc := range []struct {
|
|
inbound *model.Inbound
|
|
generate bool
|
|
settings string
|
|
}{
|
|
{inbound: remote},
|
|
{inbound: local},
|
|
{inbound: mtproto, generate: true, settings: mtproto.Settings},
|
|
{inbound: mtproto},
|
|
} {
|
|
got, err := getInboundForClientPreparation(tc.inbound.Id, tc.generate)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var nodeID, wantNodeID int
|
|
if got.NodeID != nil {
|
|
nodeID = *got.NodeID
|
|
}
|
|
if tc.inbound.NodeID != nil {
|
|
wantNodeID = *tc.inbound.NodeID
|
|
}
|
|
if got.Id != tc.inbound.Id || nodeID != wantNodeID || got.Protocol != tc.inbound.Protocol ||
|
|
got.Enable != tc.inbound.Enable || got.Listen != tc.inbound.Listen || got.Settings != tc.settings {
|
|
t.Fatalf("projection id=%d node=%d protocol=%s settings bytes=%d, want id=%d node=%d protocol=%s settings bytes=%d",
|
|
got.Id, nodeID, got.Protocol, len(got.Settings), tc.inbound.Id, wantNodeID, tc.inbound.Protocol, len(tc.settings))
|
|
}
|
|
}
|
|
secret := model.GenerateFakeTLSSecret("supplied.example.test")
|
|
const email = "preserve-supplied-secret@x"
|
|
if _, err := (&ClientService{}).CreateOne(&InboundService{}, mtproto.Id, model.Client{Email: email, Secret: secret}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if c, ok := settingsClient(t, mtproto.Id, email); !ok || c.Secret != secret {
|
|
t.Fatal("create regenerated the supplied MTProto secret")
|
|
}
|
|
}
|
|
|
|
func TestSlimAttachUsesLockedFlowAndPreservesRawAdd(t *testing.T) {
|
|
setupClientNodeOrderDB(t)
|
|
db := database.GetDB()
|
|
inboundSvc, svc := &InboundService{}, &ClientService{}
|
|
client := groupedRecoveryClient("attach-flow@x")
|
|
client.Flow = "xtls-rprx-vision"
|
|
source := seedInboundSettingsReadTest(t, 46351, model.VLESS, clientsSettings(t, []model.Client{client}))
|
|
if err := svc.SyncInbound(nil, source.Id, []model.Client{client}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
target := seedInboundSettingsReadTest(t, 46352, model.VLESS, `{"clients":[]}`)
|
|
if err := db.Model(target).Update("stream_settings", `{"network":"tcp","security":"tls"}`).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
query := db.Callback().Query()
|
|
const hook = "test:disable-flow-after-attach-preparation-read"
|
|
var disable sync.Once
|
|
if err := query.After("gorm:query").Register(hook, func(tx *gorm.DB) {
|
|
if ib, ok := tx.Statement.Dest.(*model.Inbound); ok && ib.Id == target.Id && tx.Error == nil {
|
|
disable.Do(func() { _ = tx.AddError(db.Model(target).Update("disable_flow", true).Error) })
|
|
}
|
|
}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = query.Remove(hook) })
|
|
if _, err := svc.AttachByEmail(inboundSvc, client.Email, []int{target.Id}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if c, ok := settingsClient(t, target.Id, client.Email); !ok || c.Flow != "" {
|
|
t.Fatalf("attach retained stale flow %q", c.Flow)
|
|
}
|
|
client.Email, client.SubID, client.ID = "legacy-add@x", "legacy-add", "aaaaaaaa-1111-2222-3333-555555555555"
|
|
if _, err := svc.AddInboundClient(inboundSvc, &model.Inbound{
|
|
Id: target.Id, Settings: clientsSettings(t, []model.Client{client}),
|
|
}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if c, ok := settingsClient(t, target.Id, client.Email); !ok || c.Flow != client.Flow {
|
|
t.Fatalf("raw AddInboundClient changed its caller-owned flow to %q", c.Flow)
|
|
}
|
|
}
|
|
|
|
func TestSlimUpdateRebasesConcurrentSettings(t *testing.T) {
|
|
setupClientNodeOrderDB(t)
|
|
ib := seedRenewableNeighbour(t, 46361, nil)
|
|
record := lookupClientRecord(t, "x@stale")
|
|
current := record.ToClient()
|
|
current.Comment = "updated alongside renewal"
|
|
reads := trackInboundSettingsReads(t)
|
|
var editErr error
|
|
commitTickBetweenReadAndWrite(t, renewYTick(ib.Id), func() {
|
|
_, editErr = (&ClientService{}).Update(&InboundService{}, record.Id, *current, 0)
|
|
})
|
|
if editErr != nil {
|
|
t.Fatal(editErr)
|
|
}
|
|
if len(reads.sizes) != 4 || reads.sizes[0] != 0 || reads.sizes[1] == 0 || reads.sizes[2] == 0 || reads.sizes[3] == 0 {
|
|
t.Fatalf("update settings reads = %v, want empty preparation plus full locked, renewal and transactional reads", reads.sizes)
|
|
}
|
|
requireNeighbourRenewed(t, ib.Id)
|
|
if saved, ok := settingsClient(t, ib.Id, current.Email); !ok || saved.Comment != current.Comment {
|
|
t.Fatalf("update lost the edited comment: %+v", saved)
|
|
}
|
|
}
|