mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 16:34:52 +03:00
c483882e56
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.
254 lines
7.1 KiB
Go
254 lines
7.1 KiB
Go
package controller
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/json"
|
|
"errors"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
|
)
|
|
|
|
const detachHistoryTTL = 15 * time.Minute
|
|
|
|
type savedDetachScope struct {
|
|
scope *service.DetachScope
|
|
issued time.Time
|
|
}
|
|
|
|
type detachScopeStore struct {
|
|
mu sync.Mutex
|
|
entries map[string]savedDetachScope
|
|
}
|
|
|
|
var (
|
|
detachScopes detachScopeStore
|
|
freezeDetachMu sync.Mutex
|
|
)
|
|
|
|
func (s *detachScopeStore) save(scope *service.DetachScope) string {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.entries == nil {
|
|
s.entries = make(map[string]savedDetachScope)
|
|
}
|
|
now := time.Now()
|
|
var oldest string
|
|
for token, entry := range s.entries {
|
|
if now.Sub(entry.issued) >= detachHistoryTTL {
|
|
delete(s.entries, token)
|
|
} else if oldest == "" || entry.issued.Before(s.entries[oldest].issued) {
|
|
oldest = token
|
|
}
|
|
}
|
|
if len(s.entries) >= 8 {
|
|
delete(s.entries, oldest)
|
|
}
|
|
token := uuid.NewString()
|
|
s.entries[token] = savedDetachScope{scope: scope, issued: now}
|
|
return token
|
|
}
|
|
|
|
func (s *detachScopeStore) get(token string) *service.DetachScope {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
entry, ok := s.entries[token]
|
|
if !ok || time.Since(entry.issued) >= detachHistoryTTL {
|
|
delete(s.entries, token)
|
|
return nil
|
|
}
|
|
return entry.scope
|
|
}
|
|
|
|
type DetachJobStatus struct {
|
|
Running bool `json:"running"`
|
|
Processed int `json:"processed"`
|
|
Total int `json:"total"`
|
|
Result *service.DetachSelectionResult `json:"result,omitempty"`
|
|
Error string `json:"error,omitempty"`
|
|
}
|
|
|
|
type detachJob struct {
|
|
status DetachJobStatus
|
|
request [sha256.Size]byte
|
|
generation uint64
|
|
ended time.Time
|
|
}
|
|
|
|
type detachJobStore struct {
|
|
mu sync.Mutex
|
|
running bool
|
|
entries map[string]detachJob
|
|
}
|
|
|
|
var detachJobs detachJobStore
|
|
|
|
func (s *detachJobStore) start(id string, inboundID int, selection service.DetachSelection, run func(*service.DetachPlan, func(int)) (*service.DetachSelectionResult, error)) error {
|
|
parsed, err := uuid.Parse(id)
|
|
if err != nil || parsed == uuid.Nil || id != parsed.String() ||
|
|
len(selection.ClientIDs) > service.DetachSelectionLimit || len(selection.ExcludedClientIDs) > service.DetachSelectionLimit {
|
|
return errors.New("invalid client detachment request")
|
|
}
|
|
encoded, err := json.Marshal(struct {
|
|
InboundID int
|
|
Selection service.DetachSelection
|
|
}{inboundID, selection})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
fingerprint := sha256.Sum256(encoded)
|
|
generation := database.ConnectionGeneration()
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.entries == nil {
|
|
s.entries = make(map[string]detachJob)
|
|
}
|
|
var oldest string
|
|
for key, entry := range s.entries {
|
|
if entry.status.Running {
|
|
continue
|
|
}
|
|
if time.Since(entry.ended) >= detachHistoryTTL || entry.generation != generation {
|
|
delete(s.entries, key)
|
|
} else if oldest == "" || entry.ended.Before(s.entries[oldest].ended) {
|
|
oldest = key
|
|
}
|
|
}
|
|
if entry, ok := s.entries[id]; ok {
|
|
if entry.request != fingerprint || entry.generation != generation {
|
|
return errors.New("detachment request ID is already in use")
|
|
}
|
|
return nil
|
|
}
|
|
if s.running {
|
|
return errors.New("another client detachment is running")
|
|
}
|
|
plan, err := service.NewDetachPlan(inboundID, selection, detachScopes.get(selection.ScopeToken))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(s.entries) >= 32 {
|
|
delete(s.entries, oldest)
|
|
}
|
|
s.entries[id] = detachJob{request: fingerprint, generation: generation, status: DetachJobStatus{
|
|
Running: true, Total: plan.Total(),
|
|
}}
|
|
s.running = true
|
|
common.GoRecover("client-detachment", func() {
|
|
var result *service.DetachSelectionResult
|
|
failure := "client detachment interrupted"
|
|
defer func() {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
entry := s.entries[id]
|
|
entry.ended = time.Now()
|
|
entry.status.Running, entry.status.Result, entry.status.Error = false, result, failure
|
|
s.entries[id] = entry
|
|
s.running = false
|
|
}()
|
|
var err error
|
|
result, err = run(plan, func(n int) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
entry := s.entries[id]
|
|
entry.status.Processed = n
|
|
s.entries[id] = entry
|
|
})
|
|
if err != nil {
|
|
failure = err.Error()
|
|
} else {
|
|
failure = ""
|
|
}
|
|
})
|
|
return nil
|
|
}
|
|
|
|
func (s *detachJobStore) get(id string) (DetachJobStatus, bool) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
entry, ok := s.entries[id]
|
|
if !ok || entry.generation != database.ConnectionGeneration() ||
|
|
(!entry.status.Running && time.Since(entry.ended) >= detachHistoryTTL) {
|
|
return DetachJobStatus{}, false
|
|
}
|
|
return entry.status, true
|
|
}
|
|
|
|
func (a *ClientController) detachCandidates(c *gin.Context) {
|
|
c.Header("Cache-Control", "no-store")
|
|
var params service.DetachCandidateParams
|
|
if err := c.ShouldBindQuery(¶ms); err != nil {
|
|
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
|
return
|
|
}
|
|
var scope *service.DetachScope
|
|
if token := c.Query("scopeToken"); token != "" {
|
|
scope = detachScopes.get(token)
|
|
if scope == nil {
|
|
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), errors.New("client detachment selection expired"))
|
|
return
|
|
}
|
|
}
|
|
page, err := a.clientService.ListDetachCandidates(c.Request.Context(), params, scope)
|
|
jsonObj(c, page, err)
|
|
}
|
|
|
|
func (a *ClientController) freezeDetachCandidates(c *gin.Context) {
|
|
var req struct {
|
|
InboundID int `json:"inboundId"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
|
return
|
|
}
|
|
if !freezeDetachMu.TryLock() {
|
|
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), errors.New("another detachment selection is being prepared"))
|
|
return
|
|
}
|
|
defer freezeDetachMu.Unlock()
|
|
scope, total, err := a.clientService.FreezeDetachScope(c.Request.Context(), req.InboundID)
|
|
if err != nil {
|
|
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
|
return
|
|
}
|
|
jsonObj(c, service.DetachScopeSummary{ScopeToken: detachScopes.save(scope), Total: total}, nil)
|
|
}
|
|
|
|
func (a *ClientController) beginBulkDetach(c *gin.Context, req bulkDetachRequest) {
|
|
if len(req.Emails) != 0 || len(req.InboundIds) != 1 {
|
|
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), errors.New("a scoped detachment requires one inbound and no email list"))
|
|
return
|
|
}
|
|
err := detachJobs.start(req.RequestID, req.InboundIds[0], *req.Selection, func(plan *service.DetachPlan, progress func(int)) (*service.DetachSelectionResult, error) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
|
defer cancel()
|
|
result, err := a.clientService.ApplyDetachPlan(ctx, plan, progress)
|
|
if err == nil || (result != nil && result.Detached > 0) {
|
|
notifyClientsChanged()
|
|
}
|
|
return result, err
|
|
})
|
|
if err != nil {
|
|
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
|
|
return
|
|
}
|
|
jsonObj(c, gin.H{"jobId": req.RequestID}, nil)
|
|
}
|
|
|
|
func (a *ClientController) detachStatus(c *gin.Context) {
|
|
c.Header("Cache-Control", "no-store")
|
|
status, ok := detachJobs.get(c.Param("id"))
|
|
if !ok {
|
|
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), errors.New("client detachment status unavailable"))
|
|
return
|
|
}
|
|
jsonObj(c, status, nil)
|
|
}
|