refactor: move execution context and timeout management into pool

This commit is contained in:
Meo597
2026-10-04 05:22:47 +08:00
parent e38794ed88
commit 399563b6d9
8 changed files with 441 additions and 172 deletions
+4 -12
View File
@@ -142,19 +142,11 @@ func newLuaClientQuery(L *lua.LState, client featureDNS.Client) *lua.LFunction {
})
}
// CallLuaHook invokes HandleDNSQuery in the supplied state.
// callLuaHook invokes HandleDNSQuery in the supplied state.
// Returned slices and IP bytes may share storage with DNS caches or matcher inputs.
func (s *DNS) CallLuaHook(L *lua.LState, ctx context.Context, domain string, option featureDNS.IPOption) ([]net.IP, uint32, error) {
previous, top := L.Context(), L.GetTop()
L.SetContext(ctx)
defer func() {
L.SetTop(top)
if previous == nil {
L.RemoveContext()
} else {
L.SetContext(previous)
}
}()
func (s *DNS) callLuaHook(L *lua.LState, domain string, option featureDNS.IPOption) ([]net.IP, uint32, error) {
top := L.GetTop()
defer L.SetTop(top)
fn := L.GetGlobal("HandleDNSQuery")
if fn.Type() != lua.LTFunction {
return nil, 0, errors.New("DNS script must define HandleDNSQuery(...)")
+15 -17
View File
@@ -84,14 +84,15 @@ func TestCallLuaHookCancellation(t *testing.T) {
if err := L.DoString(`function HandleDNSQuery(domain, ipv4, ipv6, fake) while true do end end`); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
_, _, err := (&DNS{}).CallLuaHook(L, ctx, "example.com", featureDNS.IPOption{IPv4Enable: true})
ctx, cancel := context.WithCancel(context.Background())
cancel()
L.SetContext(ctx)
_, _, err := (&DNS{}).callLuaHook(L, "example.com", featureDNS.IPOption{IPv4Enable: true})
if err == nil {
t.Fatal("CallLuaHook did not stop after context cancellation")
}
if L.Context() != nil {
t.Fatal("CallLuaHook left the canceled context on the Lua state")
if L.Context() != ctx {
t.Fatal("CallLuaHook changed the Lua state's context")
}
}
@@ -111,12 +112,12 @@ func TestCallLuaHookNormalizesDomain(t *testing.T) {
t.Fatal(err)
}
s := &DNS{}
if _, _, err := s.CallLuaHook(L, context.Background(), "ExAmPlE.CoM", featureDNS.IPOption{IPv4Enable: true}); err != nil {
if _, _, err := s.callLuaHook(L, "ExAmPlE.CoM", featureDNS.IPOption{IPv4Enable: true}); err != nil {
t.Fatal(err)
}
}
func TestCallLuaHookRestoresState(t *testing.T) {
func TestCallLuaHookRestoresStack(t *testing.T) {
for _, tc := range []struct {
name string
body string
@@ -134,16 +135,13 @@ func TestCallLuaHookRestoresState(t *testing.T) {
if err := L.DoString("function HandleDNSQuery() " + tc.body + " end"); err != nil {
t.Fatal(err)
}
previous, cancel := context.WithCancel(context.Background())
defer cancel()
L.SetContext(previous)
L.Push(lua.LTrue)
_, _, err := (&DNS{}).CallLuaHook(L, context.Background(), "example.com", featureDNS.IPOption{IPv4Enable: true})
_, _, err := (&DNS{}).callLuaHook(L, "example.com", featureDNS.IPOption{IPv4Enable: true})
if (err != nil) != tc.wantErr {
t.Fatalf("hook error = %v, want error %t", err, tc.wantErr)
}
if L.Context() != previous || L.GetTop() != 1 || L.Get(1) != lua.LTrue {
t.Fatal("hook did not restore the previous context and stack")
if L.GetTop() != 1 || L.Get(1) != lua.LTrue {
t.Fatal("hook did not restore the stack")
}
})
}
@@ -170,7 +168,8 @@ end
`); err != nil {
t.Fatal(err)
}
got, ttl, err := server.CallLuaHook(L, context.Background(), "example.com", option)
L.SetContext(context.Background())
got, ttl, err := server.callLuaHook(L, "example.com", option)
if err != nil || ttl != 60 || len(got) != 1 || !got[0].Equal(ips[0]) {
t.Fatalf("server query = %v, TTL %d, %v", got, ttl, err)
}
@@ -189,7 +188,6 @@ func TestLuaDNSClientQuery(t *testing.T) {
L := lua.NewState()
defer L.Close()
L.SetContext(context.Background())
defer L.RemoveContext()
geodata.RegisterLua(L)
want := []net.IP{{127, 0, 0, 1}}
client := &luaDNSClient{lookup: func(domain string, option featureDNS.IPOption) ([]net.IP, uint32, error) {
@@ -218,7 +216,6 @@ func TestLuaDNSLocalClient(t *testing.T) {
L := lua.NewState()
defer L.Close()
L.SetContext(context.Background())
defer L.RemoveContext()
RegisterLua(L, localdns.New())
if err := L.DoString(`
local dns = require("xray.dns")
@@ -268,12 +265,13 @@ end
}
ctx := context.Background()
L.SetContext(ctx)
for _, bench := range []struct {
name string
query func() ([]net.IP, uint32, error)
}{
{"direct", func() ([]net.IP, uint32, error) { return client.QueryIP(ctx, "example.com", option) }},
{"lua_hook", func() ([]net.IP, uint32, error) { return server.CallLuaHook(L, ctx, "example.com", option) }},
{"lua_hook", func() ([]net.IP, uint32, error) { return server.callLuaHook(L, "example.com", option) }},
} {
b.Run(bench.name, func(b *testing.B) {
b.ReportAllocs()
+7 -10
View File
@@ -1,7 +1,6 @@
package dns
import (
"context"
"time"
"github.com/xtls/xray-core/common/errors"
@@ -13,7 +12,7 @@ import (
lua "github.com/yuin/gopher-lua"
)
const scriptExecutionTimeout = 10 * time.Second
const scriptExecutionTimeout = 6 * time.Second
type scriptEngine struct {
dns *DNS
@@ -26,8 +25,8 @@ func newScriptEngine(path string, server *DNS) (*scriptEngine, error) {
return nil, err
}
e := &scriptEngine{dns: server}
e.pool, err = luamgr.NewPool(server.ctx, program.NewStateFactory(
scriptExecutionTimeout,
e.pool, err = luamgr.NewPool(server.ctx, scriptExecutionTimeout, program.NewStateFactory(
scriptExecutionTimeout*20,
func(L *lua.LState) {
geodata.RegisterLua(L)
log.RegisterLua(L)
@@ -51,12 +50,10 @@ func (e *scriptEngine) close() {
}
func (e *scriptEngine) query(domain string, option dns.IPOption) (ips []net.IP, ttl uint32, err error) {
err = e.pool.WithState(func(L *lua.LState) error {
luaCtx, cancel := context.WithTimeout(e.pool.Context(), scriptExecutionTimeout)
defer cancel()
var luaErr error
ips, ttl, luaErr = e.dns.CallLuaHook(L, luaCtx, domain, option)
return luaErr
err = e.pool.WithState(nil, 0, func(L *lua.LState) error {
var hookErr error
ips, ttl, hookErr = e.dns.callLuaHook(L, domain, option)
return hookErr
})
return
}
+4 -13
View File
@@ -1,7 +1,6 @@
package router
import (
"context"
"runtime"
"strings"
@@ -120,18 +119,10 @@ func pushLuaError(L *lua.LState, err error) {
L.Push(value)
}
// CallLuaHook invokes HandleRoute in the supplied state.
func (r *Router) CallLuaHook(L *lua.LState, luaCtx context.Context, routeCtx routing.Context) (string, string, error) {
previous, top := L.Context(), L.GetTop()
L.SetContext(luaCtx)
defer func() {
L.SetTop(top)
if previous == nil {
L.RemoveContext()
} else {
L.SetContext(previous)
}
}()
// callLuaHook invokes HandleRoute in the supplied state.
func (r *Router) callLuaHook(L *lua.LState, routeCtx routing.Context) (string, string, error) {
top := L.GetTop()
defer L.SetTop(top)
fn := L.GetGlobal("HandleRoute")
if fn.Type() != lua.LTFunction {
return "", "", errors.New("routing script must define HandleRoute(...)")
+9 -10
View File
@@ -88,7 +88,7 @@ function HandleRoute(ctx, inboundTag, sourcePort, targetPort, localPort,
end`)
ctx := newLuaRouteTestContext()
tag, rule, err := r.CallLuaHook(L, context.Background(), ctx)
tag, rule, err := r.callLuaHook(L, ctx)
if err != nil || tag != "out" || rule != "rule" {
t.Fatalf("hook = %q, %q, %v", tag, rule, err)
}
@@ -137,11 +137,9 @@ func TestLuaRouteResult(t *testing.T) {
value := L.NewUserData()
value.Value = nativeErr
L.SetGlobal("nativeError", value)
previous := context.WithValue(context.Background(), struct{}{}, true)
L.SetContext(previous)
L.Push(lua.LTrue)
tag, rule, err := r.CallLuaHook(L, context.Background(), &routing_session.Context{})
tag, rule, err := r.callLuaHook(L, &routing_session.Context{})
if tag != tc.tag || rule != tc.rule {
t.Fatalf("result = %q, %q, %v", tag, rule, err)
}
@@ -157,8 +155,8 @@ func TestLuaRouteResult(t *testing.T) {
case err != nil:
t.Fatal(err)
}
if L.Context() != previous || L.GetTop() != 1 || L.Get(1) != lua.LTrue {
t.Fatal("hook did not restore the previous context and stack")
if L.GetTop() != 1 || L.Get(1) != lua.LTrue {
t.Fatal("hook did not restore the stack")
}
})
}
@@ -168,10 +166,11 @@ func TestLuaRouteCancellation(t *testing.T) {
r, L := newLuaRouterState(t, `function HandleRoute() while true do end end`)
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, _, err := r.CallLuaHook(L, ctx, &routing_session.Context{}); err == nil {
L.SetContext(ctx)
if _, _, err := r.callLuaHook(L, &routing_session.Context{}); err == nil {
t.Fatal("CallLuaHook did not stop after context cancellation")
}
if L.Context() != nil || L.GetTop() != 0 {
if L.Context() != ctx || L.GetTop() != 0 {
t.Fatal("CallLuaHook did not restore the Lua state")
}
}
@@ -253,7 +252,7 @@ end
b.Fatal(err)
}
ctx := context.Background()
L.SetContext(context.Background())
routeCtx := newLuaRouteTestContext()
for _, benchmark := range []struct {
name string
@@ -267,7 +266,7 @@ end
return route.GetOutboundTag(), route.GetRuleTag(), nil
}},
{"lua_hook", func() (string, string, error) {
return r.CallLuaHook(L, ctx, routeCtx)
return r.callLuaHook(L, routeCtx)
}},
} {
b.Run(benchmark.name, func(b *testing.B) {
+7 -10
View File
@@ -1,7 +1,6 @@
package router
import (
"context"
"time"
"github.com/xtls/xray-core/app/dns"
@@ -14,7 +13,7 @@ import (
lua "github.com/yuin/gopher-lua"
)
const scriptExecutionTimeout = 10 * time.Second
const scriptExecutionTimeout = 6 * time.Second
type scriptEngine struct {
router *Router
@@ -27,8 +26,8 @@ func newScriptEngine(path string, router *Router) (*scriptEngine, error) {
return nil, err
}
e := &scriptEngine{router: router}
e.pool, err = luamgr.NewPool(router.ctx, program.NewStateFactory(
scriptExecutionTimeout,
e.pool, err = luamgr.NewPool(router.ctx, scriptExecutionTimeout, program.NewStateFactory(
scriptExecutionTimeout*20,
func(L *lua.LState) {
geodata.RegisterLua(L)
log.RegisterLua(L)
@@ -54,12 +53,10 @@ func (e *scriptEngine) close() {
func (e *scriptEngine) pickRoute(ctx routing.Context) (routing.Route, error) {
var tag, ruleTag string
err := e.pool.WithState(func(L *lua.LState) error {
luaCtx, cancel := context.WithTimeout(e.pool.Context(), scriptExecutionTimeout)
defer cancel()
var luaErr error
tag, ruleTag, luaErr = e.router.CallLuaHook(L, luaCtx, ctx)
return luaErr
err := e.pool.WithState(nil, 0, func(L *lua.LState) error {
var hookErr error
tag, ruleTag, hookErr = e.router.callLuaHook(L, ctx)
return hookErr
})
if err != nil {
return nil, err