Files
mirror-3x-ui/internal/database/model/model_test.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

334 lines
10 KiB
Go

package model
import (
"encoding/json"
"reflect"
"strings"
"testing"
)
func TestInboundMarshalJSONNestsObjectFields(t *testing.T) {
in := Inbound{
Id: 7,
Protocol: VLESS,
Port: 443,
Settings: `{"clients":[],"decryption":"none"}`,
StreamSettings: `{"network":"tcp"}`,
Sniffing: `{"enabled":true}`,
}
out, err := json.Marshal(in)
if err != nil {
t.Fatalf("Marshal failed: %v", err)
}
var parsed map[string]any
if err := json.Unmarshal(out, &parsed); err != nil {
t.Fatalf("output is not valid JSON: %v", err)
}
for _, field := range []string{"settings", "streamSettings", "sniffing"} {
if _, ok := parsed[field].(map[string]any); !ok {
t.Errorf("expected %s to marshal as a JSON object, got %T", field, parsed[field])
}
}
if strings.Contains(string(out), `"settings":"`) {
t.Errorf("settings should not be emitted as a JSON string: %s", out)
}
}
func TestInboundMarshalJSONEmptyFieldsBecomeNull(t *testing.T) {
in := Inbound{Id: 1, Protocol: VLESS}
out, err := json.Marshal(in)
if err != nil {
t.Fatalf("Marshal failed: %v", err)
}
var parsed map[string]any
if err := json.Unmarshal(out, &parsed); err != nil {
t.Fatalf("output is not valid JSON: %v", err)
}
for _, field := range []string{"settings", "streamSettings", "sniffing"} {
if parsed[field] != nil {
t.Errorf("expected %s to be null, got %v", field, parsed[field])
}
}
}
func TestInboundUnmarshalJSONAcceptsBothShapes(t *testing.T) {
cases := []struct {
name string
body string
}{
{
name: "nested objects (modern)",
body: `{"id":1,"settings":{"clients":[],"decryption":"none"},"streamSettings":{"network":"tcp"},"sniffing":{"enabled":true}}`,
},
{
name: "JSON-encoded strings (legacy)",
body: `{"id":1,"settings":"{\"clients\":[],\"decryption\":\"none\"}","streamSettings":"{\"network\":\"tcp\"}","sniffing":"{\"enabled\":true}"}`,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var in Inbound
if err := json.Unmarshal([]byte(tc.body), &in); err != nil {
t.Fatalf("Unmarshal failed: %v", err)
}
if !strings.Contains(in.Settings, `"decryption":"none"`) {
t.Errorf("Settings not normalised: %q", in.Settings)
}
if !strings.Contains(in.StreamSettings, `"network":"tcp"`) {
t.Errorf("StreamSettings not normalised: %q", in.StreamSettings)
}
if !strings.Contains(in.Sniffing, `"enabled":true`) {
t.Errorf("Sniffing not normalised: %q", in.Sniffing)
}
})
}
}
func TestInboundMarshalJSONInvalidTextFallsBackToString(t *testing.T) {
in := Inbound{Id: 1, Settings: "not json at all"}
out, err := json.Marshal(in)
if err != nil {
t.Fatalf("Marshal failed: %v", err)
}
if !strings.Contains(string(out), `"settings":"not json at all"`) {
t.Errorf("expected invalid settings text to be wrapped as a JSON string, got %s", out)
}
}
func TestClientRecordMarshalJSONNestsReverse(t *testing.T) {
rec := ClientRecord{Id: 1, Email: "alice@example.com", Reverse: `{"tag":"vless-in"}`}
out, err := json.Marshal(rec)
if err != nil {
t.Fatalf("Marshal failed: %v", err)
}
var parsed map[string]any
if err := json.Unmarshal(out, &parsed); err != nil {
t.Fatalf("output is not valid JSON: %v", err)
}
obj, ok := parsed["reverse"].(map[string]any)
if !ok {
t.Fatalf("expected reverse to marshal as a JSON object, got %T", parsed["reverse"])
}
if obj["tag"] != "vless-in" {
t.Errorf("expected tag to be preserved, got %v", obj["tag"])
}
}
func TestClientRecordMarshalJSONEmptyReverseIsNull(t *testing.T) {
rec := ClientRecord{Id: 1, Email: "alice@example.com"}
out, err := json.Marshal(rec)
if err != nil {
t.Fatalf("Marshal failed: %v", err)
}
var parsed map[string]any
if err := json.Unmarshal(out, &parsed); err != nil {
t.Fatalf("output is not valid JSON: %v", err)
}
if parsed["reverse"] != nil {
t.Errorf("expected reverse to be null, got %v", parsed["reverse"])
}
}
func TestClientRecordUnmarshalJSONAcceptsBothShapes(t *testing.T) {
cases := []struct {
name string
body string
}{
{name: "nested object", body: `{"id":1,"reverse":{"tag":"vless-in"}}`},
{name: "legacy string", body: `{"id":1,"reverse":"{\"tag\":\"vless-in\"}"}`},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var rec ClientRecord
if err := json.Unmarshal([]byte(tc.body), &rec); err != nil {
t.Fatalf("Unmarshal failed: %v", err)
}
if !strings.Contains(rec.Reverse, `"tag":"vless-in"`) {
t.Errorf("Reverse not normalised: %q", rec.Reverse)
}
})
}
}
func TestInboundClientIpsMarshalJSONNestsArray(t *testing.T) {
row := InboundClientIps{Id: 1, ClientEmail: "alice@example.com", Ips: `[{"ip":"1.2.3.4","timestamp":1700000000}]`}
out, err := json.Marshal(row)
if err != nil {
t.Fatalf("Marshal failed: %v", err)
}
var parsed map[string]any
if err := json.Unmarshal(out, &parsed); err != nil {
t.Fatalf("output is not valid JSON: %v", err)
}
arr, ok := parsed["ips"].([]any)
if !ok {
t.Fatalf("expected ips to marshal as a JSON array, got %T", parsed["ips"])
}
if len(arr) != 1 {
t.Errorf("expected 1 entry, got %d", len(arr))
}
}
func TestInboundClientIpsUnmarshalJSONAcceptsBothShapes(t *testing.T) {
cases := []struct {
name string
body string
}{
{name: "nested array", body: `{"id":1,"ips":[{"ip":"1.2.3.4","timestamp":1}]}`},
{name: "legacy string", body: `{"id":1,"ips":"[{\"ip\":\"1.2.3.4\",\"timestamp\":1}]"}`},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var row InboundClientIps
if err := json.Unmarshal([]byte(tc.body), &row); err != nil {
t.Fatalf("Unmarshal failed: %v", err)
}
if !strings.Contains(row.Ips, `"ip":"1.2.3.4"`) {
t.Errorf("Ips not normalised: %q", row.Ips)
}
})
}
}
func TestStripInboundXhttpClientFields_RemovesClientOnlyKnobs(t *testing.T) {
stream := `{
"network": "xhttp",
"security": "reality",
"xhttpSettings": {
"path": "/app",
"host": "example.com",
"mode": "stream-one",
"xmux": { "maxConcurrency": "16-32" },
"downloadSettings": { "network": "xhttp" },
"scMinPostsIntervalMs": "20-40",
"uplinkChunkSize": 4096,
"noGRPCHeader": true
}
}`
out, changed := StripInboundXhttpClientFields(stream)
if !changed {
t.Fatal("expected client-only xhttp fields to be stripped")
}
if strings.Contains(out, `"xmux"`) {
t.Fatalf("xmux should be removed from xray config stream: %s", out)
}
for _, key := range []string{"downloadSettings", "scMinPostsIntervalMs", "uplinkChunkSize", "noGRPCHeader"} {
if strings.Contains(out, `"`+key+`"`) {
t.Fatalf("%s should be removed from xray config stream: %s", key, out)
}
}
var parsed map[string]any
if err := json.Unmarshal([]byte(out), &parsed); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
xhttp := parsed["xhttpSettings"].(map[string]any)
if xhttp["path"] != "/app" || xhttp["host"] != "example.com" {
t.Fatalf("server fields must survive: %#v", xhttp)
}
}
func TestStripInboundXhttpClientFields_UnchangedWithoutClientFields(t *testing.T) {
stream := `{"network":"xhttp","xhttpSettings":{"path":"/app","mode":"stream-one"}}`
out, changed := StripInboundXhttpClientFields(stream)
if changed {
t.Fatalf("expected no change, got: %s", out)
}
if out != stream {
t.Fatalf("unchanged stream must be returned verbatim")
}
}
func TestStripInboundXhttpClientFields_NonXhttpPassthrough(t *testing.T) {
stream := `{"network":"ws","wsSettings":{"path":"/"}}`
out, changed := StripInboundXhttpClientFields(stream)
if changed || out != stream {
t.Fatalf("non-xhttp stream must pass through unchanged, got changed=%v out=%s", changed, out)
}
}
func TestGenXrayInboundConfig_OmitsInboundXmuxButDbRowUnchanged(t *testing.T) {
stream := `{
"network": "xhttp",
"xhttpSettings": {
"path": "/app",
"mode": "stream-one",
"xmux": { "maxConcurrency": "16-32", "hMaxRequestTimes": "600-900" }
}
}`
in := Inbound{
Protocol: VLESS,
Port: 443,
Listen: "0.0.0.0",
Tag: "in-xhttp",
Settings: `{"clients":[],"decryption":"none"}`,
StreamSettings: stream,
}
cfg := in.GenXrayInboundConfig()
if strings.Contains(string(cfg.StreamSettings), `"xmux"`) {
t.Fatalf("GenXrayInboundConfig must not emit xmux: %s", cfg.StreamSettings)
}
if strings.Contains(in.StreamSettings, `"xmux"`) == false {
t.Fatal("inbound row streamSettings must still carry xmux for subscriptions")
}
}
// nil must survive (it means "leave the stored binding alone"), while an empty or
// all-invalid list must come back empty so it clears.
func TestNormalizeClientHostRuleIds(t *testing.T) {
for _, tt := range []struct {
name string
in []int
want []int
}{
{"nil preserves", nil, nil},
{"empty clears", []int{}, []int{}},
{"dedupe keeps order", []int{3, 2, 3, 2}, []int{3, 2}},
{"non-positive dropped", []int{0, -1, 2, 0, 3}, []int{2, 3}},
{"all non-positive clears", []int{0, -2}, []int{}},
} {
t.Run(tt.name, func(t *testing.T) {
got := NormalizeClientHostRuleIds(tt.in)
if (got == nil) != (tt.want == nil) || !reflect.DeepEqual(got, tt.want) {
t.Fatalf("NormalizeClientHostRuleIds(%v) = %#v, want %#v", tt.in, got, tt.want)
}
})
}
}
// The panel keeps encryption beside decryption only to build share links; the
// core's inbound takes decryption alone, and settings without the key pass as stored.
func TestGenXrayInboundConfigDropsVlessEncryption(t *testing.T) {
tests := []struct {
name, settings, want string
}{
{
name: "encryption set",
settings: `{"encryption":"none","decryption":"none","clients":[{"id":"u","email":"a@x"}]}`,
want: "{\n \"clients\": [\n {\n \"email\": \"a@x\",\n \"id\": \"u\"\n }\n ],\n \"decryption\": \"none\"\n}",
},
{
name: "encryption null",
settings: `{"encryption":null,"clients":[]}`,
want: "{\n \"clients\": []\n}",
},
{
name: "no encryption",
settings: `{"decryption":"none", "clients":[]}`,
want: `{"decryption":"none", "clients":[]}`,
},
{
name: "not an object",
settings: `{"encryption":`,
want: `{"encryption":`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
in := Inbound{Protocol: VLESS, Port: 443, Settings: tt.settings}
if got := string(in.GenXrayInboundConfig().Settings); got != tt.want {
t.Fatalf("core settings = %s\nwant %s", got, tt.want)
}
})
}
}