perf(clients): avoid repeated inbound settings reads (#7312)

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
This commit is contained in:
Hamed
2026-12-03 00:56:57 +03:30
committed by GitHub
parent 91d5ff400d
commit 1e1b32247e
6 changed files with 524 additions and 29 deletions
+10
View File
@@ -165,6 +165,16 @@ jobs:
exit 1
fi
- name: PostgreSQL client inbound read regressions
run: |
set -o pipefail
go test ./internal/web/service -run '^Test(ClientCreate(ReadsInboundSettingsOnlyForMutation|ClearsFlowOnIneligibleInbound|PreservesSettingsBasedDefaults)|UpdateInboundClientReadsSettingsOnceBeforeCommit|Slim(Create(UsesLockedFlowForGroupedDelivery|HealthyTargetsProgressWithBlockedPeer|ProjectionPreservesNodeIDAndProtocolSettings)|AttachUsesLockedFlowAndPreservesRawAdd|UpdateRebasesConcurrentSettings))$' -count=1 -v | tee /tmp/postgres-client-inbound-reads.log
passed=$(grep -c -- '^--- PASS' /tmp/postgres-client-inbound-reads.log || true)
if [ "$passed" -ne 9 ]; then
echo "expected 9 passing PostgreSQL client inbound read tests, got $passed" >&2
exit 1
fi
- name: PostgreSQL global-traffic heartbeat regressions
run: |
set -o pipefail
@@ -0,0 +1,286 @@
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)
}
}
@@ -0,0 +1,174 @@
package service
import (
"encoding/hex"
"fmt"
"slices"
"strings"
"sync"
"testing"
"time"
"gorm.io/gorm"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
type inboundSettingsReads struct {
mu sync.Mutex
sizes []int
}
func trackInboundSettingsReads(t testing.TB) *inboundSettingsReads {
t.Helper()
reads := &inboundSettingsReads{}
query := database.GetDB().Callback().Query()
const name = "test:track_client_inbound_settings"
if err := query.After("gorm:query").Register(name, func(tx *gorm.DB) {
if tx.Statement.Table != "inbounds" || tx.Error != nil {
return
}
projection, _, _ := strings.Cut(tx.Statement.SQL.String(), " FROM ")
if !strings.Contains(projection, "settings") && !strings.Contains(projection, "*") {
return
}
reads.mu.Lock()
defer reads.mu.Unlock()
switch dest := tx.Statement.Dest.(type) {
case *model.Inbound:
reads.sizes = append(reads.sizes, len(dest.Settings))
case *[]string:
for _, settings := range *dest {
reads.sizes = append(reads.sizes, len(settings))
}
}
}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := query.Remove(name); err != nil {
t.Error(err)
}
})
return reads
}
func seedInboundSettingsReadTest(t *testing.T, port int, protocol model.Protocol, settings string) *model.Inbound {
t.Helper()
ib := &model.Inbound{Tag: fmt.Sprintf("settings-reads-%d", port), Enable: true, Port: port, Protocol: protocol, Settings: settings}
if err := database.GetDB().Create(ib).Error; err != nil {
t.Fatal(err)
}
return ib
}
func TestClientCreateReadsInboundSettingsOnlyForMutation(t *testing.T) {
setupBulkDB(t)
const flow = "xtls-rprx-vision"
ib := seedInboundSettingsReadTest(t, 23121, model.VLESS, `{"clients":[],"decryption":"mlkem768x25519plus.native.0rtt.test"}`)
reads := trackInboundSettingsReads(t)
if _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{
InboundIds: []int{ib.Id},
Client: model.Client{Email: "create-reads@example.test", Flow: flow},
}); err != nil {
t.Fatal(err)
}
want := []int{0, len(ib.Settings), len(ib.Settings)}
if !slices.Equal(reads.sizes, want) {
t.Fatalf("inbound settings bytes by read = %v, want %v (preparation, locked read, transaction guard)", reads.sizes, want)
}
if client, found := settingsClient(t, ib.Id, "create-reads@example.test"); !found || client.Flow != flow {
t.Fatalf("encrypted VLESS inbound saved flow %q, want %q", client.Flow, flow)
}
}
func TestClientCreateClearsFlowOnIneligibleInbound(t *testing.T) {
setupBulkDB(t)
ib := seedInboundSettingsReadTest(t, 23123, model.VLESS, `{"clients":[],"decryption":"none"}`)
if _, err := (&ClientService{}).CreateOne(&InboundService{}, ib.Id, model.Client{
Email: "create-noflow@example.test", Flow: "xtls-rprx-vision",
}); err != nil {
t.Fatal(err)
}
if client, found := settingsClient(t, ib.Id, "create-noflow@example.test"); !found || client.Flow != "" {
t.Fatalf("ineligible VLESS inbound has client=%v with flow %q, want client without flow", found, client.Flow)
}
}
func TestClientCreatePreservesSettingsBasedDefaults(t *testing.T) {
setupBulkDB(t)
const method = "2022-blake3-aes-256-gcm"
const domain = "front.example.test"
ss := seedInboundSettingsReadTest(t, 23124, model.Shadowsocks, `{"clients":[],"method":"`+method+`","password":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="}`)
mt := seedInboundSettingsReadTest(t, 23125, model.MTProto, `{"clients":[],"fakeTlsDomain":"`+domain+`"}`)
const email = "create-defaults@example.test"
if _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{
InboundIds: []int{ss.Id, mt.Id},
Client: model.Client{Email: email},
}); err != nil {
t.Fatal(err)
}
if client, found := settingsClient(t, ss.Id, email); !found || !validShadowsocksClientKey(method, client.Password) {
t.Fatalf("Shadowsocks client found=%v, want a valid %s key", found, method)
}
if client, found := settingsClient(t, mt.Id, email); !found || !model.ValidMtprotoSecret(client.Secret) ||
!strings.HasSuffix(client.Secret, hex.EncodeToString([]byte(domain))) {
t.Fatalf("MTProto client found=%v, want a valid FakeTLS secret for %s", found, domain)
}
}
func TestUpdateInboundClientReadsSettingsOnceBeforeCommit(t *testing.T) {
setupBulkDB(t)
svc, inbounds := &ClientService{}, &InboundService{}
client := model.Client{Email: "update-reads@example.test", ID: "225452da-1385-4a1c-84ab-05481e000001", SubID: "update-reads"}
ib := seedInboundSettingsReadTest(t, 23122, model.VLESS, clientsSettings(t, []model.Client{client}))
if err := svc.SyncInbound(nil, ib.Id, []model.Client{client}); err != nil {
t.Fatal(err)
}
reads := trackInboundSettingsReads(t)
client.Comment = "changed"
if _, err := svc.UpdateInboundClient(inbounds, &model.Inbound{
Id: ib.Id, Settings: clientsSettings(t, []model.Client{client}),
}, client.Email); err != nil {
t.Fatal(err)
}
want := []int{len(ib.Settings), len(ib.Settings)}
if !slices.Equal(reads.sizes, want) {
t.Fatalf("inbound settings bytes by read = %v, want %v (locked read, transaction guard)", reads.sizes, want)
}
}
func BenchmarkClientCreateLargeInboundSettings(b *testing.B) {
setupScaleDB(b)
const inbounds, clientsPerInbound = 11, 4000
data := seedScaleDataset(b, inbounds*clientsPerInbound, inbounds)
svc, inboundSvc := &ClientService{}, &InboundService{}
reads := trackInboundSettingsReads(b)
var times []time.Duration
for b.Loop() {
payload := &ClientCreatePayload{
InboundIds: data.inboundIds,
Client: model.Client{Email: fmt.Sprintf("add-%d@example.test", len(times))},
}
start := time.Now()
if _, err := svc.Create(inboundSvc, payload); err != nil {
b.Fatal(err)
}
times = append(times, time.Since(start))
}
slices.Sort(times)
b.ReportMetric(float64(times[(95*len(times)+99)/100-1].Microseconds())/1000, "p95-ms")
bytes, blobs := 0, 0
for _, size := range reads.sizes {
bytes += size
if size > 0 {
blobs++
}
}
b.ReportMetric(float64(len(reads.sizes))/float64(b.N), "inbound-projections/op")
b.ReportMetric(float64(bytes)/float64(b.N), "settings-bytes/op")
b.ReportMetric(float64(blobs)/float64(b.N), "settings-reads/op")
}
@@ -10,7 +10,6 @@ import (
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
@@ -439,13 +438,16 @@ func TestGroupedCreateReconcilesUnsentRebasedSettings(t *testing.T) {
ID: "bbbbbbbb-1111-2222-3333-555555555555", SubID: "group-rebased",
}
db := database.GetDB()
var reads atomic.Int32
var inject sync.Once
const callback = "test:concurrent-settings-before-grouped-write"
if err := db.Callback().Query().After("gorm:query").Register(callback, func(tx *gorm.DB) {
read, ok := tx.Statement.Dest.(*model.Inbound)
if ok && read.Id == changed.Id && reads.Add(1) == 3 {
_ = tx.AddError(db.Model(&model.Inbound{}).Where("id = ?", changed.Id).
Update("settings", `{"clients":[],"decryption":"none"}`).Error)
if ok && read.Id == changed.Id && read.Settings == changed.Settings {
// VLESS preparation omits settings. The first full read is under the mutation lock.
inject.Do(func() {
_ = tx.AddError(db.Model(&model.Inbound{}).Where("id = ?", changed.Id).
Update("settings", `{"clients":[],"decryption":"none"}`).Error)
})
}
}); err != nil {
t.Fatal(err)
+35 -9
View File
@@ -295,7 +295,7 @@ func (s *ClientService) CreateWithContext(ctx context.Context, inboundSvc *Inbou
// shared credentials on the first inbound and every later one reuses them.
adds := make([]*model.Inbound, 0, len(payload.InboundIds))
for _, ibId := range payload.InboundIds {
inbound, getErr := inboundSvc.GetInbound(ibId)
inbound, getErr := getInboundForClientPreparation(ibId, client.Secret == "")
if getErr != nil {
return false, fmt.Errorf("inbound %d: %w", ibId, getErr)
}
@@ -317,7 +317,7 @@ func (s *ClientService) CreateWithContext(ctx context.Context, inboundSvc *Inbou
if err := validateAmneziaWGClientWrite(inbound, []model.Client{clientForInbound}, ""); err != nil {
return false, fmt.Errorf("inbound %d: %w", ibId, err)
}
settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(clientForInbound, inbound)}})
settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientForInbound}})
if mErr != nil {
return false, fmt.Errorf("inbound %d: %w", ibId, mErr)
}
@@ -338,6 +338,23 @@ func (s *ClientService) CreateWithContext(ctx context.Context, inboundSvc *Inbou
return needRestart || remoteRestart, errors.Join(saveErr, pushErr)
}
// getInboundForClientPreparation returns the settings blob only for protocols
// that need it to prepare the client before any writes.
func getInboundForClientPreparation(id int, generateSecret bool) (*model.Inbound, error) {
protocolsWithSettings := []model.Protocol{model.Shadowsocks, model.AmneziaWG}
if generateSecret {
protocolsWithSettings = append(protocolsWithSettings, model.MTProto)
}
var inbound model.Inbound
if err := database.GetDB().Select(
"id, node_id, protocol, enable, listen, CASE WHEN protocol IN ? THEN settings ELSE '' END AS settings",
protocolsWithSettings,
).First(&inbound, id).Error; err != nil {
return nil, err
}
return &inbound, nil
}
// inboundFanoutConcurrency caps how many inbounds one client op applies at
// once, so a client spanning many of them can't start an unbounded RPC burst.
const inboundFanoutConcurrency = 4
@@ -396,7 +413,7 @@ func (s *ClientService) fanoutInboundClientAdds(inboundSvc *InboundService, adds
queued = &pushes[i]
}
applies = append(applies, inboundApply{id: add.Id, nodeID: add.NodeID, run: func() (bool, error) {
return s.addInboundClient(inboundSvc, add, queued)
return s.addInboundClient(inboundSvc, add, true, queued)
}})
}
return fanoutInboundApplies(applies)
@@ -603,7 +620,7 @@ func mtprotoDomainFromSettings(settings string) string {
}
func clientWithInboundFlow(c model.Client, ib *model.Inbound) model.Client {
if ib.DisableFlow || !inboundCanEnableTlsFlow(string(ib.Protocol), ib.StreamSettings, ib.Settings) {
if c.Flow != "" && (ib.DisableFlow || !inboundCanEnableTlsFlow(string(ib.Protocol), ib.StreamSettings, ib.Settings)) {
c.Flow = ""
}
return c
@@ -893,7 +910,18 @@ func (s *ClientService) update(inboundSvc *InboundService, id int, updated model
// mints the shared credentials on the first inbound, later ones reuse them.
applies := make([]inboundApply, 0, len(inboundIds))
for _, ibId := range inboundIds {
inbound, getErr := inboundSvc.GetInbound(ibId)
requestedFlow := updated.Flow
if keepInboundFlows {
requestedFlow = inboundFlows[ibId]
}
var inbound *model.Inbound
var getErr error
if requestedFlow == "" {
inbound, getErr = getInboundForClientPreparation(ibId, updated.Secret == "")
} else {
inbound, getErr = inboundSvc.GetInbound(ibId)
}
if getErr != nil {
if errors.Is(getErr, gorm.ErrRecordNotFound) {
if err := database.GetDB().
@@ -915,9 +943,7 @@ func (s *ClientService) update(inboundSvc *InboundService, id int, updated model
if inbound.Protocol == model.WireGuard && tunnelCount > 1 {
clientForInbound.WireguardDevices = nil
}
if keepInboundFlows {
clientForInbound.Flow = inboundFlows[ibId]
}
clientForInbound.Flow = requestedFlow
if ips, ok := updated.AllowedIPsByInbound[ibId]; ok {
clientForInbound.AllowedIPs = ips
} else if tunnelCount > 1 && (inbound.Protocol == model.WireGuard || inbound.Protocol == model.AmneziaWG) {
@@ -1332,7 +1358,7 @@ func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []
if err := s.fillProtocolDefaults(&copyClient, inbound); err != nil {
return false, fmt.Errorf("inbound %d: %w", ibId, err)
}
settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(copyClient, inbound)}})
settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {copyClient}})
if mErr != nil {
return false, fmt.Errorf("inbound %d: %w", ibId, mErr)
}
+12 -15
View File
@@ -397,10 +397,10 @@ func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, c
}
func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (restartNeeded bool, saveErr error) {
return s.addInboundClient(inboundSvc, data, nil)
return s.addInboundClient(inboundSvc, data, false, nil)
}
func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model.Inbound, queued *queuedClientCreate) (restartNeeded bool, saveErr error) {
func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model.Inbound, gateFlow bool, queued *queuedClientCreate) (restartNeeded bool, saveErr error) {
defer InvalidateSubData()
mutation := beginInboundClientMutation(data.Id)
defer mutation.close()
@@ -412,15 +412,15 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model
if err := validateClientsRenewal(clients); err != nil {
return false, err
}
inbound, err := inboundSvc.GetInbound(data.Id)
oldInbound, err := inboundSvc.GetInbound(data.Id)
if err != nil {
return false, err
}
existingClients, err := inboundSvc.GetClients(inbound)
existingClients, err := inboundSvc.GetClients(oldInbound)
if err != nil {
return false, err
}
if err := validateClientsKeepAliveAgainstExisting(inbound.Protocol, clients, existingClients); err != nil {
if err := validateClientsKeepAliveAgainstExisting(oldInbound.Protocol, clients, existingClients); err != nil {
return false, err
}
@@ -434,6 +434,11 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model
nowTs := time.Now().Unix() * 1000
for i := range interfaceClients {
if cm, ok := interfaceClients[i].(map[string]any); ok {
// Create and attach filter flow against the locked inbound snapshot.
if gateFlow && clients[i].Flow != "" && clientWithInboundFlow(clients[i], oldInbound).Flow == "" {
clients[i].Flow = ""
delete(cm, "flow")
}
if _, ok2 := cm["created_at"]; !ok2 {
cm["created_at"] = nowTs
}
@@ -453,10 +458,6 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model
return false, common.NewError("Duplicate email:", existEmail)
}
oldInbound, err := inboundSvc.GetInbound(data.Id)
if err != nil {
return false, err
}
defer s.recordClientNodeFailure(oldInbound.NodeID, &saveErr)
if err := validateTuicClientEmails(oldInbound.Protocol, clients); err != nil {
return false, err
@@ -774,7 +775,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
if err := validateClientsRenewal(clients); err != nil {
return false, err
}
inbound, err := inboundSvc.GetInbound(data.Id)
oldInbound, err := inboundSvc.GetInbound(data.Id)
if err != nil {
return false, err
}
@@ -786,10 +787,6 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
interfaceClients := settings["clients"].([]any)
oldInbound, err := inboundSvc.GetInbound(data.Id)
if err != nil {
return false, err
}
defer s.recordClientNodeFailure(oldInbound.NodeID, &saveErr)
if err := validateTuicClientEmails(oldInbound.Protocol, clients); err != nil {
return false, err
@@ -804,7 +801,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
if i == 0 {
identityEmail = oldEmail
}
if err := validateClientKeepAliveAgainstExisting(inbound.Protocol, client, oldClients, identityEmail); err != nil {
if err := validateClientKeepAliveAgainstExisting(oldInbound.Protocol, client, oldClients, identityEmail); err != nil {
return false, fmt.Errorf("client %q: %w", client.Email, err)
}
}