Files
mirror-3x-ui/internal/web/service/inbound_settings_commit.go
T
Sanaei e7717fb185 perf(inbounds): decode an inbound's settings once per save
Saving an inbound ran its settings through about twenty full decodes and
four encodes: every step of the save took the JSON as a string and parsed
all of it again, most of them to read one top-level key. With 100,000
clients the settings are 45 MB, and a form save that only changed the
remark took 5.4 s over HTTP.

The save now decodes the stored settings once, keeps the result through
the client steps (stored clients back, timestamps, Shadowsocks keys,
Vision flow) and encodes once, and it parses the typed client list once
per side instead of five times. Those steps are split into a core that
works on the decoded clients and the string wrapper their other callers
keep using.

The readers that only need one key no longer decode the client list:
the transport bits of a port check, the Shadowsocks method, and the
check for the VLESS encryption key that the core config must not carry.
The runtime inbound drops that key while it is decoded anyway, and the
node payload decodes its settings only when there are fallbacks to add.

Same save on the same data: 5.4 s -> 2.7 s over HTTP on a running panel,
with the stored settings byte-identical before and after.

Refs #7207
2026-11-26 12:10:11 +03:30

204 lines
5.2 KiB
Go

package service
import (
"encoding/json"
"reflect"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"gorm.io/gorm"
)
// commitInboundClientSettings writes a client op's edit (base → ib.Settings) onto
// the settings committed now: a traffic tick after the op's read must survive.
func commitInboundClientSettings(tx *gorm.DB, ib *model.Inbound, base string) error {
defer InvalidateSubData()
var current []string
if err := tx.Model(&model.Inbound{}).Where("id = ?", ib.Id).Pluck("settings", &current).Error; err != nil {
return err
}
if len(current) == 1 && current[0] != base {
merged, err := rebaseClientSettings(base, ib.Settings, current[0])
if err != nil {
return err
}
ib.Settings = merged
}
return tx.Model(&model.Inbound{}).Where("id = ?", ib.Id).Update("settings", ib.Settings).Error
}
// rebaseClientSettings three-way merges settings JSON: every key and client field
// ours left as base had it takes current's value; clients are matched by email.
func rebaseClientSettings(base, ours, current string) (string, error) {
var baseM, oursM, curM map[string]any
for _, p := range []struct {
raw string
dst *map[string]any
}{{base, &baseM}, {ours, &oursM}, {current, &curM}} {
if err := json.Unmarshal([]byte(p.raw), p.dst); err != nil {
return "", err
}
}
out := mergeFields(baseM, oursM, curM)
baseClients, _ := baseM["clients"].([]any)
oursClients, _ := oursM["clients"].([]any)
curClients, _ := curM["clients"].([]any)
if _, has := oursM["clients"]; has {
out["clients"] = mergeClientLists(baseClients, oursClients, curClients)
}
b, err := json.MarshalIndent(out, "", " ")
if err != nil {
return "", err
}
return string(b), nil
}
func mergeFields(base, ours, current map[string]any) map[string]any {
out := make(map[string]any, len(current)+len(ours))
for k, v := range current {
out[k] = v
}
keys := make(map[string]struct{}, len(base)+len(ours))
for k := range base {
keys[k] = struct{}{}
}
for k := range ours {
keys[k] = struct{}{}
}
for k := range keys {
bv, inBase := base[k]
ov, inOurs := ours[k]
if inBase == inOurs && reflect.DeepEqual(bv, ov) {
continue
}
if inOurs {
out[k] = ov
} else {
delete(out, k)
}
}
return out
}
func clientEntryEmail(entry any) (map[string]any, string) {
m, ok := entry.(map[string]any)
if !ok {
return nil, ""
}
email, _ := m["email"].(string)
return m, email
}
func indexClientsByEmail(list []any) map[string]map[string]any {
out := make(map[string]map[string]any, len(list))
for _, entry := range list {
if m, email := clientEntryEmail(entry); email != "" {
out[email] = m
}
}
return out
}
// mergeClientLists keeps ours' order. A client ours removed stays removed; one a
// concurrent writer added or removed keeps that change unless ours edited it.
func mergeClientLists(base, ours, current []any) []any {
baseBy := indexClientsByEmail(base)
curBy := indexClientsByEmail(current)
out := make([]any, 0, len(ours)+len(current))
placed := make(map[string]struct{}, len(ours))
for _, entry := range ours {
o, email := clientEntryEmail(entry)
if email == "" {
out = append(out, entry)
continue
}
placed[email] = struct{}{}
b, inBase := baseBy[email]
c, inCur := curBy[email]
switch {
case !inBase:
out = append(out, o)
case !inCur:
if !reflect.DeepEqual(b, o) {
out = append(out, o)
}
default:
out = append(out, mergeFields(b, o, c))
}
}
for _, entry := range current {
c, email := clientEntryEmail(entry)
if email == "" {
continue
}
if _, done := placed[email]; done {
continue
}
if _, inBase := baseBy[email]; !inBase {
out = append(out, c)
}
}
return out
}
// keepStoredClients puts the stored client list back into an inbound save's
// payload: clients change through the client endpoints, never this form.
func keepStoredClients(payload, stored map[string]any) bool {
storedClients, has := stored["clients"]
if reflect.DeepEqual(payload["clients"], storedClients) {
return false
}
if has {
payload["clients"] = storedClients
} else {
delete(payload, "clients")
}
return true
}
// stampClientTimestamps fills a missing created_at / updated_at from the stored entry of
// the same email, or created_at with now: an inbound save never bumps a client's stamps.
func stampClientTimestamps(clients, stored []any, now int64) bool {
storedCreated := make(map[string]int64, len(stored))
storedUpdated := make(map[string]int64, len(stored))
for _, entry := range stored {
m, ok := entry.(map[string]any)
if !ok {
continue
}
email, ok := m["email"].(string)
if !ok {
continue
}
if v, ok := m["created_at"].(float64); ok {
storedCreated[email] = int64(v)
}
if v, ok := m["updated_at"].(float64); ok {
storedUpdated[email] = int64(v)
}
}
changed := false
for _, entry := range clients {
m, ok := entry.(map[string]any)
if !ok {
continue
}
email, _ := m["email"].(string)
if _, has := m["created_at"]; !has {
if v := storedCreated[email]; v > 0 {
m["created_at"] = v
} else {
m["created_at"] = now
}
changed = true
}
if _, has := m["updated_at"]; !has {
if v := storedUpdated[email]; v > 0 {
m["updated_at"] = v
changed = true
}
}
}
return changed
}