86 lines
1.7 KiB
Go
86 lines
1.7 KiB
Go
package runner
|
|
|
|
import "sync"
|
|
|
|
// 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
|
|
|
|
// internal mutex for concurrent access
|
|
mu sync.RWMutex
|
|
}
|
|
|
|
// Context pool to reduce allocations
|
|
var contextPool = sync.Pool{
|
|
New: func() interface{} {
|
|
return &Context{
|
|
Values: make(map[string]any, 16), // Pre-allocate with reasonable capacity
|
|
}
|
|
},
|
|
}
|
|
|
|
// NewContext creates a new context, potentially reusing one from the pool
|
|
func NewContext() *Context {
|
|
return contextPool.Get().(*Context)
|
|
}
|
|
|
|
// Release returns the context to the pool after clearing its values
|
|
func (c *Context) Release() {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
|
|
// Clear all values to prevent data leakage
|
|
for k := range c.Values {
|
|
delete(c.Values, k)
|
|
}
|
|
|
|
contextPool.Put(c)
|
|
}
|
|
|
|
// Set adds a value to the context
|
|
func (c *Context) Set(key string, value any) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
|
|
c.Values[key] = value
|
|
}
|
|
|
|
// Get retrieves a value from the context
|
|
func (c *Context) Get(key string) any {
|
|
c.mu.RLock()
|
|
defer c.mu.RUnlock()
|
|
|
|
return c.Values[key]
|
|
}
|
|
|
|
// Contains checks if a key exists in the context
|
|
func (c *Context) Contains(key string) bool {
|
|
c.mu.RLock()
|
|
defer c.mu.RUnlock()
|
|
|
|
_, exists := c.Values[key]
|
|
return exists
|
|
}
|
|
|
|
// Delete removes a value from the context
|
|
func (c *Context) Delete(key string) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
|
|
delete(c.Values, key)
|
|
}
|
|
|
|
// All returns a copy of all values in the context
|
|
func (c *Context) All() map[string]any {
|
|
c.mu.RLock()
|
|
defer c.mu.RUnlock()
|
|
|
|
result := make(map[string]any, len(c.Values))
|
|
for k, v := range c.Values {
|
|
result[k] = v
|
|
}
|
|
|
|
return result
|
|
}
|