make lua deps modular

This commit is contained in:
2025-08-01 23:18:45 +03:00
parent 041fda8522
commit a60b75a4c0

View File

@@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"io" "io"
"log/slog" "log/slog"
"math/rand/v2"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
@@ -40,69 +41,88 @@ func (h *HandlerV1) handleLUA(sid string, r *http.Request, req *rpc.RPCRequest,
L := lua.NewState() L := lua.NewState()
defer L.Close() defer L.Close()
inTable := L.NewTable() seed := rand.Int()
paramsTable := L.NewTable()
loadSessionMod := func(lL *lua.LState) int {
h.x.SLog.Debug("import module session", slog.String("script", path))
sessionMod := lL.NewTable()
inTable := lL.NewTable()
paramsTable := lL.NewTable()
if fetchedParams, ok := req.Params.(map[string]any); ok { if fetchedParams, ok := req.Params.(map[string]any); ok {
for k, v := range fetchedParams { for k, v := range fetchedParams {
L.SetField(paramsTable, k, ConvertGolangTypesToLua(L, v)) lL.SetField(paramsTable, k, ConvertGolangTypesToLua(lL, v))
} }
} }
L.SetField(inTable, "Params", paramsTable) lL.SetField(inTable, "params", paramsTable)
L.SetGlobal("In", inTable)
outTable := L.NewTable() outTable := lL.NewTable()
resultTable := L.NewTable() resultTable := lL.NewTable()
L.SetField(outTable, "Result", resultTable) lL.SetField(outTable, "result", resultTable)
L.SetGlobal("Out", outTable)
logTable := L.NewTable() lL.SetField(sessionMod, "in", inTable)
lL.SetField(sessionMod, "out", outTable)
lL.Push(sessionMod)
lL.SetField(sessionMod, "__gosally_internal", lua.LString(fmt.Sprint(seed)))
return 1
}
loadLogMod := func(lL *lua.LState) int {
h.x.SLog.Debug("import module log", slog.String("script", path))
logMod := lL.NewTable()
logFuncs := map[string]func(string, ...any){ logFuncs := map[string]func(string, ...any){
"Info": h.x.SLog.Info, "info": h.x.SLog.Info,
"Debug": h.x.SLog.Debug, "debug": h.x.SLog.Debug,
"Error": h.x.SLog.Error, "error": h.x.SLog.Error,
"Warn": h.x.SLog.Warn, "warn": h.x.SLog.Warn,
} }
for name, logFunc := range logFuncs { for name, logFunc := range logFuncs {
L.SetField(logTable, name, L.NewFunction(func(L *lua.LState) int { fun := logFunc
msg := L.ToString(1) lL.SetField(logMod, name, lL.NewFunction(func(lL *lua.LState) int {
logFunc(fmt.Sprintf("the script says: %s", msg), slog.String("script", path)) msg := lL.ToString(1)
fun(fmt.Sprintf("the script says: %s", msg), slog.String("script", path))
return 0 return 0
})) }))
} }
L.SetField(logTable, "Event", L.NewFunction(func(L *lua.LState) int { lL.SetField(logMod, "event", lL.NewFunction(func(lL *lua.LState) int {
msg := L.ToString(1) msg := lL.ToString(1)
h.x.Log.Printf("%s: %s", path, msg) h.x.Log.Printf("%s: %s", path, msg)
return 0 return 0
})) }))
L.SetField(logTable, "EventError", L.NewFunction(func(L *lua.LState) int { lL.SetField(logMod, "event_error", lL.NewFunction(func(lL *lua.LState) int {
msg := L.ToString(1) msg := lL.ToString(1)
h.x.Log.Printf("%s: %s: %s", colors.PrintError(), path, msg) h.x.Log.Printf("%s: %s: %s", colors.PrintError(), path, msg)
return 0 return 0
})) }))
L.SetField(logTable, "EventWarn", L.NewFunction(func(L *lua.LState) int { lL.SetField(logMod, "event_warn", lL.NewFunction(func(lL *lua.LState) int {
msg := L.ToString(1) msg := lL.ToString(1)
h.x.Log.Printf("%s: %s: %s", colors.PrintWarn(), path, msg) h.x.Log.Printf("%s: %s: %s", colors.PrintWarn(), path, msg)
return 0 return 0
})) }))
L.SetGlobal("Log", logTable) lL.Push(logMod)
lL.SetField(logMod, "__gosally_internal", lua.LString(fmt.Sprint(seed)))
return 1
}
net := L.NewTable() loadNetMod := func(lL *lua.LState) int {
netHttp := L.NewTable() h.x.SLog.Debug("import module net", slog.String("script", path))
netMod := lL.NewTable()
netModhttp := lL.NewTable()
L.SetField(netHttp, "Get", L.NewFunction(func(L *lua.LState) int { lL.SetField(netModhttp, "get_request", lL.NewFunction(func(lL *lua.LState) int {
logRequest := L.ToBool(1) logRequest := lL.ToBool(1)
url := L.ToString(2) url := lL.ToString(2)
req, err := http.NewRequest("GET", url, nil) req, err := http.NewRequest("GET", url, nil)
if err != nil { if err != nil {
L.Push(lua.LNil) lL.Push(lua.LNil)
L.Push(lua.LString(err.Error())) lL.Push(lua.LString(err.Error()))
return 2 return 2
} }
@@ -111,16 +131,16 @@ func (h *HandlerV1) handleLUA(sid string, r *http.Request, req *rpc.RPCRequest,
client := &http.Client{} client := &http.Client{}
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
L.Push(lua.LNil) lL.Push(lua.LNil)
L.Push(lua.LString(err.Error())) lL.Push(lua.LString(err.Error()))
return 2 return 2
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err := io.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
L.Push(lua.LNil) lL.Push(lua.LNil)
L.Push(lua.LString(err.Error())) lL.Push(lua.LString(err.Error()))
return 2 return 2
} }
@@ -134,34 +154,34 @@ func (h *HandlerV1) handleLUA(sid string, r *http.Request, req *rpc.RPCRequest,
) )
} }
result := L.NewTable() result := lL.NewTable()
L.SetField(result, "status", lua.LNumber(resp.StatusCode)) lL.SetField(result, "status", lua.LNumber(resp.StatusCode))
L.SetField(result, "status_text", lua.LString(resp.Status)) lL.SetField(result, "status_text", lua.LString(resp.Status))
L.SetField(result, "body", lua.LString(body)) lL.SetField(result, "body", lua.LString(body))
L.SetField(result, "content_length", lua.LNumber(resp.ContentLength)) lL.SetField(result, "content_length", lua.LNumber(resp.ContentLength))
headers := L.NewTable() headers := lL.NewTable()
for k, v := range resp.Header { for k, v := range resp.Header {
L.SetField(headers, k, ConvertGolangTypesToLua(L, v)) lL.SetField(headers, k, ConvertGolangTypesToLua(lL, v))
} }
L.SetField(result, "headers", headers) lL.SetField(result, "headers", headers)
L.Push(result) lL.Push(result)
return 1 return 1
})) }))
L.SetField(netHttp, "Post", L.NewFunction(func(L *lua.LState) int { lL.SetField(netModhttp, "post_request", lL.NewFunction(func(lL *lua.LState) int {
logRequest := L.ToBool(1) logRequest := lL.ToBool(1)
url := L.ToString(2) url := lL.ToString(2)
contentType := L.ToString(3) contentType := lL.ToString(3)
payload := L.ToString(4) payload := lL.ToString(4)
body := strings.NewReader(payload) body := strings.NewReader(payload)
req, err := http.NewRequest("POST", url, body) req, err := http.NewRequest("POST", url, body)
if err != nil { if err != nil {
L.Push(lua.LNil) lL.Push(lua.LNil)
L.Push(lua.LString(err.Error())) lL.Push(lua.LString(err.Error()))
return 2 return 2
} }
@@ -172,16 +192,16 @@ func (h *HandlerV1) handleLUA(sid string, r *http.Request, req *rpc.RPCRequest,
client := &http.Client{} client := &http.Client{}
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
L.Push(lua.LNil) lL.Push(lua.LNil)
L.Push(lua.LString(err.Error())) lL.Push(lua.LString(err.Error()))
return 2 return 2
} }
defer resp.Body.Close() defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body) respBody, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
L.Push(lua.LNil) lL.Push(lua.LNil)
L.Push(lua.LString(err.Error())) lL.Push(lua.LString(err.Error()))
return 2 return 2
} }
@@ -196,46 +216,85 @@ func (h *HandlerV1) handleLUA(sid string, r *http.Request, req *rpc.RPCRequest,
) )
} }
result := L.NewTable() result := lL.NewTable()
L.SetField(result, "status", lua.LNumber(resp.StatusCode)) lL.SetField(result, "status", lua.LNumber(resp.StatusCode))
L.SetField(result, "status_text", lua.LString(resp.Status)) lL.SetField(result, "status_text", lua.LString(resp.Status))
L.SetField(result, "body", lua.LString(respBody)) lL.SetField(result, "body", lua.LString(respBody))
L.SetField(result, "content_length", lua.LNumber(resp.ContentLength)) lL.SetField(result, "content_length", lua.LNumber(resp.ContentLength))
headers := L.NewTable() headers := lL.NewTable()
for k, v := range resp.Header { for k, v := range resp.Header {
L.SetField(headers, k, ConvertGolangTypesToLua(L, v)) lL.SetField(headers, k, ConvertGolangTypesToLua(lL, v))
} }
L.SetField(result, "headers", headers) lL.SetField(result, "headers", headers)
L.Push(result) lL.Push(result)
return 1 return 1
})) }))
L.SetField(net, "Http", netHttp) lL.SetField(netMod, "http", netModhttp)
L.SetGlobal("Net", net)
lL.Push(netMod)
lL.SetField(netMod, "__gosally_internal", lua.LString(fmt.Sprint(seed)))
return 1
}
L.PreloadModule("session", loadSessionMod)
L.PreloadModule("log", loadLogMod)
L.PreloadModule("net", loadNetMod)
prep := filepath.Join(*h.x.Config.Conf.Node.ComDir, "_prepare.lua") prep := filepath.Join(*h.x.Config.Conf.Node.ComDir, "_prepare.lua")
if _, err := os.Stat(prep); err == nil { if _, err := os.Stat(prep); err == nil {
if err := L.DoFile(prep); err != nil { if err := L.DoFile(prep); err != nil {
return rpc.NewError(rpc.ErrInternalError, err.Error(), req.ID) h.x.SLog.Error("script error", slog.String("script", path), slog.String("error", err.Error()))
return rpc.NewError(rpc.ErrInternalError, rpc.ErrInternalErrorS, req.ID)
} }
} }
if err := L.DoFile(path); err != nil { if err := L.DoFile(path); err != nil {
return rpc.NewError(rpc.ErrInternalError, err.Error(), req.ID) h.x.SLog.Error("script error", slog.String("script", path), slog.String("error", err.Error()))
return rpc.NewError(rpc.ErrInternalError, rpc.ErrInternalErrorS, req.ID)
} }
lv := L.GetGlobal("Out") pkg := L.GetGlobal("package")
outTbl, ok := lv.(*lua.LTable) pkgTbl, ok := pkg.(*lua.LTable)
if !ok { if !ok {
return rpc.NewError(rpc.ErrInternalError, "Out is not a table", req.ID) h.x.SLog.Error("script error", slog.String("script", path), slog.String("error", "package not found"))
return rpc.NewError(rpc.ErrInternalError, rpc.ErrInternalErrorS, req.ID)
} }
// Check if Out.Error exists loaded := pkgTbl.RawGetString("loaded")
if errVal := outTbl.RawGetString("Error"); errVal != lua.LNil { loadedTbl, ok := loaded.(*lua.LTable)
if !ok {
h.x.SLog.Error("script error", slog.String("script", path), slog.String("error", "package.loaded not found"))
return rpc.NewError(rpc.ErrInternalError, rpc.ErrInternalErrorS, req.ID)
}
sessionVal := loadedTbl.RawGetString("session")
sessionTbl, ok := sessionVal.(*lua.LTable)
if !ok {
return rpc.NewResponse(map[string]any{
"responsible-node": h.cs.UUID32,
}, req.ID)
}
tag := sessionTbl.RawGetString("__gosally_internal")
if tag.Type() != lua.LTString || tag.String() != fmt.Sprint(seed) {
return rpc.NewResponse(map[string]any{
"responsible-node": h.cs.UUID32,
}, req.ID)
}
outVal := sessionTbl.RawGetString("out")
outTbl, ok := outVal.(*lua.LTable)
if !ok {
h.x.SLog.Error("script error", slog.String("script", path), slog.String("error", "out is not a table"))
return rpc.NewError(rpc.ErrInternalError, rpc.ErrInternalErrorS, req.ID)
}
if errVal := outTbl.RawGetString("error"); errVal != lua.LNil {
if errTbl, ok := errVal.(*lua.LTable); ok { if errTbl, ok := errVal.(*lua.LTable); ok {
code := rpc.ErrInternalError code := rpc.ErrInternalError
message := "Internal script error" message := rpc.ErrInternalErrorS
if c := errTbl.RawGetString("code"); c.Type() == lua.LTNumber { if c := errTbl.RawGetString("code"); c.Type() == lua.LTNumber {
code = int(c.(lua.LNumber)) code = int(c.(lua.LNumber))
} }
@@ -245,21 +304,16 @@ func (h *HandlerV1) handleLUA(sid string, r *http.Request, req *rpc.RPCRequest,
h.x.SLog.Error("the script terminated with an error", slog.String("code", strconv.Itoa(code)), slog.String("message", message)) h.x.SLog.Error("the script terminated with an error", slog.String("code", strconv.Itoa(code)), slog.String("message", message))
return rpc.NewError(code, message, req.ID) return rpc.NewError(code, message, req.ID)
} }
return rpc.NewError(rpc.ErrInternalError, "Out.Error is not a table", req.ID) return rpc.NewError(rpc.ErrInternalError, rpc.ErrInternalErrorS, req.ID)
} }
// Otherwise, parse Out.Result resultVal := outTbl.RawGetString("result")
resultVal := outTbl.RawGetString("Result") payload := make(map[string]any)
resultTbl, ok := resultVal.(*lua.LTable) if tbl, ok := resultVal.(*lua.LTable); ok {
if !ok { tbl.ForEach(func(k, v lua.LValue) { payload[k.String()] = ConvertLuaTypesToGolang(v) })
return rpc.NewError(rpc.ErrInternalError, "Out.Result is not a table", req.ID) } else {
payload["message"] = ConvertLuaTypesToGolang(resultVal)
} }
payload["responsible-node"] = h.cs.UUID32
out := make(map[string]any) return rpc.NewResponse(payload, req.ID)
resultTbl.ForEach(func(key lua.LValue, value lua.LValue) {
out[key.String()] = ConvertLuaTypesToGolang(value)
})
out["responsible-node"] = h.cs.UUID32
return rpc.NewResponse(out, req.ID)
} }