Files
Dark Dev 2b8fb1429a perf(clients): cache settings and inbound metadata and batch client lookups (#7226)
On panels with thousands of clients, opening one client's links read and decoded the full clients array of every inbound it is attached to, the client detail endpoints ran one query per record, and every settings getter hit the database.

Client links now build from the client's own row plus inbound metadata cached without the clients array (TUIC, WireGuard and AmneziaWG still read their full settings), client detail and list lookups are batched, and single-key settings reads go through a short cache. On a panel with 2,005 clients and 6,008 memberships, links for one client drop from 27 ms to 0.5 ms and client detail from 1.1 ms to 0.4 ms, with byte-identical responses on SQLite and PostgreSQL; subscription fetches are unchanged.

Writes made by the panel itself invalidate the caches after they commit. A write made to the settings table by another process (the CLI, manual SQL) is seen by a running panel after up to 5 seconds, and to inbounds after up to 10.

The composite index on client_inbounds (inbound_id, client_id) from the first revision is not included: it made SQLite scan every membership of each inbound on every subscription fetch.
2026-12-05 15:02:51 +03:30

148 lines
4.2 KiB
Go

package service
import (
"sync"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
)
type SubLinkProvider interface {
SubLinksForSubId(host, subId string) ([]string, error)
LinksForClient(host string, inbound *model.Inbound, email string) []string
LinksForInbounds(host string, inbounds []*model.Inbound) []string
}
// ClientBatchLinkProvider lets LinkProvider render all links for one client
// across multiple inbounds with one host preload and primed client metadata.
type ClientBatchLinkProvider interface {
LinksForClientInbounds(host string, inbounds []*model.Inbound, rec *model.ClientRecord, flowByInbound map[int]string) []string
}
var (
subLinkProviderMu sync.RWMutex
registeredSubLinkProvider SubLinkProvider
)
func RegisterSubLinkProvider(p SubLinkProvider) {
subLinkProviderMu.Lock()
defer subLinkProviderMu.Unlock()
registeredSubLinkProvider = p
}
// subLinkProvider guards the registry: startup writes it while link requests read it.
func subLinkProvider() SubLinkProvider {
subLinkProviderMu.RLock()
defer subLinkProviderMu.RUnlock()
return registeredSubLinkProvider
}
func (s *InboundService) GetSubLinks(host, subId string) ([]string, error) {
provider := subLinkProvider()
if provider == nil {
return nil, common.NewError("sub link provider not registered")
}
return provider.SubLinksForSubId(host, subId)
}
func (s *InboundService) GetAllInboundLinks(host string, userId int) ([]string, error) {
provider := subLinkProvider()
if provider == nil {
return nil, common.NewError("sub link provider not registered")
}
inbounds, err := s.GetInbounds(userId)
if err != nil {
return nil, err
}
return provider.LinksForInbounds(host, inbounds), nil
}
func (s *InboundService) GetAllClientLinks(host string, email string) ([]string, error) {
if email == "" {
return nil, common.NewError("client email is required")
}
provider := subLinkProvider()
if provider == nil {
return nil, common.NewError("sub link provider not registered")
}
rec, err := s.clientService.GetRecordByEmail(nil, email)
if err != nil {
return nil, err
}
var linkRows []struct {
InboundId int
FlowOverride string
}
if err := database.GetDB().Table("client_inbounds").
Select("inbound_id, flow_override").
Where("client_id = ?", rec.Id).
Order("inbound_id ASC").
Scan(&linkRows).Error; err != nil {
return nil, err
}
if len(linkRows) == 0 {
return nil, nil
}
inboundIds := make([]int, len(linkRows))
flowByInbound := make(map[int]string, len(linkRows))
for i, row := range linkRows {
inboundIds[i] = row.InboundId
if row.FlowOverride != "" {
flowByInbound[row.InboundId] = row.FlowOverride
}
}
batchProvider, canBatch := provider.(ClientBatchLinkProvider)
if !canBatch {
fullByID, getErr := s.GetInboundsByIDs(inboundIds)
if getErr != nil {
return nil, getErr
}
var links []string
for _, ibId := range inboundIds {
inbound := fullByID[ibId]
if inbound == nil {
return nil, common.NewErrorf("inbound %d not found", ibId)
}
links = append(links, provider.LinksForClient(host, inbound, email)...)
}
return links, nil
}
metas, metaErrs := s.GetInboundMetaBatch(inboundIds)
for _, ibId := range inboundIds {
if mErr := metaErrs[ibId]; mErr != nil {
return nil, mErr
}
}
// WireGuard/AmneziaWG need peer keys and TUIC reads embedded client eligibility/credentials.
var fullSettingsIDs []int
for _, ibId := range inboundIds {
m := metas[ibId]
if m != nil && (m.Protocol == model.WireGuard || m.Protocol == model.AmneziaWG || m.Protocol == model.TUIC) {
fullSettingsIDs = append(fullSettingsIDs, ibId)
}
}
var fullInbounds map[int]*model.Inbound
if len(fullSettingsIDs) > 0 {
var fErr error
fullInbounds, fErr = s.GetInboundsByIDs(fullSettingsIDs)
if fErr != nil {
return nil, fErr
}
}
inbounds := make([]*model.Inbound, 0, len(inboundIds))
for _, ibId := range inboundIds {
if fullIb := fullInbounds[ibId]; fullIb != nil {
inbounds = append(inbounds, fullIb)
continue
}
inbounds = append(inbounds, metas[ibId].ToInboundShell())
}
return batchProvider.LinksForClientInbounds(host, inbounds, rec, flowByInbound), nil
}