mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-03 16:04:50 +03:00
91d5ff400d
Group compatible client creates by destination and effective payload via the existing clients/add API. Resolve node-local inbound IDs, preserve distinct flow/address/credential payloads, bound delivery concurrency and use a shared four-second remote delivery budget after local commits.
Advance reconciliation fingerprints only for acknowledged intended settings, retaining previous-fingerprint CAS rather than stamping unrelated rebased changes. Preserve FIFO turns, node-wide barriers, dirty generations, durable delete supersession, partial and uncertain delivery recovery and downstream outcomes. Protect later reattachments in final Delete cleanup and complete Create metadata before remote delivery.
Validation: all 12 CI jobs passed on 63e70cda38 (run 46935177853). PostgreSQL logs confirm 21 ordering/grouped-create tests and prior reporter-lock, reconciliation and traffic contention gates; node E2E confirms all four version pairings. Author reports SQLite/PostgreSQL race tests, make verify and isolated full make race.
Author-reported paired PostgreSQL 18 benchmark: 11 -> 1 RPC, fixed 200 ms peer delay 11-target p95 1552.0 -> 731.9 ms, timeout probe 12.41–12.42 -> 4.41–4.50 s. Size-dependent peer cost can instead cause pending delivery (1.74 -> 4.51 s with 0.74 s recovery); four stalled nodes can defer a fifth. Monitor production convergence and pending rate. No general production latency or allocation improvement claimed.
Refs #7299
148 lines
4.1 KiB
Go
148 lines
4.1 KiB
Go
package service
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
"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/wirecodec"
|
|
)
|
|
|
|
// fakeNodeHTTP emulates a node panel over real HTTP, so the master's Remote
|
|
// (tag cache, list fetch, per-op RPC, timeouts) runs for real, not a stub.
|
|
type fakeNodeHTTP struct {
|
|
srv *httptest.Server
|
|
mu sync.Mutex
|
|
tags map[string]int
|
|
hits map[string]int
|
|
caps string
|
|
pendingClientAcks int
|
|
clientAdds []ClientCreatePayload
|
|
clientAddEvents chan ClientCreatePayload
|
|
// hold makes every non-list request block until the master gives up.
|
|
hold bool
|
|
release chan struct{}
|
|
}
|
|
|
|
func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP {
|
|
t.Helper()
|
|
f := &fakeNodeHTTP{
|
|
tags: map[string]int{}, hits: map[string]int{}, release: make(chan struct{}),
|
|
clientAddEvents: make(chan ClientCreatePayload, 16),
|
|
}
|
|
f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
f.mu.Lock()
|
|
w.Header().Set(wirecodec.CapsHeader, f.caps)
|
|
f.mu.Unlock()
|
|
if strings.HasSuffix(r.URL.Path, "/inbounds/list") {
|
|
f.mu.Lock()
|
|
f.hits["list"]++
|
|
type ent struct {
|
|
Id int `json:"id"`
|
|
Tag string `json:"tag"`
|
|
}
|
|
list := make([]ent, 0, len(f.tags))
|
|
for tag, id := range f.tags {
|
|
list = append(list, ent{Id: id, Tag: tag})
|
|
}
|
|
f.mu.Unlock()
|
|
b, _ := json.Marshal(list)
|
|
_, _ = w.Write([]byte(`{"success":true,"msg":"","obj":` + string(b) + `}`))
|
|
return
|
|
}
|
|
f.mu.Lock()
|
|
f.hits[r.URL.Path]++
|
|
hold := f.hold
|
|
pending := f.pendingClientAcks > 0 && strings.Contains(r.URL.Path, "/clients/")
|
|
if pending {
|
|
f.pendingClientAcks--
|
|
}
|
|
f.mu.Unlock()
|
|
if strings.HasSuffix(r.URL.Path, "/clients/add") {
|
|
var payload ClientCreatePayload
|
|
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
f.mu.Lock()
|
|
f.clientAdds = append(f.clientAdds, payload)
|
|
f.mu.Unlock()
|
|
select {
|
|
case f.clientAddEvents <- payload:
|
|
default:
|
|
}
|
|
}
|
|
if hold {
|
|
// Drain first: the server only notices a client disconnect once the
|
|
// body is consumed, and Close would otherwise wait on this forever.
|
|
_, _ = io.Copy(io.Discard, r.Body)
|
|
select {
|
|
case <-r.Context().Done():
|
|
case <-f.release:
|
|
}
|
|
return
|
|
}
|
|
if pending {
|
|
_, _ = w.Write([]byte(`{"success":true,"obj":{"nodePending":true}}`))
|
|
return
|
|
}
|
|
_, _ = w.Write([]byte(`{"success":true,"msg":""}`))
|
|
}))
|
|
t.Cleanup(f.srv.Close)
|
|
// Registered after Close, so it runs first and frees any held handler.
|
|
t.Cleanup(func() { close(f.release) })
|
|
return f
|
|
}
|
|
|
|
func (f *fakeNodeHTTP) setHold(v bool) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
f.hold = v
|
|
}
|
|
|
|
// hitCount is how many requests whose path contains pathPart reached the node.
|
|
func (f *fakeNodeHTTP) hitCount(pathPart string) int {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
n := 0
|
|
for path, c := range f.hits {
|
|
if strings.Contains(path, pathPart) {
|
|
n += c
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
|
|
// realNodeInbound creates a Node row pointing at the fake server plus one
|
|
// inbound on it, with NO runtime override so RuntimeFor builds a real Remote.
|
|
func realNodeInbound(t *testing.T, f *fakeNodeHTTP, port int, clients []model.Client) *model.Inbound {
|
|
t.Helper()
|
|
hostPart, portStr, _ := strings.Cut(strings.TrimPrefix(f.srv.URL, "http://"), ":")
|
|
srvPort, err := strconv.Atoi(portStr)
|
|
if err != nil {
|
|
t.Fatalf("parse fake node port: %v", err)
|
|
}
|
|
node := &model.Node{
|
|
Name: fmt.Sprintf("%s-%d", t.Name(), port), Scheme: "http", Address: hostPart, Port: srvPort,
|
|
BasePath: "/", ApiToken: "tok", Enable: true, Status: "online",
|
|
AllowPrivateAddress: true, TlsVerifyMode: "verify",
|
|
}
|
|
if err := database.GetDB().Create(node).Error; err != nil {
|
|
t.Fatalf("create node: %v", err)
|
|
}
|
|
ib := nodeInbound(t, node.Id, port, clients)
|
|
f.mu.Lock()
|
|
f.tags[ib.Tag] = 100 + port%100
|
|
f.mu.Unlock()
|
|
return ib
|
|
}
|