Documentation
¶
Overview ¶
Package luaengine 提供公共操作辅助函数
该模块提取各个 ops 文件中的公共逻辑,减少代码重复。
Package luaengine 提供全局变量常量 ¶
定义 Lua 脚本中使用的全局变量名称常量。
Package luaengine 提供 Go 与 Lua 数据转换函数 ¶
该文件包含所有 Go 类型到 Lua 类型和 Lua 类型到 Go 类型的转换函数, 用于在 Go 程序和 Lua 脚本之间传递数据。
Package luaengine 提供类型转换注册表实现 ¶
该模块使用注册表模式来管理类型转换器,减少重复的类型断言代码。
Package luaengine 提供 dbOps Lua 模块 ¶
该模块允许 Lua 脚本执行 SQL 查询,支持单行和多行结果返回。
Package luaengine 提供依赖注入机制 ¶
该文件定义了 Lua 引擎所需的依赖上下文和依赖注入接口, 支持将外部依赖(如数据库连接、HTTP 客户端)注入到 Lua 模块中。
Package luaengine 提供增强的 Lua 引擎功能 ¶
该包提供了以下主要功能: 1. Lua 虚拟机管理(LuaEngine) 2. Lua 状态池(LuaStatePool)用于性能优化 3. Lua 模块注册和管理 4. Go 与 Lua 数据转换
设计特点: - 使用 sync.Pool 复用 Lua 状态,提升性能 - 支持模块化预加载 - 提供统一的数据转换函数 - 支持外部依赖注入(如数据库连接)
Package luaengine 提供 Lua 引擎错误处理和Panic恢复 ¶
该文件实现了 Lua 脚本执行的Panic恢复机制和增强的错误处理。
Package luaengine 提供统一的错误处理机制 ¶
该模块定义了 luaengine 包的标准错误类型、错误码和错误处理工具。
Package luaengine 提供 esOps 模块 ¶
esOps 模块提供 Lua 脚本操作 Elasticsearch 的 API 函数。
Package luaengine HTTP 辅助函数(向后兼容)
该文件保留用于向后兼容的辅助函数。 新功能已迁移到 http_types.go, http_request_builder.go, http_response_handler.go 等文件中。
Package luaengine HTTP 日志记录器 ¶
该文件实现 HTTP 请求和响应的结构化日志记录。
Package luaengine HTTP 性能指标收集器 ¶
该文件实现 HTTP 请求的性能指标收集和统计。
Package luaengine 提供 httpOps Lua 模块 ¶
该模块允许 Lua 脚本发起 HTTP 请求,支持 GET、POST、PUT、DELETE 方法。 支持的功能: - JSON 请求体(application/json) - 查询参数(URL params) - 表单数据(application/x-www-form-urlencoded) - 文件上传(multipart/form-data) - 响应头返回 - 日志记录 - 性能指标收集
Package luaengine HTTP 请求构建器 ¶
该文件实现 HTTP 请求的构建逻辑,包括 JSON 序列化、查询参数编码、文件上传等功能。
Package luaengine HTTP 响应处理器 ¶
该文件实现 HTTP 响应的解析和处理逻辑,包括响应头提取、状态码处理等。
Package luaengine HTTP 模块核心类型定义 ¶
该文件定义 HTTP 请求和响应的核心数据结构。
Package luaengine 提供核心接口定义 ¶
该文件定义了 Lua 引擎的核心接口,用于统一不同模块的实现。
Package luaengine 提供 Lua 引擎性能监控 ¶
该文件实现了 Lua 脚本执行的指标收集和慢查询日志功能。
Package luaengine 提供 mongodbOps 模块 ¶
mongodbOps 模块提供 Lua 脚本操作 MongoDB 的 API 函数。
Package luaengine 提供 mqOps 模块 ¶
mqOps 模块提供 Lua 脚本操作消息队列的 API 函数。
Package luaengine 提供操作解析器实现 ¶
该模块使用配置驱动的方式重构操作解析逻辑,减少 switch-case 语句。
Package luaengine 提供 redisOps 模块 ¶
redisOps 模块提供 Lua 脚本操作 Redis 数据的 API 函数。
Package luaengine 提供沙箱安全机制 ¶
该文件实现了 Lua 脚本的沙箱安全机制,限制 Lua 脚本对系统资源的访问, 防止恶意脚本执行危险操作。
Package luaengine 提供 scriptOps 模块 ¶
scriptOps 模块提供 Lua 脚本访问原始数据的 API 函数。
Package luaengine 提供 Lua 状态池实现 ¶
该文件实现了基于 sync.Pool 的 Lua 状态复用机制, 用于优化 Lua 虚拟机的创建和销毁开销。
Package luaengine 提供脚本热更新功能 ¶
该文件实现了 Lua 脚本文件监控和热更新机制,支持在运行时 自动检测脚本变化并重新加载,无需重启应用。
Index ¶
- Constants
- Variables
- func AddOperationToRet(L *lua.LState, placeholderKey string, data *lua.LTable)
- func BuildESOperation(L *lua.LState, index lua.LValue, action string, id lua.LValue, body lua.LValue) *lua.LTable
- func BuildMongoDBOperation(L *lua.LState, collection lua.LValue, action string, id lua.LValue, ...) *lua.LTable
- func BuildOperationTable(L *lua.LState, fields map[string]lua.LValue) *lua.LTable
- func CompileLuaScript(script string, filePath string) (*lua.FunctionProto, error)
- func ConvertToLuaValue(value interface{}) interface{}
- func ConvertType(value interface{}, targetType reflect.Type) (interface{}, error)
- func DefaultHTTPClient() *http.Client
- func DoScript(input map[string]interface{}, action string, proto *lua.FunctionProto) error
- func FormatPanic(info PanicInfo) string
- func GenerateUniqueKey(prefix, key string) string
- func GetErrorType(err error) string
- func InitGlobalLuaStatePool(deps *DependencyContext, autoLoadModules ...bool)
- func InterfaceToLv(v interface{}) lua.LValue
- func IsRetryableError(err error) bool
- func LvToByteArray(lv lua.LValue) []byte
- func LvToInterface(lv lua.LValue, tableToJson bool) interface{}
- func LvToMap(lv lua.LValue) (map[string]interface{}, bool)
- func LvToString(lv lua.LValue) string
- func NewRequest(method, url string, body io.Reader) (*http.Request, error)
- func PaddingTable(L *lua.LState, t *lua.LTable, m map[string]interface{})
- func RegisterGlobalModules(L *lua.LState, autoLoadAsGlobals bool)
- func RegisterTypeConverter(fromType, toType reflect.Type, handler ConvertHandler)
- func ReloadScript(filePath string) (*lua.FunctionProto, error)
- func SafeExecute(fn func() error, errorHandler ...func(error) error) error
- func SetGlobalDependencies(deps *DependencyContext)
- func WrapError(err error, context string) error
- type ContentType
- type ConvertHandler
- type DefaultHTTPLogger
- type DefaultHTTPMetrics
- func (m *DefaultHTTPMetrics) GetStats() map[string]interface{}
- func (m *DefaultHTTPMetrics) PrintStats()
- func (m *DefaultHTTPMetrics) RecordError(method, url string, err error)
- func (m *DefaultHTTPMetrics) RecordRequest(method, url string, duration time.Duration, statusCode int)
- func (m *DefaultHTTPMetrics) RecordRetry(method, url string, attempt int)
- func (m *DefaultHTTPMetrics) Reset()
- type DependencyContext
- func (d *DependencyContext) GetHTTPClient() interface{}
- func (d *DependencyContext) GetLogger() interface{}
- func (d *DependencyContext) GetMetrics() interface{}
- func (d *DependencyContext) GetMySQLClient() interface{}
- func (d *DependencyContext) GetRedisClient() interface{}
- func (d *DependencyContext) SetHTTPClient(client interface{})
- func (d *DependencyContext) SetLogger(logger interface{})
- func (d *DependencyContext) SetMetrics(metrics interface{})
- func (d *DependencyContext) SetMySQLClient(client interface{})
- func (d *DependencyContext) SetRedisClient(client interface{})
- type ErrorCode
- type ErrorWithContext
- type FileUpload
- type HTTPClientProvider
- type HTTPLogger
- type HTTPMethod
- type HTTPMetrics
- type HTTPRequestOptions
- type HashOperationParser
- type HttpRequest
- type HttpResponse
- type ListOperationParser
- type LuaEngine
- func (e *LuaEngine) Close()
- func (e *LuaEngine) GetDependencies() *DependencyContext
- func (e *LuaEngine) GetSandboxPolicy() *SandboxPolicy
- func (e *LuaEngine) GetState() *lua.LState
- func (e *LuaEngine) Initialize() error
- func (e *LuaEngine) IsInitialized() bool
- func (e *LuaEngine) PutState(state *lua.LState)
- func (e *LuaEngine) SetDependencies(deps *DependencyContext)
- func (e *LuaEngine) SetHTTPClient(client interface{})
- func (e *LuaEngine) SetMySQLClient(client interface{})
- func (e *LuaEngine) SetSandboxPolicy(policy *SandboxPolicy)
- type LuaEngineError
- func ErrConverterTypeUnsupported(fromType, toType string) *LuaEngineError
- func ErrConverterValueInvalid(value interface{}, reason string) *LuaEngineError
- func ErrDependencyNil(depName string) *LuaEngineError
- func ErrDependencyUnsupported(depName, depType string) *LuaEngineError
- func ErrHTTPClient(reason string) *LuaEngineError
- func ErrHTTPRequest(method, url string, err error) *LuaEngineError
- func ErrInvalidArg(argName, reason string) *LuaEngineError
- func ErrNotFound(target string) *LuaEngineError
- func ErrParserInvalidValue(reason string) *LuaEngineError
- func ErrParserUnknownAction(action, dataType string) *LuaEngineError
- func ErrParserUnknownStruct(structureCode string) *LuaEngineError
- func ErrPoolClosed() *LuaEngineError
- func ErrRedisInvalidKey(keyStr, reason string) *LuaEngineError
- func ErrRedisInvalidOp(op string) *LuaEngineError
- func ErrRedisInvalidValue(reason string) *LuaEngineError
- func ErrRedisNilClient() *LuaEngineError
- func NewLuaEngineError(code ErrorCode, message string, err error) *LuaEngineError
- type LuaOperation
- type LuaStatePool
- type Metrics
- func (m *Metrics) GetSlowQueries(limit ...int) []SlowQuery
- func (m *Metrics) GetStats() map[string]interface{}
- func (m *Metrics) RecordExecution(duration time.Duration, action string, inputSize int, err error, ...)
- func (m *Metrics) RecordPoolHit()
- func (m *Metrics) RecordPoolMiss()
- func (m *Metrics) Reset()
- func (m *Metrics) SetSampleConfig(enable bool, rate float64)
- func (m *Metrics) SetSlowQueryThreshold(threshold time.Duration)
- func (m *Metrics) UpdateActiveStates(count int32)
- type OperationParser
- type OperationRegistry
- type PanicInfo
- type PanicRecovery
- type RedisOperation
- type SandboxPolicy
- func (p *SandboxPolicy) AddAllowedModule(moduleName string)
- func (p *SandboxPolicy) AddRestrictedGlobal(name string)
- func (p *SandboxPolicy) AllowFunction(moduleName, funcName string) bool
- func (p *SandboxPolicy) AllowModule(moduleName string) bool
- func (p *SandboxPolicy) ApplyToState(L *lua.LState)
- func (p *SandboxPolicy) FilterGlobals(L *lua.LState)
- func (p *SandboxPolicy) GetMaxExecutionTime() int
- func (p *SandboxPolicy) GetMaxMemory() int64
- func (p *SandboxPolicy) RemoveAllowedModule(moduleName string)
- func (p *SandboxPolicy) RemoveRestrictedGlobal(name string)
- func (p *SandboxPolicy) RestrictGlobal(name string) bool
- func (p *SandboxPolicy) SetMaxExecutionTime(seconds int)
- func (p *SandboxPolicy) SetMaxMemory(bytes int64)
- func (p *SandboxPolicy) ValidateScript(script string) error
- type ScriptWatcher
- func (w *ScriptWatcher) AddFile(filePath string, callback func(string)) error
- func (w *ScriptWatcher) Close()
- func (w *ScriptWatcher) RemoveFile(filePath string)
- func (w *ScriptWatcher) Start() error
- func (w *ScriptWatcher) Stop()
- func (w *ScriptWatcher) WatchDirectory(dirPath string, callback func(string)) error
- type SetOperationParser
- type SlowQuery
- type SortedSetOperationParser
- type StringOperationParser
- type StructureCode
- type TypeConverter
- type TypeConverterRegistry
Constants ¶
const ( // PlaceholderRedis Redis 操作占位符 PlaceholderRedis = "redis_uuid_placeholder" // PlaceholderMongoDB MongoDB 操作占位符 PlaceholderMongoDB = "mongodb_uuid_placeholder" // PlaceholderES Elasticsearch 操作占位符 PlaceholderES = "es_uuid_placeholder" )
占位符常量
Variables ¶
var DefaultHTTPRequestOptions = HTTPRequestOptions{ Timeout: 30 * time.Second, MaxRetries: 3, RetryDelay: 500 * time.Millisecond, RetryBackoff: 2.0, }
DefaultHTTPRequestOptions 默认 HTTP 请求选项
var GlobalOperationRegistry = NewOperationRegistry()
GlobalOperationRegistry 全局操作注册表
Functions ¶
func AddOperationToRet ¶
AddOperationToRet 将操作添加到全局返回表
获取全局返回表,并将操作数据添加到指定键。
参数:
- L: Lua 状态机
- placeholderKey: 返回表中的占位符键名
- data: 操作数据表
func BuildESOperation ¶
func BuildESOperation(L *lua.LState, index lua.LValue, action string, id lua.LValue, body lua.LValue) *lua.LTable
BuildESOperation 构建 Elasticsearch 操作表
构造一个 ES 操作表,包含 index、action、id 和 body 字段。
参数:
- L: Lua 状态机
- index: 索引名称
- action: 操作类型 (insert/update/delete)
- id: 文档 ID(可选)
- body: 请求体
返回值:
- *lua.LTable: 构造的操作表
func BuildMongoDBOperation ¶
func BuildMongoDBOperation(L *lua.LState, collection lua.LValue, action string, id lua.LValue, table lua.LValue) *lua.LTable
BuildMongoDBOperation 构建 MongoDB 操作表
构造一个 MongoDB 操作表,包含 collection、action、id 和 table 字段。
参数:
- L: Lua 状态机
- collection: 集合名称
- action: 操作类型 (insert/update/delete/upsert)
- id: 文档 ID(可选)
- table: 数据表
返回值:
- *lua.LTable: 构造的操作表
func BuildOperationTable ¶
BuildOperationTable 构造操作数据表
创建一个 Lua 表并设置初始字段,用于存储操作数据。
参数:
- L: Lua 状态机
- fields: 要设置的字段键值对
返回值:
- *lua.LTable: 构造的操作表
func CompileLuaScript ¶
func CompileLuaScript(script string, filePath string) (*lua.FunctionProto, error)
CompileLuaScript 编译 Lua 脚本
从文件或直接从脚本内容编译 Lua 代码。 编译时会预加载所有全局模块(如 scriptOps、dbOps 等),确保脚本可以访问这些模块。
参数:
- script: Lua 脚本内容,如果为空则从 filePath 读取
- filePath: Lua 脚本文件路径
返回值:
- *lua.FunctionProto: 编译后的 Lua 函数原型
- error: 编译失败时返回错误
func ConvertToLuaValue ¶
func ConvertToLuaValue(value interface{}) interface{}
ConvertToLuaValue 将 Go 值转换为 Lua 值
使用类型注册表统一处理类型转换,减少重复代码。
参数:
- value: Go 值
返回值:
- interface{}: 可以作为 Lua 值使用的 Go 类型(基础类型或 []byte)
func ConvertType ¶
ConvertType 使用全局注册表转换类型
func DefaultHTTPClient ¶
DefaultHTTPClient 创建默认的 HTTP 客户端
该方法创建一个配置合理的 HTTP 客户端,用于 httpOps 模块。
返回值:
- *http.Client: 默认配置的 HTTP 客户端
func DoScript ¶
func DoScript(input map[string]interface{}, action string, proto *lua.FunctionProto) error
DoScript 执行 Lua 脚本
该函数用于执行编译好的 Lua 脚本原型,处理规则转换。 从全局状态池获取 Lua 状态,填充数据后执行脚本。
参数:
- input: 输入数据,将被填充到 Lua 的全局变量 ___ROW___
- action: 操作类型,将被设置到 Lua 的全局变量 ___ACT___
- proto: Lua 函数原型,要执行的 Lua 脚本
返回值:
- error: 执行失败时的错误信息
func FormatPanic ¶
FormatPanic 格式化 Panic 信息
将 Panic 信息格式化为可读字符串。
参数:
- info: Panic 信息
返回值:
- string: 格式化后的字符串
func GenerateUniqueKey ¶
GenerateUniqueKey 生成唯一键名
使用纳秒时间戳生成唯一键名,防止多次调用同一 key 时数据被覆盖。
参数:
- prefix: 键前缀(如 "RPUSH_3_"、"SADD_4_")
- key: 基础键名
返回值:
- string: 唯一键名
func InitGlobalLuaStatePool ¶
func InitGlobalLuaStatePool(deps *DependencyContext, autoLoadModules ...bool)
InitGlobalLuaStatePool 初始化全局 Lua 状态池
该函数创建并初始化全局 Lua 状态池,用于 DoScript 函数的调用。 必须在调用 DoScript 之前调用。 默认启用自动加载模块为全局变量。
参数:
- deps: 依赖上下文,可以为 nil
- autoLoadModules: 是否自动加载模块为全局变量,默认为 true
func InterfaceToLv ¶
InterfaceToLv 将 Go 接口转换为 Lua 值
将 Go 接口值转换为对应的 Lua 值类型。 使用统一的类型转换逻辑,减少重复代码。
参数:
- v: Go 接口值
返回值:
- lua.LValue: 转换后的 Lua 值
func IsRetryableError ¶
IsRetryableError 判断错误是否可重试
根据错误类型和消息判断是否可以重试操作。
参数:
- err: 错误信息
返回值:
- bool: 是否可重试
func LvToByteArray ¶
LvToByteArray 将 Lua 值转换为字节数组
将 Lua 值转换为 []byte 类型。
参数:
- lv: Lua 值
返回值:
- []byte: 转换后的字节数组
func LvToInterface ¶
LvToInterface 将 Lua 值转换为 Go 接口
递归地将 Lua 值转换为对应的 Go 类型。 支持转换 Lua 表(字典和数组)、数字、字符串、布尔值、nil。
参数:
- lv: Lua 值
- tableToJson: 是否将 Lua 表转换为 JSON 字符串
返回值:
- interface{}: 转换后的 Go 接口值
func LvToMap ¶
LvToMap 将 Lua 表转换为 Go map
将 Lua 字典表转换为 Go map[string]interface{}。 如果 Lua 值不是表类型,返回 nil 和 false。
参数:
- lv: Lua 值
返回值:
- map[string]interface{}: 转换后的 Go map
- bool: 转换是否成功,true 表示成功
func NewRequest ¶
NewRequest 创建新的 HTTP 请求(兼容标准库)
func PaddingTable ¶
PaddingTable 将 Go map 填充到 Lua 表
递归地将 Go map[string]interface{} 转换为 Lua 表,支持嵌套结构。
参数:
- L: Lua 状态机
- t: Lua 表,用于存储转换后的数据
- m: Go map,包含要转换的数据
func RegisterGlobalModules ¶
RegisterGlobalModules 注册所有全局 Lua 模块到指定状态
将所有 Ops 模块预加载到 Lua 状态中,使 Lua 脚本可以直接使用。 该函数是独立的工具函数,可用于任何 Lua 状态实例。
参数:
- L: Lua 状态实例
- autoLoadAsGlobals: 是否将模块设置为全局变量
func RegisterTypeConverter ¶
func RegisterTypeConverter(fromType, toType reflect.Type, handler ConvertHandler)
RegisterTypeConverter 注册全局类型转换器
func ReloadScript ¶
func ReloadScript(filePath string) (*lua.FunctionProto, error)
ReloadScript 重新加载 Lua 脚本
读取并编译指定的 Lua 脚本文件。
参数:
- filePath: 文件路径
返回值:
- *lua.FunctionProto: 编译后的 Lua 函数原型
- error: 编译失败时返回错误
func SafeExecute ¶
SafeExecute 安全执行 Lua 函数
使用 defer recover 捕获 panic,确保错误不会导致程序崩溃。
参数:
- fn: 要执行的函数
- errorHandler: 错误处理函数(可选)
返回值:
- error: 执行错误(包括panic)
func SetGlobalDependencies ¶
func SetGlobalDependencies(deps *DependencyContext)
SetGlobalDependencies 设置全局依赖
该方法设置全局依赖上下文,用于向后兼容。 新代码应通过 DependencyContext 直接访问依赖。
参数:
- deps: 依赖上下文
Types ¶
type ContentType ¶
type ContentType string
ContentType HTTP 请求内容类型
const ( ContentTypeFormURLEncoded ContentType = "application/x-www-form-urlencoded" ContentTypeJSON ContentType = "application/json" ContentTypeFormData ContentType = "multipart/form-data" ContentTypeTextPlain ContentType = "text/plain" )
type ConvertHandler ¶
type ConvertHandler func(value interface{}) (interface{}, error)
ConvertHandler 类型转换处理器函数类型
type DefaultHTTPLogger ¶
type DefaultHTTPLogger struct {
// contains filtered or unexported fields
}
DefaultHTTPLogger 默认的 HTTP 日志记录器
func NewDefaultHTTPLogger ¶
func NewDefaultHTTPLogger(logger interface{}) *DefaultHTTPLogger
NewDefaultHTTPLogger 创建默认的 HTTP 日志记录器
参数:
- logger: 日志记录器(可以是 nil)
返回值:
- *DefaultHTTPLogger: 日志记录器实例
func (*DefaultHTTPLogger) LogRequest ¶
func (l *DefaultHTTPLogger) LogRequest(req *HttpRequest, requestID string)
LogRequest 记录 HTTP 请求
参数:
- req: HttpRequest 对象
- requestID: 请求 ID
func (*DefaultHTTPLogger) LogResponse ¶
func (l *DefaultHTTPLogger) LogResponse(resp *HttpResponse, err error)
LogResponse 记录 HTTP 响应
参数:
- resp: HttpResponse 对象
- err: 错误信息(如果有)
type DefaultHTTPMetrics ¶
type DefaultHTTPMetrics struct {
// contains filtered or unexported fields
}
DefaultHTTPMetrics 默认的 HTTP 性能指标收集器
func NewDefaultHTTPMetrics ¶
func NewDefaultHTTPMetrics() *DefaultHTTPMetrics
NewDefaultHTTPMetrics 创建默认的 HTTP 性能指标收集器
返回值:
- *DefaultHTTPMetrics: 指标收集器实例
func (*DefaultHTTPMetrics) GetStats ¶
func (m *DefaultHTTPMetrics) GetStats() map[string]interface{}
GetStats 获取统计信息
返回值:
- map[string]interface{}: 统计信息
func (*DefaultHTTPMetrics) RecordError ¶
func (m *DefaultHTTPMetrics) RecordError(method, url string, err error)
RecordError 记录错误
参数:
- method: HTTP 方法
- url: 请求 URL
- err: 错误信息
func (*DefaultHTTPMetrics) RecordRequest ¶
func (m *DefaultHTTPMetrics) RecordRequest(method, url string, duration time.Duration, statusCode int)
RecordRequest 记录请求
参数:
- method: HTTP 方法
- url: 请求 URL
- duration: 请求耗时
- statusCode: HTTP 状态码
func (*DefaultHTTPMetrics) RecordRetry ¶
func (m *DefaultHTTPMetrics) RecordRetry(method, url string, attempt int)
RecordRetry 记录重试
参数:
- method: HTTP 方法
- url: 请求 URL
- attempt: 重试次数
type DependencyContext ¶
type DependencyContext struct {
// MySQLClient MySQL 客户端连接
// 用于 dbOps 模块执行 SQL 查询
// 可选类型:*canal.Canal 或自定义接口
MySQLClient atomic.Value
// HTTPClient HTTP 客户端
// 用于 httpOps 模块发起 HTTP 请求
// 可选类型:*http.Client 或自定义封装
HTTPClient atomic.Value
// RedisClient Redis 客户端
// 用于执行 Lua 脚本中 redisOps 模块构造的 Redis 操作
// 可选类型:redis.Cmdable(支持单实例、集群、哨兵模式)
RedisClient atomic.Value
// Logger 日志记录器
// 用于 Lua 脚本执行日志
// 可选类型:*slog.Logger 或自定义日志接口
Logger atomic.Value
// Metrics 指标收集器
// 用于 Lua 脚本执行指标统计
// 可选类型:自定义指标接口
Metrics atomic.Value
}
DependencyContext Lua 引擎依赖上下文
该结构体封装了 Lua 引擎运行所需的所有外部依赖, 通过依赖注入的方式传递给 Lua 模块,避免使用全局变量。
设计原则: - 使用 interface{} 类型支持不同实现 - 原子更新确保并发安全 - 支持可选依赖(nil 表示未设置)
func GetGlobalDependencies ¶
func GetGlobalDependencies() *DependencyContext
GetGlobalDependencies 获取全局依赖
返回全局依赖上下文,如果未设置则返回 nil。
返回值:
- *DependencyContext: 全局依赖上下文,或 nil
func NewDependencyContext ¶
func NewDependencyContext() *DependencyContext
NewDependencyContext 创建新的依赖上下文
返回一个空的依赖上下文,后续可以通过 Set 方法设置各个依赖。
返回值:
- *DependencyContext: 新的依赖上下文实例
func (*DependencyContext) GetHTTPClient ¶
func (d *DependencyContext) GetHTTPClient() interface{}
GetHTTPClient 获取 HTTP 客户端
返回已设置的 HTTP 客户端,如果未设置则返回 nil。
返回值:
- interface{}: HTTP 客户端,或 nil
func (*DependencyContext) GetLogger ¶
func (d *DependencyContext) GetLogger() interface{}
GetLogger 获取日志记录器
返回已设置的日志记录器,如果未设置则返回 nil。
返回值:
- interface{}: 日志记录器,或 nil
func (*DependencyContext) GetMetrics ¶
func (d *DependencyContext) GetMetrics() interface{}
GetMetrics 获取指标收集器
返回已设置的指标收集器,如果未设置则返回 nil。
返回值:
- interface{}: 指标收集器,或 nil
func (*DependencyContext) GetMySQLClient ¶
func (d *DependencyContext) GetMySQLClient() interface{}
GetMySQLClient 获取 MySQL 客户端
返回已设置的 MySQL 客户端,如果未设置则返回 nil。
返回值:
- interface{}: MySQL 客户端连接,或 nil
func (*DependencyContext) GetRedisClient ¶
func (d *DependencyContext) GetRedisClient() interface{}
GetRedisClient 获取 Redis 客户端
返回已设置的 Redis 客户端,如果未设置则返回 nil。
返回值:
- interface{}: Redis 客户端,或 nil
func (*DependencyContext) SetHTTPClient ¶
func (d *DependencyContext) SetHTTPClient(client interface{})
SetHTTPClient 设置 HTTP 客户端
该方法设置 HTTP 客户端,原子操作保证并发安全。 如果 client 为 nil,表示移除 HTTP 客户端依赖。
参数:
- client: HTTP 客户端,可以为 nil
func (*DependencyContext) SetLogger ¶
func (d *DependencyContext) SetLogger(logger interface{})
SetLogger 设置日志记录器
该方法设置日志记录器,原子操作保证并发安全。 如果 logger 为 nil,表示移除日志记录器依赖。
参数:
- logger: 日志记录器,可以为 nil
func (*DependencyContext) SetMetrics ¶
func (d *DependencyContext) SetMetrics(metrics interface{})
SetMetrics 设置指标收集器
该方法设置指标收集器,原子操作保证并发安全。 如果 metrics 为 nil,表示移除指标收集器依赖。
参数:
- metrics: 指标收集器,可以为 nil
func (*DependencyContext) SetMySQLClient ¶
func (d *DependencyContext) SetMySQLClient(client interface{})
SetMySQLClient 设置 MySQL 客户端
该方法设置 MySQL 客户端连接,原子操作保证并发安全。 如果 client 为 nil,表示移除 MySQL 客户端依赖。
参数:
- client: MySQL 客户端连接,可以为 nil
func (*DependencyContext) SetRedisClient ¶
func (d *DependencyContext) SetRedisClient(client interface{})
SetRedisClient 设置 Redis 客户端
该方法设置 Redis 客户端,原子操作保证并发安全。 如果 client 为 nil,表示移除 Redis 客户端依赖。
参数:
- client: Redis 客户端,可以为 nil
type ErrorCode ¶
type ErrorCode string
ErrorCode 错误码类型
const ( // 通用错误 (1000-1999) ErrCodeGeneral ErrorCode = "LUA1000" // 通用错误 ErrCodeInvalidArg ErrorCode = "LUA1001" // 无效参数 ErrCodeNotFound ErrorCode = "LUA1002" // 未找到 // Redis 相关错误 (2000-2999) ErrCodeRedisNilClient ErrorCode = "LUA2000" // Redis 客户端为空 ErrCodeRedisInvalidKey ErrorCode = "LUA2001" // 无效的 key 格式 ErrCodeRedisInvalidOp ErrorCode = "LUA2002" // 无效的操作 ErrCodeRedisInvalidValue ErrorCode = "LUA2003" // 无效的值 ErrCodeRedisOperationFail ErrorCode = "LUA2004" // Redis 操作失败 ErrCodeRedisOperationFailed ErrorCode = "LUA2005" // Redis 操作失败(多错误聚合) // 解析器相关错误 (3000-3999) ErrCodeParserUnknownStruct ErrorCode = "LUA3000" // 未知的结构码 ErrCodeParserUnknownAction ErrorCode = "LUA3001" // 未知的操作类型 ErrCodeParserInvalidValue ErrorCode = "LUA3002" // 无效的值类型 ErrCodeParserInvalidStructure ErrorCode = "LUA3003" // 无效的数据结构 // 转换器相关错误 (4000-4999) ErrCodeConverterTypeUnsupported ErrorCode = "LUA4000" // 不支持的类型转换 ErrCodeConverterTypeMismatch ErrorCode = "LUA4001" // 类型不匹配 ErrCodeConverterValueInvalid ErrorCode = "LUA4002" // 无效的值 // HTTP 相关错误 (5000-5999) ErrCodeHTTPClientError ErrorCode = "LUA5000" // HTTP 客户端错误 ErrCodeHTTPRequestError ErrorCode = "LUA5001" // HTTP 请求错误 ErrCodeHTTPResponseError ErrorCode = "LUA5002" // HTTP 响应错误 // 状态池相关错误 (6000-6999) ErrCodePoolClosed ErrorCode = "LUA6000" // 状态池已关闭 ErrCodePoolInvalidState ErrorCode = "LUA6001" // 无效的状态 ErrCodePoolInitFailed ErrorCode = "LUA6002" // 状态池初始化失败 ErrCodePoolNoDependencies ErrorCode = "LUA6003" // 无依赖上下文 ErrCodePanic ErrorCode = "LUA6004" // Lua 脚本 panic // 依赖注入相关错误 (7000-7999) ErrCodeDependencyNil ErrorCode = "LUA7000" // 依赖为空 ErrCodeDependencyUnsupported ErrorCode = "LUA7001" // 不支持的依赖类型 ErrCodeDependencyNotFound ErrorCode = "LUA7002" // 依赖未找到 )
标准错误码定义
type ErrorWithContext ¶
type ErrorWithContext struct {
*LuaEngineError
Context map[string]interface{}
}
ErrorWithContext 带上下文的错误包装器
允许在错误中携带额外的上下文信息。
func NewErrorWithContext ¶
func NewErrorWithContext(baseError *LuaEngineError, context map[string]interface{}) *ErrorWithContext
NewErrorWithContext 创建带上下文的错误
参数:
- baseError: 基础错误
- context: 上下文键值对
返回值:
- *ErrorWithContext: 带上下文的错误实例
type FileUpload ¶
type FileUpload struct {
FieldName string // 表单字段名
FileName string // 文件名
ContentType string // 文件内容类型(可选)
Content []byte // 文件内容
Reader io.Reader // 文件读取器(与 Content 二选一)
}
FileUpload 文件上传结构
type HTTPClientProvider ¶
type HTTPClientProvider interface {
GetHTTPClient() interface{}
}
HTTPClientProvider HTTP 客户端提供者
用于统一 HTTP 客户端的获取逻辑。
type HTTPLogger ¶
type HTTPLogger interface {
LogRequest(req *HttpRequest, requestID string)
LogResponse(resp *HttpResponse, err error)
}
HTTPLogger 接口定义 HTTP 日志记录器
func GetHTTPLogger ¶
func GetHTTPLogger() HTTPLogger
GetHTTPLogger 从依赖上下文获取 HTTP 日志记录器
参数:
- 无
返回值:
- HTTPLogger: HTTP 日志记录器接口
type HTTPMethod ¶
type HTTPMethod string
HTTPMethod HTTP 请求方法
const ( MethodGET HTTPMethod = "GET" MethodPOST HTTPMethod = "POST" MethodPUT HTTPMethod = "PUT" MethodDELETE HTTPMethod = "DELETE" )
type HTTPMetrics ¶
type HTTPMetrics interface {
RecordRequest(method, url string, duration time.Duration, statusCode int)
RecordError(method, url string, err error)
RecordRetry(method, url string, attempt int)
}
HTTPMetrics 接口定义 HTTP 性能指标收集器
func GetHTTPMetrics ¶
func GetHTTPMetrics() HTTPMetrics
GetHTTPMetrics 从依赖上下文获取 HTTP 指标收集器
参数:
- 无
返回值:
- HTTPMetrics: HTTP 指标收集器接口
type HTTPRequestOptions ¶
type HTTPRequestOptions struct {
Timeout time.Duration // 超时时间
MaxRetries int // 最大重试次数
RetryDelay time.Duration // 重试延迟
RetryBackoff float64 // 退避系数
}
HTTPRequestOptions HTTP 请求选项
type HashOperationParser ¶
type HashOperationParser struct{}
HashOperationParser Hash 操作解析器
func NewHashOperationParser ¶
func NewHashOperationParser() *HashOperationParser
NewHashOperationParser 创建 Hash 操作解析器
func (*HashOperationParser) GetSupportedActions ¶
func (p *HashOperationParser) GetSupportedActions() []string
GetSupportedActions 获取支持的操作列表
type HttpRequest ¶
type HttpRequest struct {
URL string // 请求 URL
Method HTTPMethod // HTTP 方法
Headers map[string]string // 请求头
QueryParams map[string]string // URL 查询参数
JSONBody interface{} // JSON 请求体
FormData map[string]interface{} // 表单数据
Files []*FileUpload // 文件上传列表
RawBody *string // 原始请求体
ContentType ContentType // 内容类型
Timeout time.Duration // 超时时间
}
HttpRequest HTTP 请求结构
type HttpResponse ¶
type HttpResponse struct {
StatusCode int // HTTP 状态码
Headers map[string][]string // 响应头
Body []byte // 响应体
Duration time.Duration // 请求耗时
RequestID string // 请求 ID(用于日志追踪)
}
HttpResponse HTTP 响应结构
type ListOperationParser ¶
type ListOperationParser struct{}
ListOperationParser List 操作解析器
func NewListOperationParser ¶
func NewListOperationParser() *ListOperationParser
NewListOperationParser 创建 List 操作解析器
func (*ListOperationParser) GetSupportedActions ¶
func (p *ListOperationParser) GetSupportedActions() []string
GetSupportedActions 获取支持的操作列表
type LuaEngine ¶
type LuaEngine struct {
// contains filtered or unexported fields
}
LuaEngine Lua 引擎核心管理器
负责管理 Lua 状态池、模块加载和 Lua 脚本执行。 使用 sync.Pool 复用 Lua 状态,避免频繁创建和销毁带来的性能开销。
func NewLuaEngine ¶
func NewLuaEngine(deps *DependencyContext, policy *SandboxPolicy, autoLoadModules ...bool) *LuaEngine
NewLuaEngine 创建新的 Lua 引擎实例
返回一个已初始化但未启动的 Lua 引擎。 需要调用 RegisterModules() 注册模块后才能使用。
参数:
- deps: 依赖上下文,可以为 nil(稍后通过 SetDependencies 设置)
- policy: 沙箱安全策略,可以为 nil(使用默认策略)
- autoLoadModules: 是否自动加载模块为全局变量,默认为 true
返回值:
- *LuaEngine: 新的 Lua 引擎实例
func (*LuaEngine) Close ¶
func (e *LuaEngine) Close()
Close 关闭 Lua 引擎
关闭状态池中的所有 Lua 状态,释放资源。 调用后不能再使用该引擎。
func (*LuaEngine) GetDependencies ¶
func (e *LuaEngine) GetDependencies() *DependencyContext
GetDependencies 获取依赖上下文
返回当前的依赖上下文。
返回值:
- *DependencyContext: 当前的依赖上下文
func (*LuaEngine) GetSandboxPolicy ¶
func (e *LuaEngine) GetSandboxPolicy() *SandboxPolicy
GetSandboxPolicy 获取沙箱安全策略
返回当前的沙箱安全策略。
返回值:
- *SandboxPolicy: 当前的沙箱安全策略
func (*LuaEngine) GetState ¶
GetState 从状态池获取 Lua 状态
该方法从池中获取一个可复用的 Lua 状态。 使用完毕后应该调用 PutState() 归还状态。
返回值:
- *lua.LState: Lua 状态实例
func (*LuaEngine) Initialize ¶
Initialize 初始化 Lua 引擎
注册预加载的 Lua 模块,准备 Lua 状态池。 必须在执行脚本之前调用。
返回值:
- error: 初始化失败时的错误信息
func (*LuaEngine) PutState ¶
PutState 将 Lua 状态归还到池中
将使用完毕的 Lua 状态归还到池中,供后续复用。
参数:
- state: 要归还的 Lua 状态实例
func (*LuaEngine) SetDependencies ¶
func (e *LuaEngine) SetDependencies(deps *DependencyContext)
SetDependencies 设置依赖上下文
该方法设置或更新 Lua 引擎的依赖上下文。 原子操作保证并发安全,可以在运行时动态更新依赖。
参数:
- deps: 新的依赖上下文
func (*LuaEngine) SetHTTPClient ¶
func (e *LuaEngine) SetHTTPClient(client interface{})
SetHTTPClient 设置 HTTP 客户端
便捷方法,用于单独设置 HTTP 客户端。
参数:
- client: HTTP 客户端
func (*LuaEngine) SetMySQLClient ¶
func (e *LuaEngine) SetMySQLClient(client interface{})
SetMySQLClient 设置 MySQL 客户端
便捷方法,用于单独设置 MySQL 客户端。
参数:
- client: MySQL 客户端
func (*LuaEngine) SetSandboxPolicy ¶
func (e *LuaEngine) SetSandboxPolicy(policy *SandboxPolicy)
SetSandboxPolicy 设置沙箱安全策略
该方法设置或更新 Lua 引擎的沙箱策略。 新策略会应用到新创建的 Lua 状态。
参数:
- policy: 新的沙箱安全策略
type LuaEngineError ¶
type LuaEngineError struct {
Code ErrorCode // 错误码
Message string // 错误消息
Err error // 原始错误(如果有)
Stack []string // 堆栈跟踪
}
LuaEngineError Lua 引擎标准错误
实现了 error 接口,包含错误码、消息、原始错误和堆栈信息。
func ErrConverterTypeUnsupported ¶
func ErrConverterTypeUnsupported(fromType, toType string) *LuaEngineError
ErrConverterTypeUnsupported 创建不支持的类型转换错误
func ErrConverterValueInvalid ¶
func ErrConverterValueInvalid(value interface{}, reason string) *LuaEngineError
ErrConverterValueInvalid 创建无效的值错误
func ErrDependencyNil ¶
func ErrDependencyNil(depName string) *LuaEngineError
ErrDependencyNil 创建依赖为空错误
func ErrDependencyUnsupported ¶
func ErrDependencyUnsupported(depName, depType string) *LuaEngineError
ErrDependencyUnsupported 创建不支持的依赖类型错误
func ErrHTTPRequest ¶
func ErrHTTPRequest(method, url string, err error) *LuaEngineError
ErrHTTPRequest 创建 HTTP 请求错误
func ErrInvalidArg ¶
func ErrInvalidArg(argName, reason string) *LuaEngineError
ErrInvalidArg 创建无效参数错误
func ErrParserInvalidValue ¶
func ErrParserInvalidValue(reason string) *LuaEngineError
ErrParserInvalidValue 创建无效的值类型错误
func ErrParserUnknownAction ¶
func ErrParserUnknownAction(action, dataType string) *LuaEngineError
ErrParserUnknownAction 创建未知的操作类型错误
func ErrParserUnknownStruct ¶
func ErrParserUnknownStruct(structureCode string) *LuaEngineError
ErrParserUnknownStruct 创建未知的结构码错误
func ErrRedisInvalidKey ¶
func ErrRedisInvalidKey(keyStr, reason string) *LuaEngineError
ErrRedisInvalidKey 创建无效的 key 错误
func ErrRedisInvalidOp ¶
func ErrRedisInvalidOp(op string) *LuaEngineError
ErrRedisInvalidOp 创建无效的操作错误
func ErrRedisInvalidValue ¶
func ErrRedisInvalidValue(reason string) *LuaEngineError
ErrRedisInvalidValue 创建无效的值错误
func ErrRedisNilClient ¶
func ErrRedisNilClient() *LuaEngineError
ErrRedisNilClient 创建 Redis 客户端为空错误
func NewLuaEngineError ¶
func NewLuaEngineError(code ErrorCode, message string, err error) *LuaEngineError
NewLuaEngineError 创建新的 Lua 引擎错误
参数:
- code: 错误码
- message: 错误消息
- err: 原始错误(可选)
返回值:
- *LuaEngineError: 错误实例
func (*LuaEngineError) Unwrap ¶
func (e *LuaEngineError) Unwrap() error
Unwrap 返回包装的错误,支持 errors.Unwrap
type LuaOperation ¶
type LuaOperation interface {
// Execute 执行 Lua 操作
//
// 参数:
// - L: Lua 状态机
//
// 返回值:
// - int: 返回栈顶元素数量
Execute(L *lua.LState) int
}
LuaOperation Lua 操作接口
统一所有 Lua 操作的执行接口,包括 Redis、HTTP、DB 等操作。
type LuaStatePool ¶
type LuaStatePool struct {
// contains filtered or unexported fields
}
LuaStatePool Lua 状态池
使用 sync.Pool 复用 Lua 状态,避免频繁创建和销毁带来的性能开销。 每个从池中获取的 Lua 状态都会预加载所有模块。
func GetGlobalLuaStatePool ¶
func GetGlobalLuaStatePool() *LuaStatePool
GetGlobalLuaStatePool 获取全局 Lua 状态池
返回全局 Lua 状态池实例。
返回值:
- *LuaStatePool: 全局 Lua 状态池实例
func NewLuaStatePool ¶
func NewLuaStatePool(deps *DependencyContext, autoLoadModules ...bool) *LuaStatePool
NewLuaStatePool 创建新的 Lua 状态池
初始化状态池并注册预加载模块。
参数:
- deps: 依赖上下文,可以为 nil
- autoLoadModules: 是否自动将模块设置为全局变量,默认为 true
返回值:
- *LuaStatePool: 新的 Lua 状态池实例
func (*LuaStatePool) Get ¶
func (p *LuaStatePool) Get() *lua.LState
Get 从池中获取 Lua 状态
如果池中有可用的状态则复用,否则创建新的状态。 会自动增加活跃状态计数。
返回值:
- *lua.LState: Lua 状态实例
func (*LuaStatePool) GetActiveCount ¶
func (p *LuaStatePool) GetActiveCount() int32
GetActiveCount 获取活跃状态计数
返回当前正在使用的 Lua 状态数量。
返回值:
- int32: 活跃状态数量
func (*LuaStatePool) GetDependencies ¶
func (p *LuaStatePool) GetDependencies() *DependencyContext
GetDependencies 获取依赖上下文
返回当前的依赖上下文。
返回值:
- *DependencyContext: 当前的依赖上下文
func (*LuaStatePool) Put ¶
func (p *LuaStatePool) Put(L *lua.LState)
Put 将 Lua 状态归还到池中
将使用完毕的 Lua 状态归还到池中,供后续复用。 在归还前会深度清理状态的全局环境和栈,避免内存泄漏和数据污染。 会自动减少活跃状态计数。
参数:
- L: 要归还的 Lua 状态实例
func (*LuaStatePool) SetDependencies ¶
func (p *LuaStatePool) SetDependencies(deps *DependencyContext)
SetDependencies 设置依赖上下文
该方法设置或更新状态池的依赖上下文。 原子操作保证并发安全。
参数:
- deps: 新的依赖上下文
func (*LuaStatePool) Shutdown ¶
func (p *LuaStatePool) Shutdown()
Shutdown 关闭状态池
关闭状态池中的所有 Lua 状态,释放资源。
type Metrics ¶
type Metrics struct {
// 执行统计
TotalExecutions int64 // 总执行次数
TotalErrors int64 // 总错误次数
TotalDuration time.Duration // 总执行时间
// 状态池统计
PoolHits int32 // 状态池命中次数
PoolMisses int32 // 状态池未命中次数
ActiveStates int32 // 当前活跃状态数
// 慢查询
SlowQueries []SlowQuery // 慢查询列表(最多保留最近100条)
SlowQueryThreshold time.Duration // 慢查询阈值
// 指标采样
EnableSampling bool // 是否启用指标采样
SampleRate float64 // 采样率(0-1)
// contains filtered or unexported fields
}
Metrics Lua 引擎指标收集器
收集 Lua 脚本执行的关键性能指标,包括执行时间、错误率、资源使用等。
func (*Metrics) GetSlowQueries ¶
GetSlowQueries 获取慢查询列表
返回最近的慢查询记录。
参数:
- limit: 返回的最大数量,0表示返回全部
返回值:
- []SlowQuery: 慢查询列表
func (*Metrics) RecordExecution ¶
func (m *Metrics) RecordExecution(duration time.Duration, action string, inputSize int, err error, scriptName ...string)
RecordExecution 记录脚本执行
记录一次 Lua 脚本的执行信息,包括执行时间、错误状态等。 自动判断是否为慢查询并记录。
参数:
- duration: 执行耗时
- action: 操作类型
- inputSize: 输入数据大小
- err: 执行错误(如果有)
- scriptName: 脚本名称(可选)
func (*Metrics) UpdateActiveStates ¶
UpdateActiveStates 更新活跃状态数
type OperationParser ¶
type OperationParser interface {
// Parse 解析操作
// 参数:
// - action: 操作类型(如 SET, GET, HSET 等)
// - key: Redis 键
// - value: 操作值
// - L: Lua 状态机(可选,用于处理 Lua 表)
// 返回值:
// - *RedisOperation: 解析后的操作
// - error: 解析失败时的错误
Parse(action string, key string, value lua.LValue, L *lua.LState) (*RedisOperation, error)
// GetSupportedActions 获取支持的操作列表
// 返回值:
// - []string: 支持的操作列表
GetSupportedActions() []string
}
OperationParser 操作解析器接口
定义了操作解析的统一接口,支持不同类型的 Redis 操作。
type OperationRegistry ¶
type OperationRegistry struct {
// contains filtered or unexported fields
}
OperationRegistry 操作注册表
使用注册表模式管理不同数据结构的操作解析器。
func NewOperationRegistry ¶
func NewOperationRegistry() *OperationRegistry
NewOperationRegistry 创建新的操作注册表
func (*OperationRegistry) ParseOperation ¶
func (r *OperationRegistry) ParseOperation(structureCode StructureCode, action string, key string, value lua.LValue, L *lua.LState) (*RedisOperation, error)
ParseOperation 解析操作
统一的操作解析入口,根据结构码路由到对应的解析器。
参数:
- structureCode: 结构码
- action: 操作类型
- key: Redis 键
- value: 操作值
- L: Lua 状态机
返回值:
- *RedisOperation: 解析后的操作
- error: 解析失败时的错误
func (*OperationRegistry) RegisterParser ¶
func (r *OperationRegistry) RegisterParser(code StructureCode, parser OperationParser)
RegisterParser 注册操作解析器
参数:
- code: 结构码
- parser: 操作解析器
type PanicInfo ¶
type PanicInfo struct {
Timestamp time.Time // 发生时间
Message string // Panic 消息
StackTrace string // 堆栈信息
Recovered bool // 是否已恢复
}
PanicInfo Panic 信息记录
type PanicRecovery ¶
type PanicRecovery struct {
// contains filtered or unexported fields
}
PanicRecovery Panic 恢复处理器
捕获 Lua 脚本执行过程中的panic,提供详细的堆栈信息。
func NewPanicRecovery ¶
func NewPanicRecovery() *PanicRecovery
NewPanicRecovery 创建新的 Panic 恢复处理器
返回值:
- *PanicRecovery: 新的处理器实例
func (*PanicRecovery) GetLastPanic ¶
func (p *PanicRecovery) GetLastPanic() *PanicInfo
GetLastPanic 获取最后一次 Panic
返回值:
- *PanicInfo: 最后一次 Panic 信息,如果没有则返回 nil
func (*PanicRecovery) GetPanicStack ¶
func (p *PanicRecovery) GetPanicStack(limit ...int) []PanicInfo
GetPanicStack 获取 Panic 栈
参数:
- limit: 返回的最大数量,0表示返回全部
返回值:
- []PanicInfo: Panic 信息列表
func (*PanicRecovery) RecoverFromPanic ¶
func (p *PanicRecovery) RecoverFromPanic(r interface{}) error
RecoverFromPanic 从 Panic 中恢复
捕获panic并记录详细信息,返回错误对象。
参数:
- r: panic 值
返回值:
- error: 转换后的错误对象
type RedisOperation ¶
type RedisOperation struct {
Cmd string // Redis 命令
Args []interface{} // 命令参数
}
RedisOperation Redis 操作定义
func ParseRedisOperation ¶
ParseRedisOperation 解析 Redis 操作(向后兼容)
该函数保留了原有的解析逻辑,内部使用新的操作注册表实现。
参数:
- keyStr: Redis 操作键名(格式:action_structure_key)
- value: 操作值
- L: Lua 状态机
返回值:
- *RedisOperation: 解析后的操作
- error: 解析失败时的错误
type SandboxPolicy ¶
type SandboxPolicy struct {
// contains filtered or unexported fields
}
SandboxPolicy 沙箱安全策略
定义了 Lua 脚本的安全策略,包括允许的模块、函数和操作。
func NewDefaultSandboxPolicy ¶
func NewDefaultSandboxPolicy() *SandboxPolicy
NewDefaultSandboxPolicy 创建默认的沙箱策略
返回一个默认的安全策略,限制了对危险模块和函数的访问。
返回值:
- *SandboxPolicy: 默认的沙箱策略
func NewOpenSandboxPolicy ¶
func NewOpenSandboxPolicy() *SandboxPolicy
NewOpenSandboxPolicy 创建开放的沙箱策略
返回一个开放的沙箱策略,允许所有模块和函数访问。 警告:此策略存在安全风险,仅用于开发和测试环境。
返回值:
- *SandboxPolicy: 开放的沙箱策略
func (*SandboxPolicy) AddAllowedModule ¶
func (p *SandboxPolicy) AddAllowedModule(moduleName string)
AddAllowedModule 添加允许的模块
参数:
- moduleName: 模块名称
func (*SandboxPolicy) AddRestrictedGlobal ¶
func (p *SandboxPolicy) AddRestrictedGlobal(name string)
AddRestrictedGlobal 添加受限的全局变量
参数:
- name: 全局变量或函数名称
func (*SandboxPolicy) AllowFunction ¶
func (p *SandboxPolicy) AllowFunction(moduleName, funcName string) bool
AllowFunction 检查是否允许调用指定函数
参数:
- moduleName: 模块名称
- funcName: 函数名称
返回值:
- bool: true 表示允许调用,false 表示禁止
func (*SandboxPolicy) AllowModule ¶
func (p *SandboxPolicy) AllowModule(moduleName string) bool
AllowModule 检查是否允许访问指定模块
参数:
- moduleName: 模块名称
返回值:
- bool: true 表示允许访问,false 表示禁止
func (*SandboxPolicy) ApplyToState ¶
func (p *SandboxPolicy) ApplyToState(L *lua.LState)
ApplyToState 将沙箱策略应用到 Lua 状态
执行全局变量过滤,设置执行限制等。
参数:
- L: Lua 状态机
func (*SandboxPolicy) FilterGlobals ¶
func (p *SandboxPolicy) FilterGlobals(L *lua.LState)
FilterGlobals 过滤 Lua 状态的全局环境
移除受限的全局变量和函数,确保沙箱安全。
参数:
- L: Lua 状态机
func (*SandboxPolicy) GetMaxExecutionTime ¶
func (p *SandboxPolicy) GetMaxExecutionTime() int
GetMaxExecutionTime 获取最大执行时间
返回值:
- int: 最大执行时间(秒)
func (*SandboxPolicy) GetMaxMemory ¶
func (p *SandboxPolicy) GetMaxMemory() int64
GetMaxMemory 获取最大内存使用
返回值:
- int64: 最大内存使用(字节)
func (*SandboxPolicy) RemoveAllowedModule ¶
func (p *SandboxPolicy) RemoveAllowedModule(moduleName string)
RemoveAllowedModule 移除允许的模块
参数:
- moduleName: 模块名称
func (*SandboxPolicy) RemoveRestrictedGlobal ¶
func (p *SandboxPolicy) RemoveRestrictedGlobal(name string)
RemoveRestrictedGlobal 移除受限的全局变量
参数:
- name: 全局变量或函数名称
func (*SandboxPolicy) RestrictGlobal ¶
func (p *SandboxPolicy) RestrictGlobal(name string) bool
RestrictGlobal 检查是否限制指定的全局变量或函数
参数:
- name: 全局变量或函数名称
返回值:
- bool: true 表示限制访问,false 表示允许访问
func (*SandboxPolicy) SetMaxExecutionTime ¶
func (p *SandboxPolicy) SetMaxExecutionTime(seconds int)
SetMaxExecutionTime 设置最大执行时间
参数:
- seconds: 最大执行时间(秒),0 表示无限制
func (*SandboxPolicy) SetMaxMemory ¶
func (p *SandboxPolicy) SetMaxMemory(bytes int64)
SetMaxMemory 设置最大内存使用
参数:
- bytes: 最大内存使用(字节),0 表示无限制
func (*SandboxPolicy) ValidateScript ¶
func (p *SandboxPolicy) ValidateScript(script string) error
ValidateScript 验证脚本是否符合沙箱策略
检查脚本中是否有尝试访问受限模块或函数的代码。 注意:这是一个简单的静态检查,不能覆盖所有情况。
参数:
- script: Lua 脚本内容
返回值:
- error: 如果发现违规操作,返回错误;否则返回 nil
type ScriptWatcher ¶
type ScriptWatcher struct {
// contains filtered or unexported fields
}
ScriptWatcher 脚本监视器
监控 Lua 脚本文件的变化,触发重新加载。
func NewScriptWatcher ¶
NewScriptWatcher 创建新的脚本监视器
参数:
- ctx: 上下文
- reloadDelay: 重载延迟
返回值:
- *ScriptWatcher: 新的脚本监视器
- error: 创建监视器失败时返回错误
func WatchAndReload ¶
func WatchAndReload(ctx context.Context, filePath string, reloadCallback func(string)) (*ScriptWatcher, error)
WatchAndReload 监控文件并自动重载
这是一个便捷方法,创建监视器、添加文件并启动。
参数:
- ctx: 上下文
- filePath: 文件路径
- reloadCallback: 重载回调函数
返回值:
- *ScriptWatcher: 脚本监视器
- error: 创建或启动失败时返回错误
func (*ScriptWatcher) AddFile ¶
func (w *ScriptWatcher) AddFile(filePath string, callback func(string)) error
AddFile 添加要监控的文件
添加一个 Lua 脚本文件到监控列表,并指定重载回调函数。
参数:
- filePath: 文件路径
- callback: 重载回调函数,参数为文件路径
返回值:
- error: 添加失败时返回错误
func (*ScriptWatcher) RemoveFile ¶
func (w *ScriptWatcher) RemoveFile(filePath string)
RemoveFile 移除监控的文件
从监控列表中移除指定的文件。
参数:
- filePath: 文件路径
func (*ScriptWatcher) Start ¶
func (w *ScriptWatcher) Start() error
Start 启动脚本监视器
开始监控文件变化,当文件被修改时触发重载回调。
返回值:
- error: 启动失败时返回错误
func (*ScriptWatcher) WatchDirectory ¶
func (w *ScriptWatcher) WatchDirectory(dirPath string, callback func(string)) error
WatchDirectory 监控目录下的所有 Lua 文件
自动发现目录下的所有 .lua 文件并添加到监控列表。
参数:
- dirPath: 目录路径
- callback: 重载回调函数
返回值:
- error: 添加失败时返回错误
type SetOperationParser ¶
type SetOperationParser struct{}
SetOperationParser Set 操作解析器
func NewSetOperationParser ¶
func NewSetOperationParser() *SetOperationParser
NewSetOperationParser 创建 Set 操作解析器
func (*SetOperationParser) GetSupportedActions ¶
func (p *SetOperationParser) GetSupportedActions() []string
GetSupportedActions 获取支持的操作列表
type SlowQuery ¶
type SlowQuery struct {
Timestamp time.Time // 执行时间
Duration time.Duration // 执行耗时
Action string // 操作类型(insert/update/delete)
InputSize int // 输入数据大小
Error error // 错误信息(如果有)
ScriptName string // 脚本名称(可选)
}
SlowQuery 慢查询记录
记录执行时间超过阈值的脚本执行信息。
type SortedSetOperationParser ¶
type SortedSetOperationParser struct{}
SortedSetOperationParser Sorted Set 操作解析器
func NewSortedSetOperationParser ¶
func NewSortedSetOperationParser() *SortedSetOperationParser
NewSortedSetOperationParser 创建 Sorted Set 操作解析器
func (*SortedSetOperationParser) GetSupportedActions ¶
func (p *SortedSetOperationParser) GetSupportedActions() []string
GetSupportedActions 获取支持的操作列表
type StringOperationParser ¶
type StringOperationParser struct{}
StringOperationParser String 操作解析器
func NewStringOperationParser ¶
func NewStringOperationParser() *StringOperationParser
NewStringOperationParser 创建 String 操作解析器
func (*StringOperationParser) GetSupportedActions ¶
func (p *StringOperationParser) GetSupportedActions() []string
GetSupportedActions 获取支持的操作列表
type StructureCode ¶
type StructureCode string
StructureCode 结构码类型
const ( StructureString StructureCode = "1" // String 类型 StructureHash StructureCode = "2" // Hash 类型 StructureList StructureCode = "3" // List 类型 StructureSet StructureCode = "4" // Set 类型 StructureSortedSet StructureCode = "5" // Sorted Set 类型 )
func ParseRedisOperationKey ¶
func ParseRedisOperationKey(keyStr string) (action string, structureCode StructureCode, key string, err error)
ParseRedisOperationKey 解析 Redis 操作键名
键名格式:action_structure_key
参数:
- keyStr: Redis 操作键名
返回值:
- action: 操作类型
- structureCode: 结构码
- key: Redis 键
- error: 解析失败时的错误
type TypeConverter ¶
type TypeConverter interface {
// ToLuaValue 将 Go 值转换为 Lua 值
//
// 参数:
// - value: Go 值
//
// 返回值:
// - lua.LValue: Lua 值
ToLuaValue(value interface{}) lua.LValue
// ToLuaField 将 Go 值转换为 Lua 字段并设置到表
//
// 参数:
// - L: Lua 状态机
// - t: Lua 表
// - key: 字段名
// - value: Go 值
ToLuaField(L *lua.LState, t *lua.LTable, key string, value interface{})
}
TypeConverter 类型转换器接口
统一 Go 类型到 Lua 类型的转换逻辑。
type TypeConverterRegistry ¶
type TypeConverterRegistry struct {
// contains filtered or unexported fields
}
TypeConverterRegistry 类型转换注册表
使用注册表模式管理不同类型之间的转换器。
func NewTypeConverterRegistry ¶
func NewTypeConverterRegistry() *TypeConverterRegistry
NewTypeConverterRegistry 创建新的类型转换注册表
func (*TypeConverterRegistry) Convert ¶
func (r *TypeConverterRegistry) Convert(value interface{}, targetType reflect.Type) (interface{}, error)
Convert 执行类型转换
参数:
- value: 要转换的值
- targetType: 目标类型
返回值:
- interface{}: 转换后的值
- error: 转换失败时返回错误
func (*TypeConverterRegistry) Register ¶
func (r *TypeConverterRegistry) Register(fromType, toType reflect.Type, handler ConvertHandler)
Register 注册类型转换处理器
参数:
- fromType: 源类型
- toType: 目标类型
- handler: 转换处理器
Source Files
¶
- common_ops.go
- constants.go
- converter.go
- converter_registry.go
- db_ops.go
- dependency.go
- engine.go
- engine_panic.go
- errors.go
- es_ops.go
- http_helper.go
- http_logger.go
- http_metrics.go
- http_ops.go
- http_request_builder.go
- http_response_handler.go
- http_types.go
- interfaces.go
- metrics.go
- mongodb_ops.go
- mq_ops.go
- operation_parser.go
- redis_ops.go
- sandbox.go
- script_ops.go
- state_pool.go
- watcher.go