package runner import ( "sync" "Moonshark/core/sessions" "github.com/valyala/bytebufferpool" "github.com/valyala/fasthttp" ) // Context represents execution context for a Lua script type Context struct { // Values stores any context values (route params, HTTP request info, etc.) Values map[string]any // FastHTTP context if this was created from an HTTP request RequestCtx *fasthttp.RequestCtx // Session data and management Session *sessions.Session SessionModified bool // Buffer for efficient string operations buffer *bytebufferpool.ByteBuffer } // Context pool to reduce allocations var contextPool = sync.Pool{ New: func() any { return &Context{ Values: make(map[string]any, 16), } }, } // NewContext creates a new context, potentially reusing one from the pool func NewContext() *Context { return contextPool.Get().(*Context) } // NewHTTPContext creates a new context from a fasthttp RequestCtx func NewHTTPContext(requestCtx *fasthttp.RequestCtx) *Context { ctx := NewContext() ctx.RequestCtx = requestCtx return ctx } // Release returns the context to the pool after clearing its values func (c *Context) Release() { // Clear all values to prevent data leakage for k := range c.Values { delete(c.Values, k) } // Reset session info c.Session = nil c.SessionModified = false // Reset request context c.RequestCtx = nil // Return buffer to pool if we have one if c.buffer != nil { bytebufferpool.Put(c.buffer) c.buffer = nil } contextPool.Put(c) } // GetBuffer returns a byte buffer for efficient string operations func (c *Context) GetBuffer() *bytebufferpool.ByteBuffer { if c.buffer == nil { c.buffer = bytebufferpool.Get() } return c.buffer } // Set adds a value to the context func (c *Context) Set(key string, value any) { c.Values[key] = value } // Get retrieves a value from the context func (c *Context) Get(key string) any { return c.Values[key] } // Contains checks if a key exists in the context func (c *Context) Contains(key string) bool { _, exists := c.Values[key] return exists } // Delete removes a value from the context func (c *Context) Delete(key string) { delete(c.Values, key) }