Files
mirror-3x-ui/internal/nodee2e/node_snapshot_test.go
T
Hamed 0afa11ddff fix(nodes): share lightweight remote inbound catalog refreshes (#7313)
Replace full inbound/client-list downloads on cold remote ID lookups with an owner-scoped six-field catalog projected directly from the database. Coalesce concurrent catalog refreshes per remote while preserving independent caller cancellation and rejecting stale ID mappings after topology mutations.

Seed reconciliation from the catalog, create missing inbounds directly, preserve prefixed/adopted aliases and invalidate pushed state when remote IDs change. Avoid invalidating catalog generations on unchanged-ID settings pushes. Retain client-membership-aware reconciliation state and legacy full-list fallback only on HTTP 404/405.

Cover permissions, query projection, concurrent refresh/cancellation, deletion/recreation, reconciliation request counts and mixed-version node compatibility. Integrated CI and Docs CI passed, including race, node E2E and PostgreSQL catalog projection. Synthetic response-size comparison is not a production latency benchmark.

Fixes #7303.
2026-12-03 03:26:44 +03:30

215 lines
7.5 KiB
Go

package nodee2e
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"os"
"slices"
"strconv"
"sync/atomic"
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
)
func TestNodeSnapshotVersionCompatibility(t *testing.T) {
current := panelBinary(t)
old := os.Getenv("XUI_NODE_E2E_OLD_BINARY")
for _, version := range []struct {
name string
master, node string
compact bool
}{
{"new-master-new-node", current, current, true},
{"new-master-old-node", current, old, false},
{"old-master-new-node", old, current, false},
{"old-master-old-node", old, old, false},
} {
t.Run(version.name, func(t *testing.T) {
if version.master == "" || version.node == "" {
t.Skip("set XUI_NODE_E2E_OLD_BINARY to a baseline panel binary")
}
t.Parallel()
master := newPanel(t, version.master, "master")
node := newPanel(t, version.node, "node")
token := node.mintToken("snapshot-link", "node-sync")
master.start()
node.start()
var catalogs, lists, compact, full, unchanged, clientAdds atomic.Int32
target, err := url.Parse(node.url())
if err != nil {
t.Fatal(err)
}
proxy := httputil.NewSingleHostReverseProxy(target)
proxy.ModifyResponse = func(response *http.Response) error {
if response.Request.URL.Path != "/panel/api/inbounds/trafficSnapshot" || response.StatusCode != http.StatusOK {
return nil
}
data, err := io.ReadAll(response.Body)
_ = response.Body.Close()
if err != nil {
return err
}
response.Body = io.NopCloser(bytes.NewReader(data))
if response.Header.Get("Content-Encoding") == "gzip" {
reader, err := gzip.NewReader(bytes.NewReader(data))
if err != nil {
return err
}
decoded, readErr := io.ReadAll(reader)
_ = reader.Close()
if readErr != nil {
return readErr
}
data = decoded
}
var env struct {
Obj struct {
Structure json.RawMessage `json:"structure"`
} `json:"obj"`
}
if err := json.Unmarshal(data, &env); err != nil {
return err
}
if len(env.Obj.Structure) > 0 && string(env.Obj.Structure) != "null" {
full.Add(1)
} else {
unchanged.Add(1)
}
return nil
}
front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
switch req.URL.Path {
case "/panel/api/inbounds/catalog":
catalogs.Add(1)
case "/panel/api/inbounds/list":
lists.Add(1)
case "/panel/api/inbounds/trafficSnapshot":
compact.Add(1)
case "/panel/api/clients/add":
clientAdds.Add(1)
}
proxy.ServeHTTP(w, req)
}))
t.Cleanup(front.Close)
address, err := url.Parse(front.URL)
if err != nil {
t.Fatal(err)
}
port, err := strconv.Atoi(address.Port())
if err != nil {
t.Fatal(err)
}
inboundPort := freePort(t)
secondaryPort := freePort(t)
var source inboundView
if err := json.Unmarshal(node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix", inboundPort, nil, vlessClient("matrix-first"))), &source); err != nil {
t.Fatal(err)
}
params := map[string]any{"name": "matrix-node", "scheme": "http", "address": address.Hostname(), "port": port, "basePath": "/", "apiToken": token, "enable": true, "allowPrivateAddress": true}
if version.master == current {
var options []inboundView
obj := master.call(http.MethodPost, "/panel/api/nodes/inbounds", params)
if err := json.Unmarshal(obj, &options); err != nil || len(options) != 1 || options[0].Id != source.Id {
t.Fatalf("read node options: %s, %v", obj, err)
}
var wantLists int32
if version.node != current {
wantLists = 1
}
if got := lists.Swap(0); catalogs.Load() != 1 || got != wantLists {
t.Fatalf("node options used catalog=%d and full list=%d, want 1 and %d", catalogs.Load(), got, wantLists)
}
}
if version.master == current {
node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix-secondary", secondaryPort, nil))
}
master.call(http.MethodPost, "/panel/api/nodes/add", params)
eventually(t, settleTimeout, "version pair synchronizes and reaches steady state", func() (bool, string) {
ib, ok := master.inboundOnPort(inboundPort)
ready := lists.Load() >= 3
if version.compact {
ready = unchanged.Load() >= 2
}
return ok && hasAll(ib.emails(), "matrix-first") && ready, fmt.Sprintf("adopted=%v lists=%d compact=%d unchanged=%d", ok, lists.Load(), compact.Load(), unchanged.Load())
})
if !version.compact && compact.Load() != 0 {
t.Fatalf("legacy peer received compact calls: %d", compact.Load())
}
before := full.Load()
node.call(http.MethodPost, "/panel/api/clients/add", map[string]any{"client": map[string]any{"email": "matrix-added", "enable": true}, "inboundIds": []int{source.Id}})
eventually(t, settleTimeout, "node edit after unchanged polls reaches master", func() (bool, string) {
ib, ok := master.inboundOnPort(inboundPort)
return ok && hasAll(ib.emails(), "matrix-first", "matrix-added"), fmt.Sprint(ib.emails())
})
if version.compact && full.Load() <= before {
t.Fatal("node edit did not refresh catalog")
}
if version.compact {
before = full.Load()
node.stop()
node.start()
eventually(t, settleTimeout, "node restart invalidates the old catalog", func() (bool, string) { return full.Load() > before, fmt.Sprint(full.Load()) })
before = full.Load()
master.stop()
master.start()
eventually(t, settleTimeout, "master restart reacquires complete structure", func() (bool, string) { return full.Load() > before, fmt.Sprint(full.Load()) })
}
if version.master == current {
first, hasFirst := master.inboundOnPort(inboundPort)
second, hasSecond := master.inboundOnPort(secondaryPort)
if !hasFirst || !hasSecond {
t.Fatal("master did not adopt both inbounds")
}
const email = "matrix-shared-create"
master.call(http.MethodPost, "/panel/api/clients/add", map[string]any{
"client": map[string]any{"email": email, "enable": true}, "inboundIds": []int{first.Id, second.Id},
})
if got := clientAdds.Load(); got != 1 {
t.Fatalf("node-sync received %d add requests, want one", got)
}
var tags []string
for _, port := range []int{inboundPort, secondaryPort} {
if ib, ok := node.inboundOnPort(port); !ok || ib.client(email) == nil {
t.Fatalf("node did not apply the grouped client on port %d", port)
} else {
tags = append(tags, ib.Tag)
}
}
admin := runtime.NewRemote(&model.Node{
Name: "matrix-admin", Scheme: "http", Address: address.Hostname(), Port: port,
BasePath: "/", ApiToken: node.token, Enable: true, AllowPrivateAddress: true,
}, nil)
const adminEmail = "matrix-admin-create"
raw, err := json.Marshal(vlessClient(adminEmail))
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
if _, ack, err := admin.AddClientGroup(ctx, tags, raw); err != nil || !slices.Equal(ack, []bool{true, true}) {
t.Fatalf("admin grouped add acknowledged %v, err=%v", ack, err)
}
if got := clientAdds.Load(); got != 2 {
t.Fatalf("admin sent %d add requests, want one", got-1)
}
for _, port := range []int{inboundPort, secondaryPort} {
if ib, ok := node.inboundOnPort(port); !ok || ib.client(adminEmail) == nil {
t.Fatalf("admin grouped client absent on port %d", port)
}
}
}
})
}
}