fix(inbounds): scale bulk client attachment selection (#7243)

With around 10,000 clients both attach dialogs loaded every client, pre-selected all of them and rendered every row, which locked the browser for minutes.

Both dialogs now ask the server for 100 rows at a time and render only the visible ones. Select All freezes the eligible client IDs that match the current search and group into a small server-issued token; the browser keeps that token plus the clients the operator unticked instead of thousands of emails, and the listing marks each row against the frozen filter so rows outside it stay unselected. On submit the server re-derives the same set and rejects the job before any write when its membership changed; clients created after the freeze stay outside it. The attach runs as a background job the dialog polls for counts.

Requests that post an email list keep their synchronous response. The Postgres job now runs the selection tests, which build their predicates by hand for both dialects.

Fixes #7236
This commit is contained in:
Hamed
2026-11-28 18:00:53 +03:30
committed by GitHub
parent 9088b8a768
commit 75dc6dc61c
34 changed files with 2643 additions and 492 deletions
+28 -2
View File
@@ -3,6 +3,7 @@ package controller
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
@@ -53,6 +54,7 @@ func NewClientController(g *gin.RouterGroup) *ClientController {
func (a *ClientController) initRouter(g *gin.RouterGroup) {
g.GET("/list", a.list)
g.GET("/list/paged", a.listPaged)
g.GET("/attachCandidates", a.attachCandidates)
g.GET("/get", a.get)
g.GET("/get/:email", a.get)
g.GET("/get/subId/:subId", a.getBySubId)
@@ -88,6 +90,7 @@ func (a *ClientController) initRouter(g *gin.RouterGroup) {
g.POST("/bulkDel", a.bulkDelete)
g.POST("/bulkCreate", a.bulkCreate)
g.POST("/bulkAttach", a.bulkAttach)
g.GET("/bulkAttach/:id", a.attachStatus)
g.POST("/bulkDetach", a.bulkDetach)
g.POST("/bulkResetTraffic", a.bulkResetTraffic)
g.POST("/resetTraffic/:email", a.resetTrafficByEmail)
@@ -138,6 +141,20 @@ func (a *ClientController) listPaged(c *gin.Context) {
jsonObj(c, resp, nil)
}
func (a *ClientController) attachCandidates(c *gin.Context) {
var params service.AttachCandidateParams
if err := c.ShouldBindQuery(&params); err != nil {
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
return
}
result, err := a.clientService.ListAttachCandidates(c.Request.Context(), params)
if err != nil {
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
return
}
jsonObj(c, result, nil)
}
func (a *ClientController) buildClientPayload(rec *model.ClientRecord) (gin.H, error) {
inboundIds, err := a.clientService.GetInboundIdsForRecord(rec.Id)
if err != nil {
@@ -426,8 +443,9 @@ type bulkDeleteRequest struct {
}
type bulkAttachRequest struct {
Emails []string `json:"emails"`
InboundIds []int `json:"inboundIds"`
Emails []string `json:"emails"`
InboundIds []int `json:"inboundIds"`
Selection *service.AttachSelection `json:"selection,omitempty"`
}
func (a *ClientController) bulkAttach(c *gin.Context) {
@@ -436,6 +454,14 @@ func (a *ClientController) bulkAttach(c *gin.Context) {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
if req.Selection != nil {
if len(req.Emails) > 0 {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), fmt.Errorf("use either emails or an attachment selection"))
return
}
a.beginBulkAttach(c, req.InboundIds, *req.Selection)
return
}
result, needRestart, err := a.clientService.BulkAttach(&a.inboundService, req.Emails, req.InboundIds)
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
@@ -0,0 +1,118 @@
package controller
import (
"context"
"errors"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
// Attachment jobs belong to the same administrator-only API as bulkAttach.
// Keep a bounded in-memory history of results and run one picker job at a time.
type attachJobStore struct {
mu sync.Mutex
running bool
jobs map[string]AttachJobStatus
}
type AttachJobStatus struct {
Running bool `json:"running" example:"false"`
Result *service.AttachSelectionResult `json:"result,omitempty"`
Error string `json:"error,omitempty"`
ended time.Time
}
var attachJobs attachJobStore
func (s *attachJobStore) start(run func() (*service.AttachSelectionResult, error)) (string, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.running {
return "", errors.New("another client attachment is running")
}
if s.jobs == nil {
s.jobs = make(map[string]AttachJobStatus)
}
cutoff := time.Now().Add(-15 * time.Minute)
var oldestID string
var oldest time.Time
for id, status := range s.jobs {
if status.ended.Before(cutoff) {
delete(s.jobs, id)
continue
}
if oldestID == "" || status.ended.Before(oldest) {
oldestID, oldest = id, status.ended
}
}
if len(s.jobs) >= 32 {
delete(s.jobs, oldestID)
}
id := uuid.NewString()
s.jobs[id] = AttachJobStatus{Running: true}
s.running = true
common.GoRecover("client-attachment", func() {
status := AttachJobStatus{Error: "client attachment interrupted"}
defer func() {
s.mu.Lock()
defer s.mu.Unlock()
status.ended = time.Now()
s.jobs[id] = status
s.running = false
}()
result, err := run()
if err != nil {
status.Error = err.Error()
return
}
status.Error = ""
status.Result = result
})
return id, nil
}
func (s *attachJobStore) get(id string) (AttachJobStatus, bool) {
s.mu.Lock()
defer s.mu.Unlock()
status, ok := s.jobs[id]
if !status.Running && time.Since(status.ended) > 15*time.Minute {
delete(s.jobs, id)
return AttachJobStatus{}, false
}
return status, ok
}
func (a *ClientController) beginBulkAttach(c *gin.Context, targets []int, selection service.AttachSelection) {
id, err := attachJobs.start(func() (*service.AttachSelectionResult, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
result, restart, err := a.clientService.BulkAttachSelection(ctx, &a.inboundService, targets, selection)
if restart {
a.xrayService.SetToNeedRestart()
}
if err == nil {
notifyClientsChanged()
}
return result, err
})
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
jsonObj(c, gin.H{"jobId": id}, nil)
}
func (a *ClientController) attachStatus(c *gin.Context) {
status, ok := attachJobs.get(c.Param("id"))
if !ok {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), errors.New("client attachment status unavailable"))
return
}
jsonObj(c, status, nil)
}
@@ -0,0 +1,51 @@
package controller
import (
"errors"
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
func TestAttachJobStorePublishesStatusAndPreventsOverlap(t *testing.T) {
var store attachJobStore
block := make(chan struct{})
id, err := store.start(func() (*service.AttachSelectionResult, error) {
<-block
return &service.AttachSelectionResult{Attached: 9997, Skipped: 1, Errors: 2}, nil
})
if err != nil {
t.Fatal(err)
}
if status, ok := store.get(id); !ok || !status.Running {
t.Fatalf("accepted job status = %#v, found=%t", status, ok)
}
if _, err := store.start(nil); err == nil {
t.Fatal("overlapping job was accepted")
}
close(block)
wait := func(id string) AttachJobStatus {
t.Helper()
for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
if status, ok := store.get(id); ok && !status.Running {
return status
}
time.Sleep(time.Millisecond)
}
t.Fatal("job did not finish")
return AttachJobStatus{}
}
result := wait(id).Result
if result == nil || result.Attached != 9997 || result.Skipped != 1 || result.Errors != 2 {
t.Fatalf("partial result lost: %#v", result)
}
id, err = store.start(func() (*service.AttachSelectionResult, error) { return nil, errors.New("stale selection") })
if err != nil {
t.Fatal(err)
}
if status := wait(id); status.Result != nil || status.Error != "stale selection" {
t.Fatalf("failed result lost: %#v", status)
}
}