perf(clients): bound orphan cleanup during inbound adds (#7228)

Adding one client checked every client already on the inbound against the clients table, 400 emails per query, so a 100,000-client inbound paid about 250 lookups per add. Each add now checks one rotating window of at most 400 existing entries; stale entries outside it are removed when the cursor reaches them or when a delete on that inbound runs its full sweep.

The check now runs inside the serialized writer, so a client that another writer recreated while the add was waiting is no longer swept from the inbound. When an add on a node-hosted inbound also prunes stale entries, the node is left to be reconciled instead of being marked as already matching, since it only received the new client.

Reading and rewriting the settings JSON still scales with the inbound: on SQLite with 50,000 clients a single add went from about 512 ms to 465 ms.

Closes #7217
This commit is contained in:
Hamed
2026-11-28 05:16:42 +03:30
committed by GitHub
parent 22ffae302f
commit ed44254b0a
4 changed files with 348 additions and 9 deletions
+10
View File
@@ -84,6 +84,16 @@ jobs:
exit 1
fi
- name: PostgreSQL inbound add orphan cleanup
run: |
set -o pipefail
go test ./internal/web/service -run '^TestAddInboundClient(BoundedOrphanCleanup|OrphanProbePreservesConcurrentRecreation)Postgres$' -count=1 -v | tee /tmp/postgres-add-orphans.log
passed=$(grep -c -- '^--- PASS: TestAddInboundClient' /tmp/postgres-add-orphans.log || true)
if [ "$passed" -ne 2 ]; then
echo "expected both PostgreSQL inbound add orphan cleanup tests to pass, got $passed" >&2
exit 1
fi
- name: PostgreSQL client traffic lifecycle edits
run: |
set -o pipefail
@@ -0,0 +1,262 @@
package service
import (
"fmt"
"net"
"net/http"
"net/http/httptest"
"slices"
"strconv"
"strings"
"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/web/runtime"
)
type addOrphanReads struct {
selects, probes, maxEmails int
}
func trackAddOrphanReads(t testing.TB) *addOrphanReads {
t.Helper()
reads := &addOrphanReads{}
callbacks := database.GetDB().Callback()
const name = "test:add_orphan_reads"
unquote := strings.NewReplacer("\"", "", "`", "")
count := func(tx *gorm.DB) {
sql := tx.Statement.SQL.String()
if !strings.HasPrefix(sql, "SELECT ") {
return
}
reads.selects++
if strings.HasPrefix(unquote.Replace(sql), "SELECT email FROM clients WHERE email IN (") {
reads.probes++
reads.maxEmails = max(reads.maxEmails, len(tx.Statement.Vars))
}
}
if err := callbacks.Query().After("gorm:query").Register(name, count); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := callbacks.Query().Remove(name); err != nil {
t.Error(err)
}
})
if err := callbacks.Row().After("gorm:row").Register(name, count); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := callbacks.Row().Remove(name); err != nil {
t.Error(err)
}
})
return reads
}
func orphanTestClient(email string) model.Client {
return model.Client{ID: uuid.NewString(), Email: email, SubID: uuid.NewString()}
}
func addOrphanTestPayload(t testing.TB, id int, clients ...model.Client) *model.Inbound {
t.Helper()
return &model.Inbound{Id: id, Settings: clientsSettings(t, clients)}
}
func TestAddInboundClientBoundedOrphanCleanup(t *testing.T) {
setupBulkDB(t)
testAddInboundClientBoundedOrphanCleanup(t)
}
func TestAddInboundClientBoundedOrphanCleanupPostgres(t *testing.T) {
setupScaleDB(t)
testAddInboundClientBoundedOrphanCleanup(t)
}
func testAddInboundClientBoundedOrphanCleanup(t *testing.T) {
t.Helper()
ds := seedScaleDataset(t, 1000, 1)
id := ds.inboundIds[0]
live := ds.perInbound[0][0]
stale := orphanTestClient("recent@orphan-add")
old := orphanTestClient("old@orphan-add")
entries := append([]model.Client{stale}, ds.perInbound[0]...)
entries = append(entries, old)
if err := database.GetDB().Model(&model.Inbound{}).Where("id = ?", id).
Update("settings", clientsSettings(t, entries)).Error; err != nil {
t.Fatal(err)
}
tombstoneClientEmails([]string{live.Email, stale.Email})
t.Cleanup(func() { withdrawClientTombstones(live.Email, stale.Email) })
reads := trackAddOrphanReads(t)
cs, is := &ClientService{}, &InboundService{}
want := emailsOf(ds.perInbound[0])
for i := range 4 {
newClient := orphanTestClient(fmt.Sprintf("new-%d@orphan-add", i))
want = append(want, newClient.Email)
*reads = addOrphanReads{}
if _, err := cs.AddInboundClient(is, addOrphanTestPayload(t, id, live, newClient)); err != nil {
t.Fatal(err)
}
if reads.probes > 1 || reads.maxEmails > 400 {
t.Errorf("add %d issued %d orphan SELECTs with up to %d emails, want at most one query of at most 400 emails", i, reads.probes, reads.maxEmails)
}
if i == 0 {
emails := settingsClientEmails(t, id)
if !slices.Contains(emails, old.Email) && !slices.Contains(emails, stale.Email) {
t.Error("a single add swept orphans at both ends of the inbound")
}
}
}
emails := settingsClientEmails(t, id)
if !slices.Equal(emails, want) {
t.Fatalf("after rotating through the inbound, got %d entries, want %d with both orphans removed and every live email kept once in order", len(emails), len(want))
}
}
func TestAddInboundClientOrphanProbePreservesConcurrentRecreation(t *testing.T) {
setupBulkDB(t)
testAddInboundClientOrphanProbePreservesConcurrentRecreation(t)
}
func TestAddInboundClientOrphanProbePreservesConcurrentRecreationPostgres(t *testing.T) {
setupScaleDB(t)
testAddInboundClientOrphanProbePreservesConcurrentRecreation(t)
}
func testAddInboundClientOrphanProbePreservesConcurrentRecreation(t *testing.T) {
t.Helper()
db := database.GetDB()
resetScaleTables(t, db, "inbounds", "clients", "client_inbounds", "client_traffics")
recreated := orphanTestClient("recreated@orphan-add")
target := model.Inbound{Tag: "target-orphan", Protocol: model.VLESS, Port: 44001, Settings: clientsSettings(t, []model.Client{recreated})}
other := model.Inbound{Tag: "other-orphan", Protocol: model.VLESS, Port: 44002, Settings: clientsSettings(t, nil)}
if err := db.Create(&target).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&other).Error; err != nil {
t.Fatal(err)
}
newClient := orphanTestClient("concurrent@orphan-add")
data := addOrphanTestPayload(t, target.Id, newClient)
cs := &ClientService{}
commitTickBetweenReadAndWrite(t, func(tx *gorm.DB) error {
return cs.ApplyInboundClientDelta(tx, other.Id, []model.Client{recreated}, nil)
}, func() {
if _, err := cs.AddInboundClient(&InboundService{}, data); err != nil {
t.Error(err)
}
})
if got, want := settingsClientEmails(t, target.Id), []string{recreated.Email, newClient.Email}; !slices.Equal(got, want) {
t.Fatalf("settings after recreation committed first = %v, want %v", got, want)
}
}
func TestNodeAddInboundClientReconcilesOrphanRemoval(t *testing.T) {
setupBulkDB(t)
stale := orphanTestClient("stale@node-orphan")
added := orphanTestClient("added@node-orphan")
added.Enable = true
var adds, updates atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/panel/api/clients/add":
adds.Add(1)
case "/panel/api/inbounds/update/7":
settings := r.FormValue("settings")
if !strings.Contains(settings, added.Email) || strings.Contains(settings, stale.Email) {
t.Errorf("node update settings = %s, want only the added client", settings)
}
updates.Add(1)
default:
t.Errorf("unexpected node call: %s", r.URL.Path)
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"success":true}`))
}))
t.Cleanup(srv.Close)
host, portString, err := net.SplitHostPort(srv.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
port, err := strconv.Atoi(portString)
if err != nil {
t.Fatal(err)
}
db := database.GetDB()
node := &model.Node{
Name: "orphan-node", Scheme: "http", Address: host, Port: port, BasePath: "/",
ApiToken: "test", Enable: true, Status: "online", AllowPrivateAddress: true,
}
if err := db.Create(node).Error; err != nil {
t.Fatal(err)
}
ib := &model.Inbound{
Tag: "orphan-inbound", NodeID: &node.Id, Port: 44003, Protocol: model.VLESS,
Settings: clientsSettings(t, []model.Client{stale}),
}
if err := db.Create(ib).Error; err != nil {
t.Fatal(err)
}
remote := runtime.NewRemote(node, nil)
useTestRuntimeManager(t).SetRuntimeOverride(node.Id, remote)
remote.AdoptInboundAlias(ib, runtime.RemoteInboundOption{Id: 7, Tag: ib.Tag})
svc := &InboundService{}
if _, err := (&ClientService{}).AddInboundClient(svc, addOrphanTestPayload(t, ib.Id, added)); err != nil {
t.Fatal(err)
}
saved, err := svc.GetInbound(ib.Id)
if err != nil {
t.Fatal(err)
}
pushed, err := remote.ReconcileInbound(t.Context(), saved, true)
if err != nil {
t.Fatal(err)
}
if !pushed || adds.Load() != 1 || updates.Load() != 1 {
t.Fatalf("got %d client adds and %d inbound updates (pushed=%t), want one of each", adds.Load(), updates.Load(), pushed)
}
}
func BenchmarkAddInboundClientOrphanCleanup(b *testing.B) {
setupScaleDB(b)
for _, n := range []int{1000, 10000, 50000, 100000} {
b.Run(fmt.Sprint(n), func(b *testing.B) {
ds := seedScaleDataset(b, n, 1)
id := ds.inboundIds[0]
reads := trackAddOrphanReads(b)
cs, is := &ClientService{}, &InboundService{}
warmup := addOrphanTestPayload(b, id, orphanTestClient("warm@orphan-bench"))
if _, err := cs.AddInboundClient(is, warmup); err != nil {
b.Fatal(err)
}
*reads = addOrphanReads{}
var samples []time.Duration
for b.Loop() {
b.StopTimer()
client := orphanTestClient(fmt.Sprintf("add-%d@orphan-bench", len(samples)))
data := addOrphanTestPayload(b, id, client)
b.StartTimer()
start := time.Now()
if _, err := cs.AddInboundClient(is, data); err != nil {
b.Fatal(err)
}
samples = append(samples, time.Since(start))
}
slices.Sort(samples)
b.ReportMetric(float64(samples[(len(samples)-1)/2].Microseconds())/1000, "p50-ms")
b.ReportMetric(float64(samples[(95*len(samples)+99)/100-1].Microseconds())/1000, "p95-ms")
b.ReportMetric(float64(reads.selects)/float64(b.N), "selects/op")
b.ReportMetric(float64(reads.probes)/float64(b.N), "orphan-selects/op")
})
}
}
+23 -6
View File
@@ -401,7 +401,8 @@ func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, c
func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) {
defer InvalidateSubData()
defer lockInbound(data.Id).Unlock()
lock := lockInbound(data.Id)
defer lock.Unlock()
clients, err := inboundSvc.GetClients(data)
if err != nil {
@@ -587,10 +588,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
}
oldClients, _ := oldSettings["clients"].([]any)
oldClients = compactOrphans(database.GetDB(), oldClients)
oldClients = append(oldClients, interfaceClients...)
oldSettings["clients"] = oldClients
oldSettings["clients"] = append(oldClients, interfaceClients...)
newSettings, err := json.MarshalIndent(oldSettings, "", " ")
if err != nil {
@@ -608,6 +606,8 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
}
needRestart := false
nextOrphanOffset := lock.orphanOffset
prunedOrphans := false
rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
if perr != nil {
@@ -645,6 +645,21 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
}
}
}
// Confirm absence in the writer so an earlier committed re-add survives.
compacted, next, err := compactAddOrphans(tx, oldClients, lock.orphanOffset)
if err != nil {
return err
}
nextOrphanOffset = next
if len(compacted) != len(oldClients) {
oldSettings["clients"] = append(compacted, interfaceClients...)
repaired, err := json.MarshalIndent(oldSettings, "", " ")
if err != nil {
return err
}
oldInbound.Settings = string(repaired)
prunedOrphans = true
}
for i := range clients {
if len(clients[i].Email) == 0 {
continue
@@ -666,6 +681,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
}); txErr != nil {
return false, txErr
}
lock.orphanOffset = nextOrphanOffset
// Apply to the running runtime after commit — outside the serialized writer
// so a slow node call can't stall traffic accounting.
@@ -724,7 +740,8 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
}
}
}
if push {
// AddClient only pushed the new clients. Reconcile any orphan removals.
if push && !prunedOrphans {
advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound)
}
}
+53 -3
View File
@@ -2,6 +2,7 @@ package service
import (
"encoding/json"
"slices"
"strconv"
"strings"
"sync"
@@ -25,14 +26,19 @@ const deleteTombstoneTTL = 90 * time.Second
var (
inboundMutationLocksMu sync.Mutex
inboundMutationLocks = map[int]*sync.Mutex{}
inboundMutationLocks = map[int]*inboundMutationLock{}
)
func lockInbound(inboundId int) *sync.Mutex {
type inboundMutationLock struct {
sync.Mutex
orphanOffset int
}
func lockInbound(inboundId int) *inboundMutationLock {
inboundMutationLocksMu.Lock()
m, ok := inboundMutationLocks[inboundId]
if !ok {
m = &sync.Mutex{}
m = &inboundMutationLock{}
inboundMutationLocks[inboundId] = m
}
inboundMutationLocksMu.Unlock()
@@ -40,6 +46,50 @@ func lockInbound(inboundId int) *sync.Mutex {
return m
}
// compactAddOrphans checks one rotating window of old settings entries per add.
// The caller holds the inbound lock and runs the check on the serialized writer.
func compactAddOrphans(tx *gorm.DB, clients []any, offset int) ([]any, int, error) {
const budget = 400
if offset >= len(clients) {
offset = 0
}
end := min(offset+budget, len(clients))
window := clients[offset:end]
emails := make([]string, 0, len(window))
missing := make(map[string]struct{}, len(window))
for _, entry := range window {
_, email := clientEntryEmail(entry)
if _, seen := missing[email]; email != "" && !seen {
emails = append(emails, email)
missing[email] = struct{}{}
}
}
if len(emails) > 0 {
var found []string
if err := tx.Model(&model.ClientRecord{}).Where("email IN ?", emails).Pluck("email", &found).Error; err != nil {
return clients, offset, err
}
for _, email := range found {
delete(missing, email)
}
}
next := end
if len(missing) > 0 {
kept := slices.DeleteFunc(window, func(entry any) bool {
_, email := clientEntryEmail(entry)
_, orphan := missing[email]
return orphan
})
next = offset + len(kept)
}
wrapped := end == len(clients)
clients = slices.Delete(clients, next, end)
if wrapped {
next = 0
}
return clients, next, nil
}
func compactOrphans(db *gorm.DB, clients []any) []any {
if len(clients) == 0 {
return clients