fix(xray): keep the config snapshot true after a runtime inbound change

The process snapshot is what a reconcile diffs the desired config against,
so it has to describe what the core is running. The local runtime added and
removed inbounds over gRPC without telling it:

- An inbound added at runtime was missing from the snapshot. The next
  reconcile saw it as new, hit "existing tag", and replaced the handler: the
  listener closed and every client on it was cut. On a WireGuard inbound all
  peers lost their tunnel for about 15 s, once, at the first device or
  client change after the inbound was created.
- An inbound removed at runtime stayed in the snapshot. Enabling it again
  through a path that only asks for a reconcile diffed as "no change", and
  the core never got it back.

The local runtime now reports both to the process, which swaps in an edited
copy of the snapshot. The wiring moved into XrayService.LocalRuntimeDeps so
the tests run the panel's own bridge against an in-process core and compare
handler identity before and after the reconcile.

User-level drift is left to the reconcile, which already settles it without
touching a session: a known WireGuard peer is updated in place, any other
user is re-added by credential, and a missing one is skipped.
This commit is contained in:
Sanaei
2026-11-25 11:02:24 +03:30
parent 05e8f17268
commit 6aefb14569
6 changed files with 181 additions and 9 deletions
+16 -3
View File
@@ -26,6 +26,10 @@ type LocalDeps struct {
APIPort func() int
SetNeedRestart func()
RequestReconcile func()
// InboundApplied and InboundRemoved report what an op changed in the running core,
// so the config snapshot a reconcile diffs against stays true.
InboundApplied func(*xray.InboundConfig)
InboundRemoved func(tag string)
}
type Local struct {
@@ -100,13 +104,18 @@ func (l *Local) AddInbound(_ context.Context, ib *model.Inbound) error {
}
return err
}
body, err := json.MarshalIndent(ib.GenXrayInboundConfig(), "", " ")
config := ib.GenXrayInboundConfig()
body, err := json.MarshalIndent(config, "", " ")
if err != nil {
return err
}
return l.withAPI(func(api *xray.XrayAPI) error {
err = l.withAPI(func(api *xray.XrayAPI) error {
return api.AddInbound(body)
})
if err == nil && l.deps.InboundApplied != nil {
l.deps.InboundApplied(config)
}
return err
}
func (l *Local) DelInbound(_ context.Context, ib *model.Inbound) error {
@@ -131,9 +140,13 @@ func (l *Local) DelInbound(_ context.Context, ib *model.Inbound) error {
}
return nil
}
return l.withAPI(func(api *xray.XrayAPI) error {
err := l.withAPI(func(api *xray.XrayAPI) error {
return api.DelInbound(ib.Tag)
})
if err == nil && l.deps.InboundRemoved != nil {
l.deps.InboundRemoved(ib.Tag)
}
return err
}
func (l *Local) UpdateInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
@@ -0,0 +1,98 @@
package service
import (
"context"
"path/filepath"
"slices"
"testing"
"github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/features/inbound"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
// localRuntimeOnCore wires the panel's own runtime deps to an in-process core, whose
// handlers the test can then tell apart by identity.
func localRuntimeOnCore(t *testing.T, cfg *xray.Config) (*core.Instance, *xray.Process, *runtime.Local) {
t.Helper()
instance, _ := startIsolationInstance(t, cfg)
process := xray.NewTestProcess(cfg, filepath.Join(t.TempDir(), "config.json"))
previousProcess, previousResult := xrayState.snapshot()
xrayState.replace(process)
t.Cleanup(func() {
xrayState.mu.Lock()
xrayState.process = previousProcess
xrayState.result = previousResult
xrayState.mu.Unlock()
})
deps := (&XrayService{}).LocalRuntimeDeps()
deps.APIPort = func() int { return cfg.InboundConfigs[0].Port }
return instance, process, runtime.NewLocal(deps)
}
func coreInboundHandler(t *testing.T, instance *core.Instance, tag string) inbound.Handler {
t.Helper()
handler, err := instance.GetFeature(inbound.ManagerType()).(inbound.Manager).GetHandler(context.Background(), tag)
if err != nil {
return nil
}
return handler
}
func liveTestInbound(t *testing.T) *model.Inbound {
t.Helper()
return &model.Inbound{
Tag: "added-live", Listen: "127.0.0.1", Port: freeLoopbackPort(t), Protocol: model.VLESS, Enable: true,
Settings: `{"clients":[{"id":"7c1c1d1e-0d0a-4b6e-9d5c-2b6f1d0c9a11","email":"live@test"}],"decryption":"none"}`,
StreamSettings: `{"network":"tcp","security":"none"}`,
}
}
func withInbound(cfg *xray.Config, ib *model.Inbound) *xray.Config {
next := *cfg
next.InboundConfigs = append(slices.Clone(cfg.InboundConfigs), *ib.GenXrayInboundConfig())
return &next
}
func TestReconcileKeepsAnInboundAddedAtRuntime(t *testing.T) {
cfg := isolationConfig(t)
instance, process, local := localRuntimeOnCore(t, cfg)
ib := liveTestInbound(t)
if err := local.AddInbound(context.Background(), ib); err != nil {
t.Fatal(err)
}
added := coreInboundHandler(t, instance, ib.Tag)
if added == nil {
t.Fatal("the runtime add did not reach the core")
}
if applied, err := (&XrayService{}).tryHotApply(process, withInbound(cfg, ib)); err != nil || !applied {
t.Fatalf("reconcile: applied=%t err=%v", applied, err)
}
if coreInboundHandler(t, instance, ib.Tag) != added {
t.Fatal("the reconcile rebuilt an inbound the core was already running: its listener closed and its clients were cut")
}
}
func TestReconcileRestoresAnInboundRemovedAtRuntime(t *testing.T) {
ib := liveTestInbound(t)
cfg := withInbound(isolationConfig(t), ib)
instance, process, local := localRuntimeOnCore(t, cfg)
if err := local.DelInbound(context.Background(), ib); err != nil {
t.Fatal(err)
}
if coreInboundHandler(t, instance, ib.Tag) != nil {
t.Fatal("the runtime removal did not reach the core")
}
// The row is enabled again by a path that only asks for a reconcile.
if applied, err := (&XrayService{}).tryHotApply(process, cfg); err != nil || !applied {
t.Fatalf("reconcile: applied=%t err=%v", applied, err)
}
if coreInboundHandler(t, instance, ib.Tag) == nil {
t.Fatal("the reconcile left out an inbound the core no longer runs: the snapshot still claimed it")
}
}
@@ -40,6 +40,12 @@ func isolationConfig(t *testing.T, relays ...xray.InboundConfig) *xray.Config {
}
func startIsolationCore(t *testing.T, cfg *xray.Config) *xray.XrayAPI {
t.Helper()
_, api := startIsolationInstance(t, cfg)
return api
}
func startIsolationInstance(t *testing.T, cfg *xray.Config) (*core.Instance, *xray.XrayAPI) {
t.Helper()
var config conf.Config
if err := json.Unmarshal(mustJSON(t, cfg), &config); err != nil {
@@ -62,7 +68,7 @@ func startIsolationCore(t *testing.T, cfg *xray.Config) *xray.XrayAPI {
t.Fatal(err)
}
t.Cleanup(api.Close)
return api
return instance, api
}
func assertIsolationRelay(t *testing.T, relay xray.InboundConfig, email string) {
+25
View File
@@ -0,0 +1,25 @@
package service
import (
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
// LocalRuntimeDeps bridges the local runtime to the core this service owns.
func (s *XrayService) LocalRuntimeDeps() runtime.LocalDeps {
return runtime.LocalDeps{
APIPort: s.GetXrayAPIPort,
SetNeedRestart: s.SetToNeedRestart,
RequestReconcile: s.SetToNeedReconcile,
InboundApplied: func(inbound *xray.InboundConfig) {
if process := currentXrayProcess(); process != nil {
process.PutInbound(inbound)
}
},
InboundRemoved: func(tag string) {
if process := currentXrayProcess(); process != nil {
process.DropInbound(tag)
}
},
}
}
+1 -5
View File
@@ -572,11 +572,7 @@ func (s *Server) start(restartXray bool, startTgBot bool) (err error) {
// add/update/delete to either the local xray or a remote node panel.
// The closures bridge into XrayService (which owns the running xray
// process state) without forcing the runtime package to import service.
mgr := runtime.NewManager(runtime.LocalDeps{
APIPort: func() int { return s.xrayService.GetXrayAPIPort() },
SetNeedRestart: func() { s.xrayService.SetToNeedRestart() },
RequestReconcile: func() { s.xrayService.SetToNeedReconcile() },
})
mgr := runtime.NewManager(s.xrayService.LocalRuntimeDeps())
runtime.SetManager(mgr)
mgr.SetNodeEgressResolver(&s.settingService)
// Supply the master client certificate for nodes in mtls mode. Issued lazily
+34
View File
@@ -10,6 +10,7 @@ import (
"os/exec"
"path/filepath"
"runtime"
"slices"
"sort"
"strings"
"sync"
@@ -321,6 +322,39 @@ func (p *Process) SetConfig(config *Config) {
p.config = config
}
// PutInbound records an inbound a runtime op placed in the running core, so the next
// reconcile compares against it instead of adding the tag a second time.
func (p *Process) PutInbound(inbound *InboundConfig) {
p.editInbounds(func(inbounds []InboundConfig) []InboundConfig {
for i := range inbounds {
if inbounds[i].Tag == inbound.Tag {
inbounds[i] = *inbound
return inbounds
}
}
return append(inbounds, *inbound)
})
}
// DropInbound records that a runtime op removed the tag's inbound from the running core.
func (p *Process) DropInbound(tag string) {
p.editInbounds(func(inbounds []InboundConfig) []InboundConfig {
return slices.DeleteFunc(inbounds, func(inbound InboundConfig) bool { return inbound.Tag == tag })
})
}
// editInbounds swaps in a copy: readers keep the snapshot GetConfig handed them.
func (p *Process) editInbounds(edit func([]InboundConfig) []InboundConfig) {
p.mu.Lock()
defer p.mu.Unlock()
if p.config == nil {
return
}
next := *p.config
next.InboundConfigs = edit(slices.Clone(p.config.InboundConfigs))
p.config = &next
}
// PersistConfig writes the current configuration snapshot to the config file,
// keeping it in step after a hot apply (Start only writes it on a cold start).
func (p *Process) PersistConfig() error {