Files
mirror-3x-ui/internal/web/service/inbound_info.go
T
Hamed fda676e62a fix(inbounds): page inbound info and stream peer exports (#7341)
Replace full inbound hydration in Show Info with owner-scoped, no-store reads of one display client or up to 50 WireGuard/AmneziaWG peers. Preserve absolute peer numbering, Host/node endpoint projection, selected tab and IP logs across live traffic updates; keep edit and clone on full detail.

Stream ordered NDJSON pages from a single stored inbound snapshot for explicit Export All Peers. Generate an ordered ZIP64 archive with existing client config/link generators; validate page offsets, protocol and total, and reject incomplete or cancelled exports. Renew the per-page HTTP write deadline through the original response writer before gzip wrapping, keeping ordinary endpoint timeouts unchanged.

Validated on head 0f853351: all 12 CI jobs and Docs CI passed, including 2,350 frontend tests, bounded-info Chromium stories, live-traffic and archive regressions, Go/race, PostgreSQL, and node/Xray E2E. The final review also verified a conflict-free test merge with main 38452eac, matching regenerated API contracts and passing focused controller tests, including the real HTTP deadline regression for identity and gzip.

The author's synthetic 50,000-peer fixture reduces the uncompressed Show Info response from 2,650,526 to 3,184 bytes. Stored JSON still requires a linear scan per page; explicit ZIP export retains archive data in browser memory. Slow individual writes and reverse-proxy timeouts remain operational limits. No production latency or memory guarantee is implied.

Fixes #7330.
2026-12-03 04:57:45 +03:30

276 lines
7.2 KiB
Go

package service
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
"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/xray"
)
const inboundPeerPageSize = 50
type InboundInfoPage struct {
Inbound *model.Inbound `json:"inbound"`
TotalPeers int `json:"totalPeers" example:"120"`
PeerOffset int `json:"peerOffset" example:"50"`
}
type inboundInfoCollection struct {
raw string
size int
}
type inboundInfoSnapshot struct {
inbound model.Inbound
fields map[string]json.RawMessage
source string
collection inboundInfoCollection
tunnel bool
}
func readInboundInfoSnapshot(ctx context.Context, db *gorm.DB, userID, id int) (inboundInfoSnapshot, error) {
var snap inboundInfoSnapshot
if err := db.WithContext(ctx).Where("user_id = ?", userID).First(&snap.inbound, id).Error; err != nil {
return snap, err
}
fields, collections, err := splitInboundInfoSettings(ctx, snap.inbound.Settings)
if err != nil {
if ctx.Err() != nil {
return snap, ctx.Err()
}
fields = make(map[string]json.RawMessage)
}
snap.fields = fields
snap.inbound.Settings = ""
snap.source = "clients"
snap.tunnel = snap.inbound.Protocol == model.WireGuard || snap.inbound.Protocol == model.AmneziaWG
if snap.inbound.Protocol == model.WireGuard && collections["clients"].size == 0 {
snap.source = "peers"
}
snap.collection = collections[snap.source]
return snap, nil
}
func splitInboundInfoSettings(ctx context.Context, settings string) (map[string]json.RawMessage, map[string]inboundInfoCollection, error) {
settings = strings.TrimSpace(settings)
if strings.HasPrefix(settings, `"`) {
var decoded string
if err := json.Unmarshal([]byte(settings), &decoded); err != nil {
return nil, nil, err
}
settings = decoded
}
metadata := make(map[string]json.RawMessage)
collections := make(map[string]inboundInfoCollection)
dec := json.NewDecoder(strings.NewReader(settings))
opening, err := dec.Token()
if err != nil || opening != json.Delim('{') {
return nil, nil, fmt.Errorf("invalid inbound settings")
}
for dec.More() {
key, err := dec.Token()
if err != nil {
return nil, nil, err
}
name, ok := key.(string)
if !ok {
return nil, nil, fmt.Errorf("invalid inbound settings field")
}
if name == "clients" || name == "peers" {
// Keep the stored array span and its count without decoding a full peer slice.
value := strings.TrimLeft(settings[dec.InputOffset():], ": \t\r\n")
if strings.HasPrefix(value, "[") {
start := len(settings) - len(value)
if _, err := dec.Token(); err != nil {
return nil, nil, err
}
count := 0
var row json.RawMessage
for dec.More() {
if err := ctx.Err(); err != nil {
return nil, nil, err
}
if err := dec.Decode(&row); err != nil {
return nil, nil, err
}
if len(row) > 0 && row[0] == '{' {
count++
}
}
if _, err := dec.Token(); err != nil {
return nil, nil, err
}
collections[name] = inboundInfoCollection{raw: settings[start:dec.InputOffset()], size: count}
continue
}
delete(collections, name)
var discarded json.RawMessage
if err := dec.Decode(&discarded); err != nil {
return nil, nil, err
}
continue
}
var field json.RawMessage
if err := dec.Decode(&field); err != nil {
return nil, nil, err
}
metadata[name] = field
}
if _, err := dec.Token(); err != nil {
return nil, nil, err
}
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
return nil, nil, fmt.Errorf("unexpected data after inbound settings")
}
return metadata, collections, nil
}
func (c inboundInfoCollection) walk(ctx context.Context, visit func(json.RawMessage) bool) error {
if c.raw == "" {
return nil
}
d := json.NewDecoder(strings.NewReader(c.raw))
if _, err := d.Token(); err != nil {
return err
}
var row json.RawMessage
for d.More() {
if err := ctx.Err(); err != nil {
return err
}
if err := d.Decode(&row); err != nil {
return err
}
if len(row) > 0 && row[0] == '{' && !visit(row) {
return nil
}
}
return nil
}
func (s inboundInfoSnapshot) page(rows []json.RawMessage, offset int) (*InboundInfoPage, error) {
// Only the chosen source array is added back, so generators see the proper representation.
for _, name := range []string{"clients", "peers"} {
delete(s.fields, name)
}
if rows != nil {
selected, err := json.Marshal(rows)
if err != nil {
return nil, err
}
s.fields[s.source] = selected
}
raw, err := json.Marshal(s.fields)
if err != nil {
return nil, err
}
inbound := s.inbound
inbound.Settings = string(raw)
total := 0
if s.tunnel {
total = s.collection.size
}
return &InboundInfoPage{Inbound: &inbound, TotalPeers: total, PeerOffset: offset}, nil
}
func (s *InboundService) GetInboundInfo(ctx context.Context, userID, id, page int) (*InboundInfoPage, error) {
if id < 1 || page < 1 || page > 1_000_000 {
return nil, fmt.Errorf("invalid inbound info page")
}
db := database.GetDB().WithContext(ctx)
snap, err := readInboundInfoSnapshot(ctx, db, userID, id)
if err != nil {
return nil, err
}
start, limit := 0, 1
if snap.tunnel {
start, limit = (page-1)*inboundPeerPageSize, inboundPeerPageSize
}
rows := make([]json.RawMessage, 0, min(limit, max(0, snap.collection.size-start)))
if start < snap.collection.size {
index := 0
err = snap.collection.walk(ctx, func(row json.RawMessage) bool {
if index >= start {
rows = append(rows, append(json.RawMessage(nil), row...))
}
index++
return len(rows) < limit
})
if err != nil {
return nil, err
}
}
info, err := snap.page(rows, start)
if err != nil {
return nil, err
}
if snap.source == "clients" && len(rows) > 0 {
var identity struct{ Email string }
if json.Unmarshal(rows[0], &identity) == nil && identity.Email != "" {
var stats xray.ClientTraffic
err := db.Where("email = ?", identity.Email).Take(&stats).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
if err == nil {
info.Inbound.ClientStats = []xray.ClientTraffic{stats}
s.overlayInboundsClientStats(db, []*model.Inbound{info.Inbound})
}
}
}
return info, nil
}
func (s *InboundService) WalkInboundPeerPages(ctx context.Context, userID, id int, visit func(*InboundInfoPage) error) error {
if id < 1 {
return fmt.Errorf("invalid inbound ID")
}
snap, err := readInboundInfoSnapshot(ctx, database.GetDB(), userID, id)
if err != nil {
return err
}
if !snap.tunnel || snap.collection.size == 0 {
return fmt.Errorf("inbound has no tunnel peers to export")
}
offset := 0
rows := make([]json.RawMessage, 0, inboundPeerPageSize)
emit := func() error {
page, err := snap.page(rows, offset)
if err != nil {
return err
}
if err = visit(page); err != nil {
return err
}
offset += len(rows)
rows = rows[:0]
return nil
}
var writeErr error
err = snap.collection.walk(ctx, func(row json.RawMessage) bool {
rows = append(rows, append(json.RawMessage(nil), row...))
if len(rows) == inboundPeerPageSize {
writeErr = emit()
}
return writeErr == nil
})
if writeErr != nil {
return writeErr
}
if err != nil {
return err
}
if len(rows) > 0 {
return emit()
}
return nil
}