Moonshark/core/runner/Embed.go
2025-04-09 19:03:35 -05:00

62 lines
1.5 KiB
Go

package runner
import (
_ "embed"
"sync"
"sync/atomic"
"Moonshark/core/utils/logger"
luajit "git.sharkk.net/Sky/LuaJIT-to-Go"
)
//go:embed sandbox.lua
var sandboxLuaCode string
// Global bytecode cache to improve performance
var (
sandboxBytecode atomic.Pointer[[]byte]
bytecodeOnce sync.Once
)
// precompileSandboxCode compiles the sandbox.lua code to bytecode once
func precompileSandboxCode() {
// Create temporary state for compilation
tempState := luajit.New()
if tempState == nil {
logger.Error("Failed to create temp Lua state for bytecode compilation")
return
}
defer tempState.Close()
defer tempState.Cleanup()
code, err := tempState.CompileBytecode(sandboxLuaCode, "sandbox.lua")
if err != nil {
logger.Error("Failed to compile sandbox code: %v", err)
return
}
bytecode := make([]byte, len(code))
copy(bytecode, code)
sandboxBytecode.Store(&bytecode)
logger.Debug("Successfully precompiled sandbox.lua to bytecode (%d bytes)", len(code))
}
// loadSandboxIntoState loads the sandbox code into a Lua state
func loadSandboxIntoState(state *luajit.State) error {
// Initialize bytecode once
bytecodeOnce.Do(precompileSandboxCode)
// Use precompiled bytecode if available
bytecode := sandboxBytecode.Load()
if bytecode != nil && len(*bytecode) > 0 {
logger.Debug("Loading sandbox.lua from precompiled bytecode")
return state.LoadAndRunBytecode(*bytecode, "sandbox.lua")
}
// Fallback to direct execution
logger.Warning("Using non-precompiled sandbox.lua (bytecode compilation failed)")
return state.DoString(sandboxLuaCode)
}