Files
mirror-3x-ui/internal/web/service/client_detach_selection.go
T
Hamed c483882e56 fix(inbounds): keep Detach Clients responsive on large inbounds (#7332)
Replace the unbounded Detach Clients modal with server-paged candidate loading, debounced search and a virtualized list. Preserve explicit-ID selection and add frozen all-matching scopes with exclusions so selection remains stable across pages and searches without sending an N-sized client list from the browser.

Execute large detach requests as idempotent background jobs. Revalidate source-inbound membership in bounded batches, atomically apply membership deltas, preserve ClientRecords and traffic, and queue reconciliation for remote nodes. Keep the legacy email-based bulkDetach API compatible.

Add PostgreSQL/SQLite regression coverage for concurrent membership changes, stale scopes, exclusions, retries, rollback and legacy callers, plus real master/node coverage for offline-node reconciliation. Regenerate and validate the API contract and OpenAPI artifacts.
2026-12-03 14:24:47 +03:30

353 lines
11 KiB
Go

package service
import (
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"slices"
"strings"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
const (
detachCandidatePageSize = 100
DetachSelectionLimit = 100_000
)
type DetachCandidateParams struct {
InboundID int `form:"inboundId"`
Page int `form:"page"`
Search string `form:"search"`
}
type DetachCandidate struct {
ID int `json:"id"`
Email string `json:"email"`
Comment string `json:"comment"`
Enable bool `json:"enable"`
InScope bool `json:"inScope"`
Incarnation string `json:"-"`
}
type DetachCandidatePage struct {
Items []DetachCandidate `json:"items"`
Total int64 `json:"total"`
Attached int64 `json:"attached"`
}
type DetachScopeSummary struct {
ScopeToken string `json:"scopeToken"`
Total int `json:"total"`
}
type DetachSelection struct {
Mode string `json:"mode"`
ClientIDs []int `json:"clientIds"`
ExcludedClientIDs []int `json:"excludedClientIds"`
ScopeToken string `json:"scopeToken"`
}
type DetachSelectionResult struct {
Detached int `json:"detached"`
Skipped int `json:"skipped"`
Errors int `json:"errors"`
NodePending bool `json:"nodePending,omitempty"`
}
type detachMembership struct {
ID int
Incarnation string
}
type DetachScope struct {
inboundID int
generation uint64
members []detachMembership
}
func detachCandidates(db *gorm.DB, id int, search string) *gorm.DB {
return filteredAttachCandidates(
db.Table("client_inbounds AS ci").Joins("JOIN clients AS c ON c.id = ci.client_id").
Where("ci.inbound_id = ? AND c.email <> ''", id),
id, search, "",
)
}
func (s *DetachScope) matches(id int) bool {
return s != nil && s.inboundID == id && s.generation == database.ConnectionGeneration()
}
func (s *DetachScope) has(id int, incarnation string) bool {
n, found := slices.BinarySearchFunc(s.members, id, func(m detachMembership, id int) int {
return cmp.Compare(m.ID, id)
})
return found && s.members[n].Incarnation == incarnation
}
func (s *ClientService) ListDetachCandidates(ctx context.Context, p DetachCandidateParams, scope *DetachScope) (*DetachCandidatePage, error) {
if p.InboundID <= 0 || p.Page < 0 || p.Page > 1_000_000 || len(p.Search) > 256 {
return nil, errors.New("invalid client detachment page")
}
if scope != nil && !scope.matches(p.InboundID) {
return nil, errors.New("client detachment selection expired")
}
db := database.GetDB().WithContext(ctx)
if _, err := attachScope(db, p.InboundID, nil); err != nil {
return nil, err
}
resp := &DetachCandidatePage{Items: []DetachCandidate{}}
q := detachCandidates(db, p.InboundID, p.Search)
if err := q.Count(&resp.Total).Error; err != nil {
return nil, err
}
resp.Attached = resp.Total
if strings.TrimSpace(p.Search) != "" {
if err := detachCandidates(db, p.InboundID, "").Count(&resp.Attached).Error; err != nil {
return nil, err
}
}
if err := q.Select("c.id, c.email, c.comment, c.enable, ci.incarnation").
Order("c.id").Offset(max(0, p.Page-1) * detachCandidatePageSize).
Limit(detachCandidatePageSize).Scan(&resp.Items).Error; err != nil {
return nil, err
}
for i := range resp.Items {
row := &resp.Items[i]
row.InScope = scope != nil && scope.has(row.ID, row.Incarnation)
}
return resp, nil
}
func (s *ClientService) FreezeDetachScope(ctx context.Context, inboundID int) (*DetachScope, int, error) {
if inboundID <= 0 {
return nil, 0, errors.New("invalid source inbound")
}
generation := database.ConnectionGeneration()
db := database.GetDB().WithContext(ctx)
if _, err := attachScope(db, inboundID, nil); err != nil {
return nil, 0, err
}
var members []detachMembership
err := detachCandidates(db, inboundID, "").Select("c.id, ci.incarnation").
Order("c.id").Limit(DetachSelectionLimit + 1).Scan(&members).Error
if err != nil {
return nil, 0, err
}
if len(members) == 0 || len(members) > DetachSelectionLimit {
return nil, 0, errors.New("no attached clients or detachment selection exceeds the limit")
}
return &DetachScope{inboundID: inboundID, generation: generation, members: members}, len(members), nil
}
type DetachPlan struct {
inboundID int
generation uint64
ids []int
scope *DetachScope
}
func NewDetachPlan(inboundID int, selection DetachSelection, scope *DetachScope) (*DetachPlan, error) {
if inboundID <= 0 || len(selection.ClientIDs) > DetachSelectionLimit || len(selection.ExcludedClientIDs) > DetachSelectionLimit {
return nil, errors.New("invalid client detachment selection")
}
plan := &DetachPlan{inboundID: inboundID, generation: database.ConnectionGeneration()}
switch selection.Mode {
case "explicit":
if len(selection.ExcludedClientIDs) != 0 || selection.ScopeToken != "" {
return nil, errors.New("invalid explicit client detachment selection")
}
plan.ids = uniqueInts(selection.ClientIDs)
for _, id := range plan.ids {
if id <= 0 {
return nil, errors.New("invalid client ID")
}
}
case "allMatching":
if len(selection.ClientIDs) != 0 || !scope.matches(inboundID) {
return nil, errors.New("client detachment selection expired or belongs to another inbound")
}
plan.scope = scope
excluded := make(map[int]struct{}, len(selection.ExcludedClientIDs))
for _, id := range selection.ExcludedClientIDs {
excluded[id] = struct{}{}
}
for _, m := range scope.members {
if _, skip := excluded[m.ID]; skip {
delete(excluded, m.ID)
} else {
plan.ids = append(plan.ids, m.ID)
}
}
if len(excluded) != 0 {
return nil, errors.New("excluded client is outside the frozen selection")
}
default:
return nil, errors.New("invalid client detachment selection mode")
}
if len(plan.ids) == 0 {
return nil, errors.New("no clients selected for detachment")
}
return plan, nil
}
func (p *DetachPlan) Total() int { return len(p.ids) }
// ApplyDetachPlan updates the source settings once, even for a large selection.
// SQL lookup/delta batches are bounded and commit with the same membership check.
func (s *ClientService) ApplyDetachPlan(ctx context.Context, p *DetachPlan, progress func(int)) (*DetachSelectionResult, error) {
defer lockInbound(p.inboundID).Unlock()
result := &DetachSelectionResult{}
var previous, inbound model.Inbound
var detachedEmails []string
err := runSerializedTx(func(tx *gorm.DB) error {
if p.generation != database.ConnectionGeneration() || (p.scope != nil && !p.scope.matches(p.inboundID)) {
return errors.New("client detachment selection expired")
}
tx = tx.WithContext(context.WithValue(ctx, serializedTxContextKey{}, serializedTxOf(tx)))
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&inbound, p.inboundID).Error; err != nil {
return err
}
if _, err := attachScope(tx, p.inboundID, nil); err != nil {
return err
}
emails := make(map[string]struct{})
processed := 0
for _, ids := range chunkInts(p.ids, sqlInChunk) {
var rows []DetachCandidate
err := detachCandidates(tx, p.inboundID, "").Where("c.id IN ?", ids).
Select("c.id, c.email, ci.incarnation").Scan(&rows).Error
if err != nil {
return err
}
for _, row := range rows {
if p.scope == nil || p.scope.has(row.ID, row.Incarnation) {
emails[row.Email] = struct{}{}
}
}
processed += len(ids)
if progress != nil {
progress(processed)
}
}
result.Detached, result.Skipped = len(emails), p.Total()-len(emails)
if len(emails) == 0 {
return nil
}
settings, err := detachClientSettings(inbound.Settings, emails)
if err != nil {
return err
}
previous = inbound
// The running core can have users that are missing or disabled in settings.
detachedEmails = slices.Collect(maps.Keys(emails))
if settings != inbound.Settings {
if err := tx.Model(&inbound).Update("settings", settings).Error; err != nil {
return err
}
}
if err := s.ApplyInboundClientDelta(tx, inbound.Id, nil, detachedEmails); err != nil {
return err
}
if inbound.NodeID != nil {
result.NodePending = true
return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
}
return nil
})
if err != nil {
return &DetachSelectionResult{Skipped: result.Skipped, Errors: p.Total() - result.Skipped}, err
}
if result.Detached > 0 {
InvalidateSubData()
}
if inbound.NodeID == nil && inbound.Enable && len(detachedEmails) > 0 {
if err := applyLocalScopedDetach(ctx, &previous, &inbound, detachedEmails); err != nil {
(&XrayService{}).SetToNeedReconcile()
return result, fmt.Errorf("memberships detached, but the local runtime has not applied the change: %w", err)
}
}
return result, nil
}
// Apply runtime changes after commit so the traffic writer stays free during RPC.
func applyLocalScopedDetach(ctx context.Context, previous, inbound *model.Inbound, emails []string) error {
inbounds := &InboundService{}
core := &XrayService{}
rt, err := inbounds.runtimeFor(inbound)
if servedOutsideXray(inbound.Protocol) {
if err != nil {
return err
}
next, err := inbounds.buildInboundForLocalRuntime(database.GetDB(), inbound)
if err != nil {
return err
}
return rt.UpdateInbound(ctx, previous, next)
}
dropSessions := removalLeavesXraySessions(inbound) && restartAfterClientRemoval()
if err == nil && len(emails) <= nodeBulkPushThreshold && inbound.Protocol != model.WireGuard {
for _, email := range emails {
err = rt.RemoveUser(ctx, inbound, email)
if err != nil && !xray.IsMissingUserErr(err) {
break
}
err = nil
}
if err == nil && !dropSessions {
return nil
}
}
if !core.IsXrayRunning() {
return nil
}
// Large selections and failed live removals reconcile before the job finishes.
err = core.restartXrayFrom(false, XrayOriginConfigChange, "", dropSessions)
if err != nil && dropSessions {
pendingXraySessionDrop.Store(true)
}
return err
}
func detachClientSettings(raw string, emails map[string]struct{}) (string, error) {
var settings map[string]json.RawMessage
if err := json.Unmarshal([]byte(raw), &settings); err != nil {
return "", err
}
var clients []json.RawMessage
if err := json.Unmarshal(settings["clients"], &clients); err != nil {
return "", fmt.Errorf("read inbound clients: %w", err)
}
kept := make([]json.RawMessage, 0, len(clients))
for _, client := range clients {
var identity struct {
Email string
}
err := json.Unmarshal(client, &identity)
email := strings.TrimSpace(identity.Email)
if _, remove := emails[email]; err == nil && remove {
continue
}
kept = append(kept, client)
}
if len(kept) == len(clients) {
return raw, nil
}
values, err := json.Marshal(kept)
if err != nil {
return "", err
}
settings["clients"] = values
out, err := json.Marshal(settings)
return string(out), err
}