diff --git a/internal/web/runtime/local.go b/internal/web/runtime/local.go index 7db656833..a2e80bfd9 100644 --- a/internal/web/runtime/local.go +++ b/internal/web/runtime/local.go @@ -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 { diff --git a/internal/web/service/runtime_inbound_snapshot_test.go b/internal/web/service/runtime_inbound_snapshot_test.go new file mode 100644 index 000000000..352fbbedf --- /dev/null +++ b/internal/web/service/runtime_inbound_snapshot_test.go @@ -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") + } +} diff --git a/internal/web/service/tuic_relay_isolation_test.go b/internal/web/service/tuic_relay_isolation_test.go index 2d837e6a1..bc19cfc3c 100644 --- a/internal/web/service/tuic_relay_isolation_test.go +++ b/internal/web/service/tuic_relay_isolation_test.go @@ -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) { diff --git a/internal/web/service/xray_runtime_deps.go b/internal/web/service/xray_runtime_deps.go new file mode 100644 index 000000000..8971d789d --- /dev/null +++ b/internal/web/service/xray_runtime_deps.go @@ -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) + } + }, + } +} diff --git a/internal/web/web.go b/internal/web/web.go index 9b5bafb07..bac32b715 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -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 diff --git a/internal/xray/process.go b/internal/xray/process.go index 4cfae62d3..fd3792183 100644 --- a/internal/xray/process.go +++ b/internal/xray/process.go @@ -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 {