Compare commits
2 Commits
ab6135e98a
...
195800082a
Author | SHA1 | Date | |
---|---|---|---|
195800082a | |||
7b7876e864 |
|
@ -186,12 +186,6 @@ func (s *Moonshark) initRunner() error {
|
|||
runner.WithLibDirs(s.Config.Dirs.Libs...),
|
||||
}
|
||||
|
||||
// Add debug option conditionally
|
||||
if s.Config.Server.Debug {
|
||||
runnerOpts = append(runnerOpts, runner.WithDebugEnabled())
|
||||
logger.Debug("Debug logging enabled for Lua runner")
|
||||
}
|
||||
|
||||
// Initialize the runner
|
||||
var err error
|
||||
s.LuaRunner, err = runner.NewRunner(runnerOpts...)
|
||||
|
|
|
@ -135,7 +135,7 @@ func (s *Server) processRequest(ctx *fasthttp.RequestCtx) {
|
|||
return
|
||||
} else if found {
|
||||
logger.Debug("Found Lua route match for %s %s with %d params", method, path, params.Count)
|
||||
s.handleLuaRoute(ctx, bytecode, scriptPath, params)
|
||||
s.handleLuaRoute(ctx, bytecode, scriptPath, params, method, path)
|
||||
return
|
||||
}
|
||||
|
||||
|
@ -152,13 +152,11 @@ func (s *Server) processRequest(ctx *fasthttp.RequestCtx) {
|
|||
}
|
||||
|
||||
// handleLuaRoute executes a Lua route
|
||||
func (s *Server) handleLuaRoute(ctx *fasthttp.RequestCtx, bytecode []byte, scriptPath string, params *routers.Params) {
|
||||
func (s *Server) handleLuaRoute(ctx *fasthttp.RequestCtx, bytecode []byte, scriptPath string, params *routers.Params, method string, path string) {
|
||||
// Create context for Lua execution
|
||||
luaCtx := runner.NewHTTPContext(ctx)
|
||||
defer luaCtx.Release()
|
||||
|
||||
method := string(ctx.Method())
|
||||
path := string(ctx.Path())
|
||||
host := string(ctx.Host())
|
||||
|
||||
// Set up additional context values
|
||||
|
@ -166,6 +164,13 @@ func (s *Server) handleLuaRoute(ctx *fasthttp.RequestCtx, bytecode []byte, scrip
|
|||
luaCtx.Set("path", path)
|
||||
luaCtx.Set("host", host)
|
||||
|
||||
// Add session data
|
||||
session := s.sessionManager.GetSessionFromRequest(ctx)
|
||||
luaCtx.Set("session", map[string]any{
|
||||
"id": session.ID,
|
||||
"data": session.Data,
|
||||
})
|
||||
|
||||
// URL parameters
|
||||
if params.Count > 0 {
|
||||
paramMap := make(map[string]any, params.Count)
|
||||
|
|
|
@ -44,16 +44,20 @@ func precompileSandboxCode() {
|
|||
}
|
||||
|
||||
// loadSandboxIntoState loads the sandbox code into a Lua state
|
||||
func loadSandboxIntoState(state *luajit.State) error {
|
||||
func loadSandboxIntoState(state *luajit.State, verbose bool) error {
|
||||
bytecodeOnce.Do(precompileSandboxCode)
|
||||
|
||||
bytecode := sandboxBytecode.Load()
|
||||
if bytecode != nil && len(*bytecode) > 0 {
|
||||
logger.ServerCont("Loading sandbox.lua from precompiled bytecode") // piggyback off Sandbox.go's Setup()
|
||||
if verbose {
|
||||
logger.ServerCont("Loading sandbox.lua from precompiled bytecode") // piggyback off Sandbox.go's Setup()
|
||||
}
|
||||
return state.LoadAndRunBytecode(*bytecode, "sandbox.lua")
|
||||
}
|
||||
|
||||
// Fallback to direct execution
|
||||
logger.WarningCont("Using non-precompiled sandbox.lua (bytecode compilation failed)")
|
||||
if verbose {
|
||||
logger.WarningCont("Using non-precompiled sandbox.lua (bytecode compilation failed)")
|
||||
}
|
||||
return state.DoString(sandboxLuaCode)
|
||||
}
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package runner
|
||||
|
||||
import (
|
||||
"Moonshark/core/utils/logger"
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
|
@ -9,8 +10,6 @@ import (
|
|||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"Moonshark/core/utils/logger"
|
||||
|
||||
luajit "git.sharkk.net/Sky/LuaJIT-to-Go"
|
||||
)
|
||||
|
||||
|
@ -41,7 +40,6 @@ type Runner struct {
|
|||
moduleLoader *ModuleLoader // Module loader
|
||||
isRunning atomic.Bool // Whether the runner is active
|
||||
mu sync.RWMutex // Mutex for thread safety
|
||||
debug bool // Enable debug logging
|
||||
scriptDir string // Current script directory
|
||||
}
|
||||
|
||||
|
@ -54,13 +52,6 @@ func WithPoolSize(size int) RunnerOption {
|
|||
}
|
||||
}
|
||||
|
||||
// WithDebugEnabled enables debug output
|
||||
func WithDebugEnabled() RunnerOption {
|
||||
return func(r *Runner) {
|
||||
r.debug = true
|
||||
}
|
||||
}
|
||||
|
||||
// WithLibDirs sets additional library directories
|
||||
func WithLibDirs(dirs ...string) RunnerOption {
|
||||
return func(r *Runner) {
|
||||
|
@ -79,7 +70,6 @@ func NewRunner(options ...RunnerOption) (*Runner, error) {
|
|||
// Default configuration
|
||||
runner := &Runner{
|
||||
poolSize: runtime.GOMAXPROCS(0),
|
||||
debug: false,
|
||||
}
|
||||
|
||||
// Apply options
|
||||
|
@ -96,11 +86,6 @@ func NewRunner(options ...RunnerOption) (*Runner, error) {
|
|||
runner.moduleLoader = NewModuleLoader(config)
|
||||
}
|
||||
|
||||
// Enable debug if requested
|
||||
if runner.debug {
|
||||
runner.moduleLoader.EnableDebug()
|
||||
}
|
||||
|
||||
// Initialize states and pool
|
||||
runner.states = make([]*State, runner.poolSize)
|
||||
runner.statePool = make(chan int, runner.poolSize)
|
||||
|
@ -115,19 +100,11 @@ func NewRunner(options ...RunnerOption) (*Runner, error) {
|
|||
return runner, nil
|
||||
}
|
||||
|
||||
// debugLog logs a message if debug mode is enabled
|
||||
func (r *Runner) debugLog(format string, args ...interface{}) {
|
||||
if r.debug {
|
||||
logger.Debug("Runner "+format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
// initializeStates creates and initializes all states in the pool
|
||||
func (r *Runner) initializeStates() error {
|
||||
r.debugLog("Initializing %d states", r.poolSize)
|
||||
logger.Server("Initializing %d states...", r.poolSize)
|
||||
|
||||
// Create all states
|
||||
for i := 0; i < r.poolSize; i++ {
|
||||
for i := range r.poolSize {
|
||||
state, err := r.createState(i)
|
||||
if err != nil {
|
||||
return err
|
||||
|
@ -144,7 +121,7 @@ func (r *Runner) initializeStates() error {
|
|||
func (r *Runner) createState(index int) (*State, error) {
|
||||
verbose := index == 0
|
||||
if verbose {
|
||||
r.debugLog("Creating Lua state %d", index)
|
||||
logger.ServerCont("Creating Lua state %d", index)
|
||||
}
|
||||
|
||||
L := luajit.New()
|
||||
|
@ -155,7 +132,7 @@ func (r *Runner) createState(index int) (*State, error) {
|
|||
sb := NewSandbox()
|
||||
|
||||
// Set up sandbox
|
||||
if err := sb.Setup(L); err != nil {
|
||||
if err := sb.Setup(L, verbose); err != nil {
|
||||
L.Cleanup()
|
||||
L.Close()
|
||||
return nil, ErrInitFailed
|
||||
|
@ -176,7 +153,7 @@ func (r *Runner) createState(index int) (*State, error) {
|
|||
}
|
||||
|
||||
if verbose {
|
||||
r.debugLog("Lua state %d initialized successfully", index)
|
||||
logger.ServerCont("Lua state %d initialized successfully", index)
|
||||
}
|
||||
|
||||
return &State{
|
||||
|
@ -281,7 +258,7 @@ cleanup:
|
|||
}
|
||||
}
|
||||
|
||||
r.debugLog("Runner closed")
|
||||
logger.Debug("Runner closed")
|
||||
return nil
|
||||
}
|
||||
|
||||
|
@ -294,7 +271,7 @@ func (r *Runner) RefreshStates() error {
|
|||
return ErrRunnerClosed
|
||||
}
|
||||
|
||||
r.debugLog("Refreshing all states...")
|
||||
logger.Server("Runner is refreshing all states...")
|
||||
|
||||
// Drain all states from the pool
|
||||
for {
|
||||
|
@ -312,7 +289,7 @@ cleanup:
|
|||
for i, state := range r.states {
|
||||
if state != nil {
|
||||
if state.inUse {
|
||||
r.debugLog("Warning: attempting to refresh state %d that is in use", i)
|
||||
logger.WarningCont("Attempting to refresh state %d that is in use", i)
|
||||
}
|
||||
state.L.Cleanup()
|
||||
state.L.Close()
|
||||
|
@ -325,24 +302,25 @@ cleanup:
|
|||
return err
|
||||
}
|
||||
|
||||
r.debugLog("All states refreshed successfully")
|
||||
logger.ServerCont("All states refreshed successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
// NotifyFileChanged alerts the runner about file changes
|
||||
func (r *Runner) NotifyFileChanged(filePath string) bool {
|
||||
r.debugLog("File change detected: %s", filePath)
|
||||
logger.Debug("Runner has been notified of a file change...")
|
||||
logger.Debug("%s", filePath)
|
||||
|
||||
// Check if it's a module file
|
||||
module, isModule := r.moduleLoader.GetModuleByPath(filePath)
|
||||
if isModule {
|
||||
r.debugLog("File is a module: %s", module)
|
||||
logger.DebugCont("File is a module: %s", module)
|
||||
return r.RefreshModule(module)
|
||||
}
|
||||
|
||||
// For non-module files, refresh all states
|
||||
if err := r.RefreshStates(); err != nil {
|
||||
r.debugLog("Failed to refresh states: %v", err)
|
||||
logger.DebugCont("Failed to refresh states: %v", err)
|
||||
return false
|
||||
}
|
||||
|
||||
|
@ -358,7 +336,7 @@ func (r *Runner) RefreshModule(moduleName string) bool {
|
|||
return false
|
||||
}
|
||||
|
||||
r.debugLog("Refreshing module: %s", moduleName)
|
||||
logger.DebugCont("Refreshing module: %s", moduleName)
|
||||
|
||||
success := true
|
||||
for _, state := range r.states {
|
||||
|
@ -369,7 +347,7 @@ func (r *Runner) RefreshModule(moduleName string) bool {
|
|||
// Invalidate module in Lua
|
||||
if err := state.L.DoString(`package.loaded["` + moduleName + `"] = nil`); err != nil {
|
||||
success = false
|
||||
r.debugLog("Failed to invalidate module %s: %v", moduleName, err)
|
||||
logger.DebugCont("Failed to invalidate module %s: %v", moduleName, err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -49,10 +49,12 @@ func (s *Sandbox) AddModule(name string, module any) {
|
|||
}
|
||||
|
||||
// Setup initializes the sandbox in a Lua state
|
||||
func (s *Sandbox) Setup(state *luajit.State) error {
|
||||
logger.Server("Setting up sandbox...")
|
||||
func (s *Sandbox) Setup(state *luajit.State, verbose bool) error {
|
||||
if verbose {
|
||||
logger.Server("Setting up sandbox...")
|
||||
}
|
||||
|
||||
if err := loadSandboxIntoState(state); err != nil {
|
||||
if err := loadSandboxIntoState(state, verbose); err != nil {
|
||||
logger.ErrorCont("Failed to load sandbox: %v", err)
|
||||
return err
|
||||
}
|
||||
|
@ -74,7 +76,9 @@ func (s *Sandbox) Setup(state *luajit.State) error {
|
|||
}
|
||||
s.mu.RUnlock()
|
||||
|
||||
logger.ServerCont("Sandbox setup complete")
|
||||
if verbose {
|
||||
logger.ServerCont("Sandbox setup complete")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
@ -135,19 +139,12 @@ func (s *Sandbox) Execute(state *luajit.State, bytecode []byte, ctx *Context) (*
|
|||
|
||||
// extractResponseData pulls response info from the Lua state
|
||||
func extractHTTPResponseData(state *luajit.State, response *Response) {
|
||||
state.GetGlobal("__http_responses")
|
||||
state.GetGlobal("__http_response")
|
||||
if !state.IsTable(-1) {
|
||||
state.Pop(1)
|
||||
return
|
||||
}
|
||||
|
||||
state.PushNumber(1)
|
||||
state.GetTable(-2)
|
||||
if !state.IsTable(-1) {
|
||||
state.Pop(2)
|
||||
return
|
||||
}
|
||||
|
||||
// Extract status
|
||||
state.GetField(-1, "status")
|
||||
if state.IsNumber(-1) {
|
||||
|
@ -196,8 +193,7 @@ func extractHTTPResponseData(state *luajit.State, response *Response) {
|
|||
}
|
||||
state.Pop(1)
|
||||
|
||||
// Clean up
|
||||
state.Pop(2)
|
||||
state.Pop(1) // Pop __http_response
|
||||
}
|
||||
|
||||
// extractCookie pulls cookie data from the current table on the stack
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package sessions
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
@ -66,9 +67,7 @@ func (s *Session) GetAll() map[string]any {
|
|||
defer s.mu.RUnlock()
|
||||
|
||||
copy := make(map[string]any, len(s.Data))
|
||||
for k, v := range s.Data {
|
||||
copy[k] = v
|
||||
}
|
||||
maps.Copy(copy, s.Data)
|
||||
|
||||
return copy
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user