Documentation
¶
Overview ¶
Package plugin 提供统一的插件系统,支持多种插件类型
Package plugin 提供统一的插件系统 ¶
Package plugin 提供统一的插件系统 ¶
Package plugin 提供统一的插件系统 ¶
Package plugin 提供统一的插件系统,支持多种插件类型的动态加载和管理。
插件系统是 DSL Core 的核心功能之一,允许通过插件扩展 DSL 的功能, 无需修改核心代码。v1.2.0 引入了统一插件系统架构,通过适配器模式 支持四种插件类型。
主要特性:
- 插件生命周期管理(加载、启动、停止、卸载)
- 插件依赖管理和版本控制
- 插件隔离和错误恢复
- 与事件系统集成
- 函数注册和扩展
- 统一的插件适配器接口(v1.2.0 新增)
- 支持四种插件类型(v1.2.0 新增)
- 声明式插件配置(manifest.json)(v1.2.0 新增)
- 热加载和进程池优化(v1.2.0 新增)
支持的插件类型(v1.2.0):
- Go 原生插件:编译为 .so/.dll 的动态库,性能最优
- RPC 插件:独立进程通过 gRPC 通信,支持任意语言
- DSL 脚本插件:使用 DSL 语言编写,易于开发和调试
- 命令行插件:封装外部命令行工具,无需重写代码
基本用法(v1.1 兼容):
// 创建插件管理器
ctx := &plugin.PluginContext{
FunctionRegistry: funcRegistry,
EventBus: eventBus,
Config: config,
}
manager := plugin.NewPluginManager(ctx)
// 加载插件
httpPlugin := plugins.NewHTTPPlugin()
err := manager.Load(httpPlugin)
if err != nil {
log.Fatal(err)
}
// 使用插件注册的函数
result := engine.Execute("myRule", data)
使用统一插件系统(v1.2 新增):
// 解析插件清单
manifest, err := plugin.ParseManifest("plugins/my-plugin/manifest.json")
if err != nil {
log.Fatal(err)
}
// 创建适配器
adapter, err := plugin.CreateAdapter(manifest, ctx)
if err != nil {
log.Fatal(err)
}
// 调用插件函数
result, err := adapter.Execute("myFunc", []interface{}{"arg1", 123})
if err != nil {
log.Fatal(err)
}
// 获取运行指标
metrics := adapter.GetMetrics()
fmt.Printf("调用次数: %d, 错误率: %.2f%%\n",
metrics.CallCount, metrics.ErrorRate()*100)
创建自定义插件:
type MyPlugin struct {
status plugin.PluginStatus
}
func (p *MyPlugin) Name() string {
return "my-plugin"
}
func (p *MyPlugin) Version() string {
return "1.0.0"
}
func (p *MyPlugin) Initialize(ctx *plugin.PluginContext) error {
// 注册自定义函数
ctx.FunctionRegistry.Register("myFunc", myFunction)
// 监听事件
ctx.EventBus.On("system.ready", myListener)
p.status = plugin.StatusInitialized
return nil
}
func (p *MyPlugin) Start() error {
p.status = plugin.StatusStarted
return nil
}
func (p *MyPlugin) Stop() error {
p.status = plugin.StatusStopped
return nil
}
func (p *MyPlugin) Shutdown() error {
p.status = plugin.StatusUnloaded
return nil
}
Package plugin 提供统一的插件系统
Index ¶
- Constants
- Variables
- func GetAllPermissions() []string
- func IsLegacyPlugin(plugin Plugin) bool
- func IsPermissionDenied(err error) bool
- func IsPluginError(err error) bool
- func MigrateLegacyPlugin(plugin Plugin) (PluginAdapter, *Manifest)
- func ValidateManifest(manifest *Manifest) error
- func ValidatePermissions(perms []string) error
- type AsyncExecutor
- type AsyncExecutorConfig
- type AsyncFuture
- type AsyncResult
- type CacheConfig
- type CacheStats
- type CommandPluginAdapter
- func (a *CommandPluginAdapter) Execute(funcName string, args []interface{}) (interface{}, error)
- func (a *CommandPluginAdapter) GetAvailableProcesses() int
- func (a *CommandPluginAdapter) GetFunctions() map[string]*FunctionSignature
- func (a *CommandPluginAdapter) GetMetrics() *PluginMetrics
- func (a *CommandPluginAdapter) GetPoolSize() int
- func (a *CommandPluginAdapter) GetTimeout() time.Duration
- func (a *CommandPluginAdapter) Init(manifest *Manifest, ctx *PluginContext) error
- func (a *CommandPluginAdapter) SetTimeout(timeout time.Duration)
- func (a *CommandPluginAdapter) Stop() error
- type Dependency
- type DependencyGraph
- type Diagnostics
- func (d *Diagnostics) FormatStatus() string
- func (d *Diagnostics) GetGoRoutineCount() int
- func (d *Diagnostics) GetMemoryUsage() uint64
- func (d *Diagnostics) GetPluginStatus(name string) *PluginStatusDetail
- func (d *Diagnostics) GetSystemStatus() *SystemStatus
- func (d *Diagnostics) GetUptime() time.Duration
- func (d *Diagnostics) ListPlugins() []*PluginStatusDetail
- func (d *Diagnostics) RegisterDefaultHealthChecks()
- func (d *Diagnostics) RegisterHealthCheck(name string, check HealthCheckFunc)
- func (d *Diagnostics) RunAllHealthChecks() []*HealthCheckResult
- func (d *Diagnostics) RunHealthCheck(name string) *HealthCheckResult
- func (d *Diagnostics) SetDiscovery(discovery *PluginDiscovery)
- func (d *Diagnostics) SetHotReloader(reloader *HotReloader)
- func (d *Diagnostics) SetMetricsCollector(collector *MetricsCollector)
- func (d *Diagnostics) UnregisterHealthCheck(name string)
- type DiscoveredPlugin
- type DiscoveryCallback
- type DiscoveryEvent
- type DiscoveryEventType
- type DiscoveryStatus
- type ErrorHandler
- type ErrorIsolator
- func (e *ErrorIsolator) Disable()
- func (e *ErrorIsolator) Enable()
- func (e *ErrorIsolator) Execute(pluginName string, funcName string, fn func() (interface{}, error)) (result interface{}, err error)
- func (e *ErrorIsolator) IsEnabled() bool
- func (e *ErrorIsolator) OnError(handler ErrorHandler)
- func (e *ErrorIsolator) OnPanic(handler PanicHandler)
- func (e *ErrorIsolator) SetLogErrors(log bool)
- func (e *ErrorIsolator) SetLogger(logger Logger)
- func (e *ErrorIsolator) WrapError(pluginName, funcName string, err error) *PluginError
- type FunctionBus
- func (fb *FunctionBus) Call(funcName string, args []interface{}) (interface{}, error)
- func (fb *FunctionBus) Clear()
- func (fb *FunctionBus) Count() int
- func (fb *FunctionBus) GetAdapter(funcName string) (PluginAdapter, error)
- func (fb *FunctionBus) Has(funcName string) bool
- func (fb *FunctionBus) List() []string
- func (fb *FunctionBus) ListByNamespace(namespace string) []string
- func (fb *FunctionBus) Register(funcName string, adapter PluginAdapter) error
- func (fb *FunctionBus) Unregister(funcName string) error
- func (fb *FunctionBus) UnregisterAll(adapter PluginAdapter) int
- type FunctionCache
- func (c *FunctionCache) Cleanup() int
- func (c *FunctionCache) Clear()
- func (c *FunctionCache) Delete(key string)
- func (c *FunctionCache) Disable()
- func (c *FunctionCache) Enable()
- func (c *FunctionCache) Get(key string) (interface{}, bool)
- func (c *FunctionCache) IsEnabled() bool
- func (c *FunctionCache) Set(key string, value interface{})
- func (c *FunctionCache) Size() int
- func (c *FunctionCache) Stats() *CacheStats
- type FunctionDeclaration
- type FunctionMetricsData
- type FunctionSignature
- type GoPluginAdapter
- func (a *GoPluginAdapter) Execute(funcName string, args []interface{}) (interface{}, error)
- func (a *GoPluginAdapter) GetFunctions() map[string]*FunctionSignature
- func (a *GoPluginAdapter) GetMetrics() *PluginMetrics
- func (a *GoPluginAdapter) Init(manifest *Manifest, ctx *PluginContext) error
- func (a *GoPluginAdapter) Stop() error
- type HealthCheckFunc
- type HealthCheckResult
- type HealthStatus
- type HotReloadCallback
- type HotReloadEvent
- type HotReloadEventType
- type HotReloader
- func (h *HotReloader) AddDirectory(dir string) error
- func (h *HotReloader) Disable()
- func (h *HotReloader) Enable() error
- func (h *HotReloader) GetAdapter(path string) PluginAdapter
- func (h *HotReloader) GetAdapters() map[string]PluginAdapter
- func (h *HotReloader) IsEnabled() bool
- func (h *HotReloader) LoadAll() error
- func (h *HotReloader) OnLoad(fn func(manifestPath string) error)
- func (h *HotReloader) OnReload(callback HotReloadCallback)
- func (h *HotReloader) OnUnload(fn func(pluginID string) error)
- func (h *HotReloader) RemoveDirectory(dir string) error
- func (h *HotReloader) SetDiscovery(discovery *PluginDiscovery)
- func (h *HotReloader) SetReloadDelay(delay time.Duration)
- func (h *HotReloader) Start(dirs []string) error
- func (h *HotReloader) Stop()
- func (h *HotReloader) UnloadAll()
- type IsolatedAdapter
- func (a *IsolatedAdapter) Execute(funcName string, args []interface{}) (interface{}, error)
- func (a *IsolatedAdapter) GetAdapter() PluginAdapter
- func (a *IsolatedAdapter) GetFunctions() map[string]*FunctionSignature
- func (a *IsolatedAdapter) GetIsolator() *ErrorIsolator
- func (a *IsolatedAdapter) GetMetrics() *PluginMetrics
- func (a *IsolatedAdapter) Init(manifest *Manifest, ctx *PluginContext) error
- func (a *IsolatedAdapter) Stop() error
- type JSONLinesProtocol
- type JSONLinesRequest
- type JSONLinesResponse
- type LegacyPluginAdapter
- func (a *LegacyPluginAdapter) Execute(funcName string, args []interface{}) (interface{}, error)
- func (a *LegacyPluginAdapter) GetFunctions() map[string]*FunctionSignature
- func (a *LegacyPluginAdapter) GetMetrics() *PluginMetrics
- func (a *LegacyPluginAdapter) GetPlugin() Plugin
- func (a *LegacyPluginAdapter) Init(manifest *Manifest, ctx *PluginContext) error
- func (a *LegacyPluginAdapter) Stop() error
- type LimitedExecutor
- type Logger
- type ManagerConfig
- type Manifest
- type MetricsCollector
- func (c *MetricsCollector) Disable()
- func (c *MetricsCollector) Enable()
- func (c *MetricsCollector) GetAllFunctionMetrics() map[string]*FunctionMetricsData
- func (c *MetricsCollector) GetAllPluginMetrics() map[string]*PluginMetricsData
- func (c *MetricsCollector) GetFunctionMetrics(pluginName, funcName string) *FunctionMetricsData
- func (c *MetricsCollector) GetPluginFunctionMetrics(pluginName string) []*FunctionMetricsData
- func (c *MetricsCollector) GetPluginMetrics(name string) *PluginMetricsData
- func (c *MetricsCollector) GetUptime() time.Duration
- func (c *MetricsCollector) IsEnabled() bool
- func (c *MetricsCollector) RecordCall(pluginName, funcName string, duration time.Duration, err error)
- func (c *MetricsCollector) RegisterPlugin(name string, pluginType PluginType)
- func (c *MetricsCollector) Reset()
- func (c *MetricsCollector) Summary() string
- func (c *MetricsCollector) ToPrometheus() string
- func (c *MetricsCollector) UnregisterPlugin(name string)
- type PanicHandler
- type PermissionChecker
- func (pc *PermissionChecker) Check(perm string) error
- func (pc *PermissionChecker) CheckMultiple(perms ...string) error
- func (pc *PermissionChecker) Grant(perm string)
- func (pc *PermissionChecker) Has(perm string) bool
- func (pc *PermissionChecker) HasAll(perms ...string) bool
- func (pc *PermissionChecker) HasAny(perms ...string) bool
- func (pc *PermissionChecker) List() []string
- func (pc *PermissionChecker) Revoke(perm string)
- type PermissionDeniedError
- type Plugin
- type PluginAdapter
- type PluginBridge
- type PluginContext
- func (ctx *PluginContext) GetPluginName() string
- func (ctx *PluginContext) SetEventBus(bus event.EventBus)
- func (ctx *PluginContext) SetFunctionRegistry(registry function.Registry)
- func (ctx *PluginContext) SetLogger(logger Logger)
- func (ctx *PluginContext) SetPermissions(checker *PermissionChecker)
- func (ctx *PluginContext) SetPluginName(name string)
- type PluginDiscovery
- func (d *PluginDiscovery) AddDirectory(dir string) error
- func (d *PluginDiscovery) Clear()
- func (d *PluginDiscovery) GetDirectories() []string
- func (d *PluginDiscovery) GetPlugin(path string) *DiscoveredPlugin
- func (d *PluginDiscovery) GetPlugins() map[string]*DiscoveredPlugin
- func (d *PluginDiscovery) IsWatching() bool
- func (d *PluginDiscovery) OnDiscovery(callback DiscoveryCallback)
- func (d *PluginDiscovery) RemoveDirectory(dir string) error
- func (d *PluginDiscovery) Scan() ([]*DiscoveredPlugin, error)
- func (d *PluginDiscovery) SetScanInterval(interval time.Duration)
- func (d *PluginDiscovery) StopWatch()
- func (d *PluginDiscovery) Watch() error
- type PluginError
- type PluginManager
- func (pm *PluginManager) Call(funcName string, args []interface{}) (interface{}, error)
- func (pm *PluginManager) DisableHotReload()
- func (pm *PluginManager) EnableHotReload(dirs []string) error
- func (pm *PluginManager) GetAdapter(pluginID string) (PluginAdapter, error)
- func (pm *PluginManager) GetDiagnostics() *Diagnostics
- func (pm *PluginManager) GetFunctionBus() *FunctionBus
- func (pm *PluginManager) GetMetrics() *MetricsCollector
- func (pm *PluginManager) GetPlugin(pluginID string) (*Manifest, error)
- func (pm *PluginManager) HasFunction(funcName string) bool
- func (pm *PluginManager) ListFunctions() []string
- func (pm *PluginManager) ListPlugins() []*Manifest
- func (pm *PluginManager) LoadPlugin(manifestPath string) error
- func (pm *PluginManager) ReloadPlugin(pluginID string) error
- func (pm *PluginManager) Start() error
- func (pm *PluginManager) Stop() error
- func (pm *PluginManager) UnloadPlugin(pluginID string) error
- type PluginManagerInterface
- type PluginMetrics
- type PluginMetricsData
- type PluginStatus
- type PluginStatusDetail
- type PluginType
- type Process
- type ProcessPool
- type ProcessPoolConfig
- type RPCPluginAdapter
- func (a *RPCPluginAdapter) Execute(funcName string, args []interface{}) (interface{}, error)
- func (a *RPCPluginAdapter) GetFunctions() map[string]*FunctionSignature
- func (a *RPCPluginAdapter) GetMetrics() *PluginMetrics
- func (a *RPCPluginAdapter) GetTimeout() time.Duration
- func (a *RPCPluginAdapter) Init(manifest *Manifest, ctx *PluginContext) error
- func (a *RPCPluginAdapter) SetTimeout(timeout time.Duration)
- func (a *RPCPluginAdapter) Stop() error
- type ResourceLimiter
- func (r *ResourceLimiter) AcquireCall() error
- func (r *ResourceLimiter) CheckMemory(currentMemory int64) error
- func (r *ResourceLimiter) Disable()
- func (r *ResourceLimiter) Enable()
- func (r *ResourceLimiter) ExecuteWithTimeout(ctx context.Context, fn func() (interface{}, error)) (interface{}, error)
- func (r *ResourceLimiter) GetCallsInMinute() int
- func (r *ResourceLimiter) GetCurrentCalls() int
- func (r *ResourceLimiter) GetLimits() *ResourceLimits
- func (r *ResourceLimiter) IsEnabled() bool
- func (r *ResourceLimiter) ReleaseCall()
- func (r *ResourceLimiter) Reset()
- func (r *ResourceLimiter) SetLimits(limits *ResourceLimits)
- type ResourceLimits
- type ScriptPlugin
- func (p *ScriptPlugin) Dependencies() []Dependency
- func (p *ScriptPlugin) Description() string
- func (p *ScriptPlugin) GetFunctions() []string
- func (p *ScriptPlugin) GetScript() string
- func (p *ScriptPlugin) Initialize(ctx *PluginContext) error
- func (p *ScriptPlugin) Name() string
- func (p *ScriptPlugin) Shutdown() error
- func (p *ScriptPlugin) Start() error
- func (p *ScriptPlugin) Status() PluginStatus
- func (p *ScriptPlugin) Stop() error
- func (p *ScriptPlugin) Version() string
- type ScriptPluginAdapter
- func (a *ScriptPluginAdapter) Execute(funcName string, args []interface{}) (interface{}, error)
- func (a *ScriptPluginAdapter) GetFunctions() map[string]*FunctionSignature
- func (a *ScriptPluginAdapter) GetMetrics() *PluginMetrics
- func (a *ScriptPluginAdapter) GetScript() string
- func (a *ScriptPluginAdapter) GetScriptPath() string
- func (a *ScriptPluginAdapter) Init(manifest *Manifest, ctx *PluginContext) error
- func (a *ScriptPluginAdapter) IsModified() bool
- func (a *ScriptPluginAdapter) Reload() error
- func (a *ScriptPluginAdapter) Stop() error
- type ScriptPluginConfig
- type SystemStatus
Constants ¶
const ( // PermFileRead 文件读取权限 PermFileRead = "file.read" // PermFileWrite 文件写入权限 PermFileWrite = "file.write" // PermNetFetch 网络访问权限 PermNetFetch = "net.fetch" // PermExecCommand 执行命令权限 PermExecCommand = "exec.command" // PermEventEmit 触发事件权限 PermEventEmit = "event.emit" // PermEventListen 监听事件权限 PermEventListen = "event.listen" // PermFunctionCall 调用其他函数权限 PermFunctionCall = "function.call" // PermConfigRead 读取配置权限 PermConfigRead = "config.read" // PermConfigWrite 写入配置权限 PermConfigWrite = "config.write" )
权限常量定义
Variables ¶
var ( ErrExecutorNotRunning = &asyncError{"executor not running"} ErrQueueFull = &asyncError{"task queue full"} ErrTimeout = &asyncError{"operation timeout"} )
错误定义
Functions ¶
func MigrateLegacyPlugin ¶
func MigrateLegacyPlugin(plugin Plugin) (PluginAdapter, *Manifest)
MigrateLegacyPlugin 迁移 v1.1 插件到 v1.2 返回适配器和生成的 manifest
func ValidatePermissions ¶
ValidatePermissions 验证权限列表是否有效 检查是否包含未知的权限
Types ¶
type AsyncExecutor ¶
type AsyncExecutor struct {
// contains filtered or unexported fields
}
AsyncExecutor 异步执行器 支持异步调用插件函数
func NewAsyncExecutor ¶
func NewAsyncExecutor(bus *FunctionBus, limiter *ResourceLimiter, config *AsyncExecutorConfig) *AsyncExecutor
NewAsyncExecutor 创建异步执行器
func (*AsyncExecutor) CallAsync ¶
func (e *AsyncExecutor) CallAsync(funcName string, args []interface{}) *AsyncFuture
CallAsync 异步调用函数
func (*AsyncExecutor) CallAsyncWithContext ¶
func (e *AsyncExecutor) CallAsyncWithContext(ctx context.Context, funcName string, args []interface{}) *AsyncFuture
CallAsyncWithContext 带上下文的异步调用
type AsyncExecutorConfig ¶
type AsyncExecutorConfig struct {
// WorkerCount 工作协程数量
WorkerCount int
// QueueSize 任务队列大小
QueueSize int
}
AsyncExecutorConfig 异步执行器配置
func DefaultAsyncExecutorConfig ¶
func DefaultAsyncExecutorConfig() *AsyncExecutorConfig
DefaultAsyncExecutorConfig 默认异步执行器配置
type AsyncFuture ¶
type AsyncFuture struct {
// contains filtered or unexported fields
}
AsyncFuture 异步 Future 用于获取异步调用的结果
func (*AsyncFuture) GetWithTimeout ¶
func (f *AsyncFuture) GetWithTimeout(timeout time.Duration) *AsyncResult
GetWithTimeout 带超时获取结果
type AsyncResult ¶
type AsyncResult struct {
// Value 返回值
Value interface{}
// Error 错误
Error error
// Duration 执行时间
Duration time.Duration
}
AsyncResult 异步结果
type CacheConfig ¶
type CacheConfig struct {
// MaxSize 最大缓存条目数
MaxSize int
// TTL 缓存过期时间
TTL time.Duration
// Enabled 是否启用
Enabled bool
}
CacheConfig 缓存配置
type CacheStats ¶
type CacheStats struct {
// Size 当前大小
Size int
// MaxSize 最大大小
MaxSize int
// Hits 命中次数
Hits int64
// Misses 未命中次数
Misses int64
// HitRate 命中率
HitRate float64
// Enabled 是否启用
Enabled bool
}
CacheStats 缓存统计
type CommandPluginAdapter ¶
type CommandPluginAdapter struct {
// contains filtered or unexported fields
}
CommandPluginAdapter 命令行插件适配器 封装外部命令行工具,通过 stdin/stdout 进行 JSON Lines 通信
func NewCommandPluginAdapter ¶
func NewCommandPluginAdapter() *CommandPluginAdapter
NewCommandPluginAdapter 创建命令行插件适配器
func (*CommandPluginAdapter) Execute ¶
func (a *CommandPluginAdapter) Execute(funcName string, args []interface{}) (interface{}, error)
Execute 执行函数调用
func (*CommandPluginAdapter) GetAvailableProcesses ¶
func (a *CommandPluginAdapter) GetAvailableProcesses() int
GetAvailableProcesses 获取可用进程数
func (*CommandPluginAdapter) GetFunctions ¶
func (a *CommandPluginAdapter) GetFunctions() map[string]*FunctionSignature
GetFunctions 获取函数签名
func (*CommandPluginAdapter) GetMetrics ¶
func (a *CommandPluginAdapter) GetMetrics() *PluginMetrics
GetMetrics 获取运行指标
func (*CommandPluginAdapter) GetPoolSize ¶
func (a *CommandPluginAdapter) GetPoolSize() int
GetPoolSize 获取进程池大小
func (*CommandPluginAdapter) GetTimeout ¶
func (a *CommandPluginAdapter) GetTimeout() time.Duration
GetTimeout 获取默认超时时间
func (*CommandPluginAdapter) Init ¶
func (a *CommandPluginAdapter) Init(manifest *Manifest, ctx *PluginContext) error
Init 初始化适配器
func (*CommandPluginAdapter) SetTimeout ¶
func (a *CommandPluginAdapter) SetTimeout(timeout time.Duration)
SetTimeout 设置默认超时时间
type Dependency ¶
type Dependency struct {
// Name 依赖的插件名称
Name string
// Version 版本要求
// 支持的格式:
// - "1.0.0" - 精确版本
// - ">=1.0.0" - 大于等于
// - ">1.0.0" - 大于
// - "<=1.0.0" - 小于等于
// - "<1.0.0" - 小于
// - "^1.0.0" - 兼容版本(主版本相同)
// - "~1.0.0" - 近似版本(主版本和次版本相同)
Version string
// Optional 是否为可选依赖
Optional bool
}
Dependency 插件依赖
type DependencyGraph ¶
type DependencyGraph struct {
// contains filtered or unexported fields
}
DependencyGraph 依赖图
func (*DependencyGraph) GetDependents ¶
func (g *DependencyGraph) GetDependents(pluginName string) []string
GetDependents 获取依赖指定插件的所有插件
func (*DependencyGraph) GetLoadOrder ¶
func (g *DependencyGraph) GetLoadOrder() []string
GetLoadOrder 获取插件加载顺序(拓扑排序)
func (*DependencyGraph) Remove ¶
func (g *DependencyGraph) Remove(pluginName string)
Remove 从依赖图移除插件
type Diagnostics ¶
type Diagnostics struct {
// contains filtered or unexported fields
}
Diagnostics 诊断工具 提供插件系统的健康检查和状态查询
func (*Diagnostics) GetGoRoutineCount ¶
func (d *Diagnostics) GetGoRoutineCount() int
GetGoRoutineCount 获取 Goroutine 数量
func (*Diagnostics) GetMemoryUsage ¶
func (d *Diagnostics) GetMemoryUsage() uint64
GetMemoryUsage 获取内存使用
func (*Diagnostics) GetPluginStatus ¶
func (d *Diagnostics) GetPluginStatus(name string) *PluginStatusDetail
GetPluginStatus 获取插件状态
func (*Diagnostics) GetSystemStatus ¶
func (d *Diagnostics) GetSystemStatus() *SystemStatus
GetSystemStatus 获取系统状态
func (*Diagnostics) ListPlugins ¶
func (d *Diagnostics) ListPlugins() []*PluginStatusDetail
ListPlugins 列出所有插件
func (*Diagnostics) RegisterDefaultHealthChecks ¶
func (d *Diagnostics) RegisterDefaultHealthChecks()
DefaultHealthChecks 注册默认健康检查
func (*Diagnostics) RegisterHealthCheck ¶
func (d *Diagnostics) RegisterHealthCheck(name string, check HealthCheckFunc)
RegisterHealthCheck 注册健康检查
func (*Diagnostics) RunAllHealthChecks ¶
func (d *Diagnostics) RunAllHealthChecks() []*HealthCheckResult
RunAllHealthChecks 运行所有健康检查
func (*Diagnostics) RunHealthCheck ¶
func (d *Diagnostics) RunHealthCheck(name string) *HealthCheckResult
RunHealthCheck 运行指定的健康检查
func (*Diagnostics) SetDiscovery ¶
func (d *Diagnostics) SetDiscovery(discovery *PluginDiscovery)
SetDiscovery 设置插件发现器
func (*Diagnostics) SetHotReloader ¶
func (d *Diagnostics) SetHotReloader(reloader *HotReloader)
SetHotReloader 设置热加载器
func (*Diagnostics) SetMetricsCollector ¶
func (d *Diagnostics) SetMetricsCollector(collector *MetricsCollector)
SetMetricsCollector 设置指标收集器
func (*Diagnostics) UnregisterHealthCheck ¶
func (d *Diagnostics) UnregisterHealthCheck(name string)
UnregisterHealthCheck 注销健康检查
type DiscoveredPlugin ¶
type DiscoveredPlugin struct {
// Path 插件目录路径
Path string
// ManifestPath manifest.json 路径
ManifestPath string
// Manifest 解析后的清单
Manifest *Manifest
// LastModified 最后修改时间
LastModified time.Time
// Status 插件发现状态
Status DiscoveryStatus
}
DiscoveredPlugin 发现的插件信息
type DiscoveryCallback ¶
type DiscoveryCallback func(event *DiscoveryEvent)
DiscoveryCallback 发现回调函数
type DiscoveryEvent ¶
type DiscoveryEvent struct {
// Type 事件类型
Type DiscoveryEventType
// Plugin 相关插件
Plugin *DiscoveredPlugin
// Error 错误信息(如果有)
Error error
}
DiscoveryEvent 发现事件
type DiscoveryEventType ¶
type DiscoveryEventType string
DiscoveryEventType 发现事件类型
const ( // EventPluginAdded 插件添加 EventPluginAdded DiscoveryEventType = "added" // EventPluginUpdated 插件更新 EventPluginUpdated DiscoveryEventType = "updated" // EventPluginRemoved 插件移除 EventPluginRemoved DiscoveryEventType = "removed" // EventPluginError 插件错误 EventPluginError DiscoveryEventType = "error" )
type DiscoveryStatus ¶
type DiscoveryStatus string
DiscoveryStatus 插件发现状态
const ( // DiscoveryStatusDiscovered 已发现 DiscoveryStatusDiscovered DiscoveryStatus = "discovered" // DiscoveryStatusLoaded 已加载 DiscoveryStatusLoaded DiscoveryStatus = "loaded" // DiscoveryStatusError 错误 DiscoveryStatusError DiscoveryStatus = "error" // DiscoveryStatusRemoved 已移除 DiscoveryStatusRemoved DiscoveryStatus = "removed" )
type ErrorHandler ¶
ErrorHandler 错误处理器
type ErrorIsolator ¶
type ErrorIsolator struct {
// contains filtered or unexported fields
}
ErrorIsolator 错误隔离器 确保插件错误不会影响其他插件或主程序
func (*ErrorIsolator) Execute ¶
func (e *ErrorIsolator) Execute( pluginName string, funcName string, fn func() (interface{}, error), ) (result interface{}, err error)
Execute 安全执行函数(带 panic 恢复)
func (*ErrorIsolator) OnError ¶
func (e *ErrorIsolator) OnError(handler ErrorHandler)
OnError 注册错误处理器
func (*ErrorIsolator) OnPanic ¶
func (e *ErrorIsolator) OnPanic(handler PanicHandler)
OnPanic 注册 panic 处理器
func (*ErrorIsolator) SetLogErrors ¶
func (e *ErrorIsolator) SetLogErrors(log bool)
SetLogErrors 设置是否记录错误
func (*ErrorIsolator) SetLogger ¶
func (e *ErrorIsolator) SetLogger(logger Logger)
SetLogger 设置日志记录器
func (*ErrorIsolator) WrapError ¶
func (e *ErrorIsolator) WrapError(pluginName, funcName string, err error) *PluginError
WrapError 包装错误
type FunctionBus ¶
type FunctionBus struct {
// contains filtered or unexported fields
}
FunctionBus 函数总线 负责路由函数调用到对应的插件适配器 支持命名空间隔离和并发安全
func (*FunctionBus) Call ¶
func (fb *FunctionBus) Call(funcName string, args []interface{}) (interface{}, error)
Call 调用函数 funcName: 要调用的函数名 args: 函数参数 返回函数执行结果和可能的错误
func (*FunctionBus) GetAdapter ¶
func (fb *FunctionBus) GetAdapter(funcName string) (PluginAdapter, error)
GetAdapter 获取函数对应的适配器
func (*FunctionBus) ListByNamespace ¶
func (fb *FunctionBus) ListByNamespace(namespace string) []string
ListByNamespace 列出指定命名空间的所有函数
func (*FunctionBus) Register ¶
func (fb *FunctionBus) Register(funcName string, adapter PluginAdapter) error
Register 注册函数到总线 funcName: 函数名,可以包含命名空间(如 "http.get") adapter: 提供该函数的插件适配器
func (*FunctionBus) Unregister ¶
func (fb *FunctionBus) Unregister(funcName string) error
Unregister 注销函数
func (*FunctionBus) UnregisterAll ¶
func (fb *FunctionBus) UnregisterAll(adapter PluginAdapter) int
UnregisterAll 注销适配器的所有函数
type FunctionCache ¶
type FunctionCache struct {
// contains filtered or unexported fields
}
FunctionCache 函数缓存 缓存函数调用结果,减少重复计算
func NewFunctionCache ¶
func NewFunctionCache(config *CacheConfig) *FunctionCache
NewFunctionCache 创建函数缓存
type FunctionDeclaration ¶
type FunctionDeclaration struct {
// Name 函数名称
Name string `json:"name"`
// Signature 函数签名
// 格式: func(param1: type1, param2: type2): returnType
// 例如: func(path: string, width: int, height: int): string
Signature string `json:"signature"`
// Description 函数描述
Description string `json:"description"`
}
FunctionDeclaration 函数声明 描述插件提供的函数签名
type FunctionMetricsData ¶
type FunctionMetricsData struct {
// FunctionName 函数名称
FunctionName string
// PluginName 所属插件名称
PluginName string
// TotalCalls 总调用次数
TotalCalls int64
// SuccessCalls 成功调用次数
SuccessCalls int64
// ErrorCalls 错误调用次数
ErrorCalls int64
// TotalDuration 总耗时
TotalDuration time.Duration
// MinDuration 最小耗时
MinDuration time.Duration
// MaxDuration 最大耗时
MaxDuration time.Duration
// LastCallTime 最后调用时间
LastCallTime time.Time
// LastError 最后错误
LastError string
}
FunctionMetricsData 函数指标数据
func (*FunctionMetricsData) AverageDuration ¶
func (d *FunctionMetricsData) AverageDuration() time.Duration
AverageDuration 计算平均耗时
func (*FunctionMetricsData) ErrorRate ¶
func (d *FunctionMetricsData) ErrorRate() float64
ErrorRate 计算错误率
type FunctionSignature ¶
type FunctionSignature struct {
// Name 函数名称
Name string
// ParamTypes 参数类型列表
// 例如: ["string", "int", "float64"]
ParamTypes []string
// ReturnType 返回值类型
// 例如: "string", "int", "map[string]interface{}"
ReturnType string
// Variadic 是否为可变参数函数
Variadic bool
// Description 函数描述
Description string
}
FunctionSignature 函数签名 描述函数的参数类型和返回类型
type GoPluginAdapter ¶
type GoPluginAdapter struct {
// contains filtered or unexported fields
}
GoPluginAdapter Go 原生插件适配器 使用 Go 的 plugin 包加载 .so 动态库 注意:Go plugin 包仅在 Linux 和 macOS 上支持
func (*GoPluginAdapter) Execute ¶
func (a *GoPluginAdapter) Execute(funcName string, args []interface{}) (interface{}, error)
Execute 执行函数调用
func (*GoPluginAdapter) GetFunctions ¶
func (a *GoPluginAdapter) GetFunctions() map[string]*FunctionSignature
GetFunctions 获取插件提供的函数签名
func (*GoPluginAdapter) GetMetrics ¶
func (a *GoPluginAdapter) GetMetrics() *PluginMetrics
GetMetrics 获取运行指标
func (*GoPluginAdapter) Init ¶
func (a *GoPluginAdapter) Init(manifest *Manifest, ctx *PluginContext) error
Init 初始化适配器
type HealthCheckResult ¶
type HealthCheckResult struct {
// Name 检查名称
Name string
// Status 状态
Status HealthStatus
// Message 消息
Message string
// Duration 检查耗时
Duration time.Duration
// Details 详细信息
Details map[string]interface{}
}
HealthCheckResult 健康检查结果
type HealthStatus ¶
type HealthStatus string
HealthStatus 健康状态
const ( // HealthStatusHealthy 健康 HealthStatusHealthy HealthStatus = "healthy" // HealthStatusDegraded 降级 HealthStatusDegraded HealthStatus = "degraded" // HealthStatusUnhealthy 不健康 HealthStatusUnhealthy HealthStatus = "unhealthy" )
type HotReloadCallback ¶
type HotReloadCallback func(event *HotReloadEvent)
HotReloadCallback 热加载回调函数
type HotReloadEvent ¶
type HotReloadEvent struct {
// Type 事件类型
Type HotReloadEventType
// PluginPath 插件路径
PluginPath string
// Manifest 插件清单
Manifest *Manifest
// OldAdapter 旧适配器(如果是更新)
OldAdapter PluginAdapter
// NewAdapter 新适配器
NewAdapter PluginAdapter
// Error 错误信息(如果有)
Error error
}
HotReloadEvent 热加载事件
type HotReloadEventType ¶
type HotReloadEventType string
HotReloadEventType 热加载事件类型
const ( // HotReloadEventLoaded 插件加载 HotReloadEventLoaded HotReloadEventType = "loaded" // HotReloadEventReloaded 插件重新加载 HotReloadEventReloaded HotReloadEventType = "reloaded" // HotReloadEventUnloaded 插件卸载 HotReloadEventUnloaded HotReloadEventType = "unloaded" // HotReloadEventError 加载错误 HotReloadEventError HotReloadEventType = "error" )
type HotReloader ¶
type HotReloader struct {
// contains filtered or unexported fields
}
HotReloader 热加载器 负责监听插件变更并自动重新加载
func NewHotReloader ¶
func NewHotReloader(discovery *PluginDiscovery) *HotReloader
NewHotReloader 创建热加载器
func (*HotReloader) AddDirectory ¶
func (h *HotReloader) AddDirectory(dir string) error
AddDirectory 添加监听目录
func (*HotReloader) GetAdapter ¶
func (h *HotReloader) GetAdapter(path string) PluginAdapter
GetAdapter 获取适配器
func (*HotReloader) GetAdapters ¶
func (h *HotReloader) GetAdapters() map[string]PluginAdapter
GetAdapters 获取所有适配器
func (*HotReloader) OnLoad ¶
func (h *HotReloader) OnLoad(fn func(manifestPath string) error)
OnLoad 设置加载回调
func (*HotReloader) OnReload ¶
func (h *HotReloader) OnReload(callback HotReloadCallback)
OnReload 注册热加载回调
func (*HotReloader) OnUnload ¶
func (h *HotReloader) OnUnload(fn func(pluginID string) error)
OnUnload 设置卸载回调
func (*HotReloader) RemoveDirectory ¶
func (h *HotReloader) RemoveDirectory(dir string) error
RemoveDirectory 移除监听目录
func (*HotReloader) SetDiscovery ¶
func (h *HotReloader) SetDiscovery(discovery *PluginDiscovery)
SetDiscovery 设置插件发现器
func (*HotReloader) SetReloadDelay ¶
func (h *HotReloader) SetReloadDelay(delay time.Duration)
SetReloadDelay 设置重新加载延迟
type IsolatedAdapter ¶
type IsolatedAdapter struct {
// contains filtered or unexported fields
}
IsolatedAdapter 带错误隔离的适配器包装
func NewIsolatedAdapter ¶
func NewIsolatedAdapter(adapter PluginAdapter, pluginName string, isolator *ErrorIsolator) *IsolatedAdapter
NewIsolatedAdapter 创建带错误隔离的适配器
func (*IsolatedAdapter) Execute ¶
func (a *IsolatedAdapter) Execute(funcName string, args []interface{}) (interface{}, error)
Execute 执行函数调用
func (*IsolatedAdapter) GetAdapter ¶
func (a *IsolatedAdapter) GetAdapter() PluginAdapter
GetAdapter 获取原始适配器
func (*IsolatedAdapter) GetFunctions ¶
func (a *IsolatedAdapter) GetFunctions() map[string]*FunctionSignature
GetFunctions 获取函数签名
func (*IsolatedAdapter) GetIsolator ¶
func (a *IsolatedAdapter) GetIsolator() *ErrorIsolator
GetIsolator 获取错误隔离器
func (*IsolatedAdapter) GetMetrics ¶
func (a *IsolatedAdapter) GetMetrics() *PluginMetrics
GetMetrics 获取运行指标
func (*IsolatedAdapter) Init ¶
func (a *IsolatedAdapter) Init(manifest *Manifest, ctx *PluginContext) error
Init 初始化适配器
type JSONLinesProtocol ¶
type JSONLinesProtocol struct {
// contains filtered or unexported fields
}
JSONLinesProtocol JSON Lines 通信协议 用于与命令行插件通过标准输入输出进行通信
func NewJSONLinesProtocol ¶
func NewJSONLinesProtocol(stdin io.Writer, stdout io.Reader) *JSONLinesProtocol
NewJSONLinesProtocol 创建 JSON Lines 协议
func (*JSONLinesProtocol) Call ¶
func (p *JSONLinesProtocol) Call(ctx context.Context, function string, args []interface{}) (interface{}, error)
Call 调用函数
func (*JSONLinesProtocol) CallWithTimeout ¶
func (p *JSONLinesProtocol) CallWithTimeout(function string, args []interface{}, timeout time.Duration) (interface{}, error)
CallWithTimeout 调用函数(带超时)
type JSONLinesRequest ¶
type JSONLinesRequest struct {
// ID 请求 ID,用于匹配响应
ID int64 `json:"id"`
// Function 函数名
Function string `json:"function"`
// Args 参数列表
Args []interface{} `json:"args"`
}
JSONLinesRequest JSON Lines 请求
type JSONLinesResponse ¶
type JSONLinesResponse struct {
// ID 请求 ID
ID int64 `json:"id"`
// Result 结果(成功时)
Result interface{} `json:"result,omitempty"`
// Error 错误信息(失败时)
Error string `json:"error,omitempty"`
}
JSONLinesResponse JSON Lines 响应
type LegacyPluginAdapter ¶
type LegacyPluginAdapter struct {
// contains filtered or unexported fields
}
LegacyPluginAdapter v1.1 插件适配器 将 v1.1.0 的 Plugin 接口包装为 v1.2.0 的 PluginAdapter 接口 确保完全向后兼容
func NewLegacyPluginAdapter ¶
func NewLegacyPluginAdapter(plugin Plugin) *LegacyPluginAdapter
NewLegacyPluginAdapter 创建 v1.1 插件适配器
func (*LegacyPluginAdapter) Execute ¶
func (a *LegacyPluginAdapter) Execute(funcName string, args []interface{}) (interface{}, error)
Execute 执行函数调用 对于 v1.1 插件,函数已经注册到 FunctionRegistry 这里通过 FunctionRegistry 调用
func (*LegacyPluginAdapter) GetFunctions ¶
func (a *LegacyPluginAdapter) GetFunctions() map[string]*FunctionSignature
GetFunctions 获取插件提供的函数签名 注意:v1.1 插件没有显式声明函数签名,这里返回空映射 实际的函数已经通过 Initialize 方法注册到 FunctionRegistry
func (*LegacyPluginAdapter) GetMetrics ¶
func (a *LegacyPluginAdapter) GetMetrics() *PluginMetrics
GetMetrics 获取运行指标
func (*LegacyPluginAdapter) GetPlugin ¶
func (a *LegacyPluginAdapter) GetPlugin() Plugin
GetPlugin 获取底层的 v1.1 插件实例
func (*LegacyPluginAdapter) Init ¶
func (a *LegacyPluginAdapter) Init(manifest *Manifest, ctx *PluginContext) error
Init 初始化适配器
type LimitedExecutor ¶
type LimitedExecutor struct {
// contains filtered or unexported fields
}
LimitedExecutor 带资源限制的执行器
func NewLimitedExecutor ¶
func NewLimitedExecutor(adapter PluginAdapter, limiter *ResourceLimiter) *LimitedExecutor
NewLimitedExecutor 创建带资源限制的执行器
func (*LimitedExecutor) Execute ¶
func (e *LimitedExecutor) Execute(ctx context.Context, funcName string, args []interface{}) (interface{}, error)
Execute 执行函数调用(带资源限制)
func (*LimitedExecutor) GetAdapter ¶
func (e *LimitedExecutor) GetAdapter() PluginAdapter
GetAdapter 获取适配器
func (*LimitedExecutor) GetLimiter ¶
func (e *LimitedExecutor) GetLimiter() *ResourceLimiter
GetLimiter 获取资源限制器
type Logger ¶
type Logger interface {
// Debug 调试日志
Debug(msg string, args ...interface{})
// Info 信息日志
Info(msg string, args ...interface{})
// Warn 警告日志
Warn(msg string, args ...interface{})
// Error 错误日志
Error(msg string, args ...interface{})
}
Logger 日志记录器接口
type ManagerConfig ¶
type ManagerConfig struct {
// PluginDirs 插件目录列表
PluginDirs []string
// EnableHotReload 是否启用热加载
EnableHotReload bool
// EnableMetrics 是否启用指标收集
EnableMetrics bool
// EnableDiagnostics 是否启用诊断
EnableDiagnostics bool
// ResourceLimits 资源限制配置
ResourceLimits *ResourceLimits
// Logger 日志记录器
Logger Logger
}
ManagerConfig 管理器配置
type Manifest ¶
type Manifest struct {
// ID 插件唯一标识符
// 格式建议: com.company.plugin-name
ID string `json:"id"`
// Name 插件名称
Name string `json:"name"`
// Version 插件版本
// 格式: 语义化版本 (例如: 1.0.0)
Version string `json:"version"`
// Type 插件类型
// 可选值: go, rpc, script, command
Type PluginType `json:"type"`
// Namespace 插件命名空间
// 用于函数名前缀,例如 "http" 会使函数变成 "http.get"
Namespace string `json:"namespace,omitempty"`
// Language 插件实现语言(可选)
// 对 RPC 和 Command 插件有用
// 例如: python, nodejs, java
Language string `json:"language,omitempty"`
// Entry 插件入口点
// - Go 插件: .so/.dll 文件路径
// - RPC 插件: 可执行文件路径或服务地址
// - Script 插件: .dsl 脚本文件路径
// - Command 插件: 可执行文件路径
Entry string `json:"entry"`
// Functions 插件提供的函数列表
Functions []FunctionDeclaration `json:"functions"`
// Permissions 插件所需权限列表
// 例如: ["file.read", "file.write", "net.fetch"]
Permissions []string `json:"permissions"`
// Dependencies 插件依赖列表(可选)
Dependencies []Dependency `json:"dependencies,omitempty"`
// Config 插件配置(可选)
// 插件特定的配置参数
Config map[string]interface{} `json:"config,omitempty"`
// Description 插件描述(可选)
Description string `json:"description,omitempty"`
// Author 插件作者(可选)
Author string `json:"author,omitempty"`
// Homepage 插件主页(可选)
Homepage string `json:"homepage,omitempty"`
// contains filtered or unexported fields
}
Manifest 插件清单 描述插件的元数据、功能和配置
func CreateManifestFromPlugin ¶
CreateManifestFromPlugin 从 v1.1 插件创建 Manifest 用于将 v1.1 插件的元数据转换为 v1.2 的 Manifest 格式
func (*Manifest) GetFunction ¶
func (m *Manifest) GetFunction(name string) *FunctionDeclaration
GetFunction 根据名称获取函数声明
func (*Manifest) HasPermission ¶
HasPermission 检查是否有指定权限
type MetricsCollector ¶
type MetricsCollector struct {
// contains filtered or unexported fields
}
MetricsCollector 指标收集器 收集插件运行时的各种指标
func (*MetricsCollector) GetAllFunctionMetrics ¶
func (c *MetricsCollector) GetAllFunctionMetrics() map[string]*FunctionMetricsData
GetAllFunctionMetrics 获取所有函数指标
func (*MetricsCollector) GetAllPluginMetrics ¶
func (c *MetricsCollector) GetAllPluginMetrics() map[string]*PluginMetricsData
GetAllPluginMetrics 获取所有插件指标
func (*MetricsCollector) GetFunctionMetrics ¶
func (c *MetricsCollector) GetFunctionMetrics(pluginName, funcName string) *FunctionMetricsData
GetFunctionMetrics 获取函数指标
func (*MetricsCollector) GetPluginFunctionMetrics ¶
func (c *MetricsCollector) GetPluginFunctionMetrics(pluginName string) []*FunctionMetricsData
GetPluginFunctionMetrics 获取插件的所有函数指标
func (*MetricsCollector) GetPluginMetrics ¶
func (c *MetricsCollector) GetPluginMetrics(name string) *PluginMetricsData
GetPluginMetrics 获取插件指标
func (*MetricsCollector) GetUptime ¶
func (c *MetricsCollector) GetUptime() time.Duration
GetUptime 获取运行时间
func (*MetricsCollector) RecordCall ¶
func (c *MetricsCollector) RecordCall(pluginName, funcName string, duration time.Duration, err error)
RecordCall 记录函数调用
func (*MetricsCollector) RegisterPlugin ¶
func (c *MetricsCollector) RegisterPlugin(name string, pluginType PluginType)
RegisterPlugin 注册插件
func (*MetricsCollector) ToPrometheus ¶
func (c *MetricsCollector) ToPrometheus() string
ToPrometheus 导出为 Prometheus 格式
func (*MetricsCollector) UnregisterPlugin ¶
func (c *MetricsCollector) UnregisterPlugin(name string)
UnregisterPlugin 注销插件
type PanicHandler ¶
PanicHandler panic 处理器
type PermissionChecker ¶
type PermissionChecker struct {
// contains filtered or unexported fields
}
PermissionChecker 权限检查器 用于控制插件对系统资源的访问
func NewPermissionChecker ¶
func NewPermissionChecker(permissions []string) *PermissionChecker
NewPermissionChecker 创建权限检查器
func (*PermissionChecker) Check ¶
func (pc *PermissionChecker) Check(perm string) error
Check 检查是否有指定权限 如果没有权限,返回错误
func (*PermissionChecker) CheckMultiple ¶
func (pc *PermissionChecker) CheckMultiple(perms ...string) error
CheckMultiple 检查多个权限 如果任何一个权限缺失,返回错误
func (*PermissionChecker) Has ¶
func (pc *PermissionChecker) Has(perm string) bool
Has 检查是否有指定权限 返回 true 或 false,不返回错误
func (*PermissionChecker) HasAll ¶
func (pc *PermissionChecker) HasAll(perms ...string) bool
HasAll 检查是否有所有权限
func (*PermissionChecker) HasAny ¶
func (pc *PermissionChecker) HasAny(perms ...string) bool
HasAny 检查是否有任意一个权限
type PermissionDeniedError ¶
type PermissionDeniedError struct {
Permission string
}
PermissionDeniedError 权限拒绝错误
func (*PermissionDeniedError) Error ¶
func (e *PermissionDeniedError) Error() string
Error 实现 error 接口
type Plugin ¶
type Plugin interface {
// Name 获取插件名称
Name() string
// Version 获取插件版本
Version() string
// Description 获取插件描述
Description() string
// Dependencies 获取插件依赖
Dependencies() []Dependency
// Initialize 初始化插件
// 在此方法中注册函数、监听事件等
Initialize(ctx *PluginContext) error
// Start 启动插件
// 插件初始化完成后调用
Start() error
// Stop 停止插件
// 准备卸载插件时调用
Stop() error
// Shutdown 卸载插件
// 清理所有资源
Shutdown() error
// Status 获取插件状态
Status() PluginStatus
}
Plugin 插件接口
type PluginAdapter ¶
type PluginAdapter interface {
// Init 初始化适配器
// manifest: 插件清单,包含插件元数据
// ctx: 插件上下文,提供系统资源访问
Init(manifest *Manifest, ctx *PluginContext) error
// GetFunctions 获取插件提供的函数签名
// 返回函数名到函数签名的映射
GetFunctions() map[string]*FunctionSignature
// Execute 执行函数调用
// funcName: 要调用的函数名
// args: 函数参数列表
// 返回函数执行结果和可能的错误
Execute(funcName string, args []interface{}) (interface{}, error)
// Stop 停止适配器
// 清理所有资源,关闭连接,终止进程等
Stop() error
// GetMetrics 获取运行指标
// 返回插件的性能和运行统计信息
GetMetrics() *PluginMetrics
}
PluginAdapter 插件适配器接口 所有类型的插件(Go、RPC、Script、Command)都通过适配器实现统一接口 这是 v1.2.0 引入的核心抽象,用于统一不同插件类型的调用方式
func WrapLegacyPlugin ¶
func WrapLegacyPlugin(plugin Plugin) PluginAdapter
WrapLegacyPlugin 包装 v1.1 插件为 v1.2 适配器 这是一个便捷函数,用于快速包装现有插件
type PluginBridge ¶
type PluginBridge struct {
// contains filtered or unexported fields
}
PluginBridge 插件桥接器 将插件函数桥接到 DSL 函数注册表
func NewPluginBridge ¶
func NewPluginBridge(manager *PluginManager, registry function.Registry) *PluginBridge
NewPluginBridge 创建插件桥接器
func (*PluginBridge) GetManager ¶
func (b *PluginBridge) GetManager() *PluginManager
GetManager 获取插件管理器
func (*PluginBridge) GetRegistry ¶
func (b *PluginBridge) GetRegistry() function.Registry
GetRegistry 获取函数注册表
func (*PluginBridge) ListRegisteredFunctions ¶
func (b *PluginBridge) ListRegisteredFunctions() []string
ListRegisteredFunctions 列出已注册的函数
func (*PluginBridge) RegisterAll ¶
func (b *PluginBridge) RegisterAll() error
RegisterAll 注册所有插件函数到注册表
func (*PluginBridge) UnregisterAll ¶
func (b *PluginBridge) UnregisterAll()
UnregisterAll 注销所有已注册的函数
type PluginContext ¶
type PluginContext struct {
// FunctionRegistry 函数注册表
// 插件可以通过此接口注册自定义函数
FunctionRegistry function.Registry
// EventBus 事件总线
// 插件可以通过此接口监听和触发事件
EventBus event.EventBus
// Config 插件配置
// 从配置文件传递给插件的参数
Config map[string]interface{}
// Logger 日志记录器
Logger Logger
// Permissions 权限检查器(v1.2.0 新增)
// 插件可以通过此接口检查是否有权限执行某些操作
Permissions *PermissionChecker
// contains filtered or unexported fields
}
PluginContext 插件上下文 提供给插件访问系统资源的接口
func (*PluginContext) GetPluginName ¶
func (ctx *PluginContext) GetPluginName() string
GetPluginName 获取插件名称
func (*PluginContext) SetEventBus ¶
func (ctx *PluginContext) SetEventBus(bus event.EventBus)
SetEventBus 设置事件总线
func (*PluginContext) SetFunctionRegistry ¶
func (ctx *PluginContext) SetFunctionRegistry(registry function.Registry)
SetFunctionRegistry 设置函数注册表
func (*PluginContext) SetLogger ¶
func (ctx *PluginContext) SetLogger(logger Logger)
SetLogger 设置日志记录器
func (*PluginContext) SetPermissions ¶
func (ctx *PluginContext) SetPermissions(checker *PermissionChecker)
SetPermissions 设置权限检查器
func (*PluginContext) SetPluginName ¶
func (ctx *PluginContext) SetPluginName(name string)
SetPluginName 设置插件名称
type PluginDiscovery ¶
type PluginDiscovery struct {
// contains filtered or unexported fields
}
PluginDiscovery 插件发现器 负责扫描目录、发现插件、监听文件变更
func (*PluginDiscovery) AddDirectory ¶
func (d *PluginDiscovery) AddDirectory(dir string) error
AddDirectory 添加监听目录
func (*PluginDiscovery) GetDirectories ¶
func (d *PluginDiscovery) GetDirectories() []string
GetDirectories 获取监听目录列表
func (*PluginDiscovery) GetPlugin ¶
func (d *PluginDiscovery) GetPlugin(path string) *DiscoveredPlugin
GetPlugin 获取指定插件
func (*PluginDiscovery) GetPlugins ¶
func (d *PluginDiscovery) GetPlugins() map[string]*DiscoveredPlugin
GetPlugins 获取所有发现的插件
func (*PluginDiscovery) OnDiscovery ¶
func (d *PluginDiscovery) OnDiscovery(callback DiscoveryCallback)
OnDiscovery 注册发现回调
func (*PluginDiscovery) RemoveDirectory ¶
func (d *PluginDiscovery) RemoveDirectory(dir string) error
RemoveDirectory 移除监听目录
func (*PluginDiscovery) Scan ¶
func (d *PluginDiscovery) Scan() ([]*DiscoveredPlugin, error)
Scan 扫描所有目录
func (*PluginDiscovery) SetScanInterval ¶
func (d *PluginDiscovery) SetScanInterval(interval time.Duration)
SetScanInterval 设置扫描间隔
type PluginError ¶
type PluginError struct {
// PluginName 插件名称
PluginName string
// FunctionName 函数名称
FunctionName string
// OriginalError 原始错误
OriginalError error
// IsPanic 是否是 panic
IsPanic bool
// PanicValue panic 值
PanicValue interface{}
// Stack 堆栈信息
Stack []byte
}
PluginError 插件错误
type PluginManager ¶
type PluginManager struct {
// contains filtered or unexported fields
}
PluginManager 插件管理器 统一管理所有类型的插件,提供加载、卸载、调用等功能
func NewPluginManager ¶
func NewPluginManager(config *ManagerConfig) *PluginManager
NewPluginManager 创建插件管理器
func (*PluginManager) Call ¶
func (pm *PluginManager) Call(funcName string, args []interface{}) (interface{}, error)
Call 调用插件函数
func (*PluginManager) DisableHotReload ¶
func (pm *PluginManager) DisableHotReload()
DisableHotReload 禁用热加载
func (*PluginManager) EnableHotReload ¶
func (pm *PluginManager) EnableHotReload(dirs []string) error
EnableHotReload 启用热加载
func (*PluginManager) GetAdapter ¶
func (pm *PluginManager) GetAdapter(pluginID string) (PluginAdapter, error)
GetAdapter 获取插件适配器
func (*PluginManager) GetDiagnostics ¶
func (pm *PluginManager) GetDiagnostics() *Diagnostics
GetDiagnostics 获取诊断工具
func (*PluginManager) GetFunctionBus ¶
func (pm *PluginManager) GetFunctionBus() *FunctionBus
GetFunctionBus 获取函数总线
func (*PluginManager) GetMetrics ¶
func (pm *PluginManager) GetMetrics() *MetricsCollector
GetMetrics 获取指标收集器
func (*PluginManager) GetPlugin ¶
func (pm *PluginManager) GetPlugin(pluginID string) (*Manifest, error)
GetPlugin 获取插件信息
func (*PluginManager) HasFunction ¶
func (pm *PluginManager) HasFunction(funcName string) bool
HasFunction 检查函数是否存在
func (*PluginManager) ListFunctions ¶
func (pm *PluginManager) ListFunctions() []string
ListFunctions 列出所有可用函数
func (*PluginManager) ListPlugins ¶
func (pm *PluginManager) ListPlugins() []*Manifest
ListPlugins 列出所有已加载的插件
func (*PluginManager) LoadPlugin ¶
func (pm *PluginManager) LoadPlugin(manifestPath string) error
LoadPlugin 加载插件
func (*PluginManager) ReloadPlugin ¶
func (pm *PluginManager) ReloadPlugin(pluginID string) error
ReloadPlugin 重新加载插件
func (*PluginManager) UnloadPlugin ¶
func (pm *PluginManager) UnloadPlugin(pluginID string) error
UnloadPlugin 卸载插件
type PluginManagerInterface ¶
type PluginManagerInterface interface {
// GetContext 获取插件上下文
GetContext() *PluginContext
}
PluginManagerInterface 插件管理器接口 用于热加载器与管理器的解耦
type PluginMetrics ¶
type PluginMetrics struct {
// CallCount 函数调用总次数
CallCount int64
// ErrorCount 错误次数
ErrorCount int64
// TotalDuration 总执行时间
TotalDuration time.Duration
// AvgDuration 平均执行时间
AvgDuration time.Duration
// MinDuration 最小执行时间
MinDuration time.Duration
// MaxDuration 最大执行时间
MaxDuration time.Duration
// LastError 最后一次错误
LastError error
// LastCallTime 最后一次调用时间
LastCallTime time.Time
// LastSuccessTime 最后一次成功调用时间
LastSuccessTime time.Time
}
PluginMetrics 插件运行指标 用于监控和诊断插件性能
func (*PluginMetrics) RecordCall ¶
func (m *PluginMetrics) RecordCall(duration time.Duration, err error)
RecordCall 记录一次函数调用
type PluginMetricsData ¶
type PluginMetricsData struct {
// PluginName 插件名称
PluginName string
// PluginType 插件类型
PluginType PluginType
// TotalCalls 总调用次数
TotalCalls int64
// SuccessCalls 成功调用次数
SuccessCalls int64
// ErrorCalls 错误调用次数
ErrorCalls int64
// TotalDuration 总耗时
TotalDuration time.Duration
// MinDuration 最小耗时
MinDuration time.Duration
// MaxDuration 最大耗时
MaxDuration time.Duration
// LastCallTime 最后调用时间
LastCallTime time.Time
// LoadTime 加载时间
LoadTime time.Time
// Status 插件状态
Status string
}
PluginMetricsData 插件指标数据
func (*PluginMetricsData) AverageDuration ¶
func (d *PluginMetricsData) AverageDuration() time.Duration
AverageDuration 计算平均耗时
func (*PluginMetricsData) ErrorRate ¶
func (d *PluginMetricsData) ErrorRate() float64
ErrorRate 计算错误率
type PluginStatus ¶
type PluginStatus int
PluginStatus 插件状态
const ( // StatusUnloaded 未加载 StatusUnloaded PluginStatus = iota // StatusLoaded 已加载(但未初始化) StatusLoaded // StatusInitialized 已初始化 StatusInitialized // StatusStarted 已启动 StatusStarted // StatusStopped 已停止 StatusStopped // StatusError 错误状态 StatusError )
type PluginStatusDetail ¶
type PluginStatusDetail struct {
// Name 插件名称
Name string
// Type 插件类型
Type PluginType
// Status 状态
Status string
// LoadTime 加载时间
LoadTime time.Time
// TotalCalls 总调用次数
TotalCalls int64
// ErrorCalls 错误调用次数
ErrorCalls int64
// AverageDuration 平均耗时
AverageDuration time.Duration
// LastCallTime 最后调用时间
LastCallTime time.Time
// Functions 函数列表
Functions []string
}
PluginStatus 插件状态详情
type PluginType ¶
type PluginType string
PluginType 插件类型
const ( // PluginTypeGo Go 原生插件(.so/.dll 动态库) PluginTypeGo PluginType = "go" // PluginTypeRPC RPC 插件(通过 gRPC 与独立进程通信) PluginTypeRPC PluginType = "rpc" // PluginTypeScript DSL 脚本插件(使用 DSL 语言编写) PluginTypeScript PluginType = "script" // PluginTypeCommand 命令行插件(封装外部命令行工具) PluginTypeCommand PluginType = "command" )
type ProcessPool ¶
type ProcessPool struct {
// contains filtered or unexported fields
}
ProcessPool 进程池 管理命令行插件的子进程,避免频繁创建进程的开销
func NewProcessPool ¶
func NewProcessPool(config ProcessPoolConfig) (*ProcessPool, error)
NewProcessPool 创建进程池
type ProcessPoolConfig ¶
type ProcessPoolConfig struct {
// Command 命令路径
Command string
// Args 命令参数
Args []string
// MinSize 最小进程数(默认 1)
MinSize int
// MaxSize 最大进程数(默认 10)
MaxSize int
// IdleTimeout 空闲超时时间(默认 5 分钟)
IdleTimeout time.Duration
}
ProcessPoolConfig 进程池配置
type RPCPluginAdapter ¶
type RPCPluginAdapter struct {
// contains filtered or unexported fields
}
RPCPluginAdapter RPC 插件适配器 通过 gRPC 与独立进程中的插件通信
func NewRPCPluginAdapter ¶
func NewRPCPluginAdapter() *RPCPluginAdapter
NewRPCPluginAdapter 创建 RPC 插件适配器
func (*RPCPluginAdapter) Execute ¶
func (a *RPCPluginAdapter) Execute(funcName string, args []interface{}) (interface{}, error)
Execute 执行函数调用
func (*RPCPluginAdapter) GetFunctions ¶
func (a *RPCPluginAdapter) GetFunctions() map[string]*FunctionSignature
GetFunctions 获取函数签名
func (*RPCPluginAdapter) GetMetrics ¶
func (a *RPCPluginAdapter) GetMetrics() *PluginMetrics
GetMetrics 获取运行指标
func (*RPCPluginAdapter) GetTimeout ¶
func (a *RPCPluginAdapter) GetTimeout() time.Duration
GetTimeout 获取默认超时时间
func (*RPCPluginAdapter) Init ¶
func (a *RPCPluginAdapter) Init(manifest *Manifest, ctx *PluginContext) error
Init 初始化适配器
func (*RPCPluginAdapter) SetTimeout ¶
func (a *RPCPluginAdapter) SetTimeout(timeout time.Duration)
SetTimeout 设置默认超时时间
type ResourceLimiter ¶
type ResourceLimiter struct {
// contains filtered or unexported fields
}
ResourceLimiter 资源限制器
func NewResourceLimiter ¶
func NewResourceLimiter(limits *ResourceLimits) *ResourceLimiter
NewResourceLimiter 创建资源限制器
func (*ResourceLimiter) AcquireCall ¶
func (r *ResourceLimiter) AcquireCall() error
AcquireCall 获取调用许可 返回 nil 表示允许调用,否则返回错误
func (*ResourceLimiter) CheckMemory ¶
func (r *ResourceLimiter) CheckMemory(currentMemory int64) error
CheckMemory 检查内存使用 返回 nil 表示在限制内,否则返回错误
func (*ResourceLimiter) ExecuteWithTimeout ¶
func (r *ResourceLimiter) ExecuteWithTimeout( ctx context.Context, fn func() (interface{}, error), ) (interface{}, error)
ExecuteWithTimeout 带超时执行函数
func (*ResourceLimiter) GetCallsInMinute ¶
func (r *ResourceLimiter) GetCallsInMinute() int
GetCallsInMinute 获取当前分钟内的调用次数
func (*ResourceLimiter) GetCurrentCalls ¶
func (r *ResourceLimiter) GetCurrentCalls() int
GetCurrentCalls 获取当前并发调用数
func (*ResourceLimiter) GetLimits ¶
func (r *ResourceLimiter) GetLimits() *ResourceLimits
GetLimits 获取资源限制
func (*ResourceLimiter) SetLimits ¶
func (r *ResourceLimiter) SetLimits(limits *ResourceLimits)
SetLimits 设置资源限制
type ResourceLimits ¶
type ResourceLimits struct {
// MaxMemory 最大内存限制(字节)
// 0 表示不限制
MaxMemory int64
// MaxCPUPercent 最大 CPU 使用率(0-100)
// 0 表示不限制
MaxCPUPercent int
// MaxExecutionTime 最大执行时间
// 0 表示不限制
MaxExecutionTime time.Duration
// MaxConcurrentCalls 最大并发调用数
// 0 表示不限制
MaxConcurrentCalls int
// MaxCallsPerMinute 每分钟最大调用次数
// 0 表示不限制
MaxCallsPerMinute int
}
ResourceLimits 资源限制配置
func DefaultResourceLimits ¶
func DefaultResourceLimits() *ResourceLimits
DefaultResourceLimits 默认资源限制
type ScriptPlugin ¶
type ScriptPlugin struct {
// contains filtered or unexported fields
}
ScriptPlugin 脚本插件 允许通过 DSL 脚本定义插件功能
func NewScriptPlugin ¶
func NewScriptPlugin(config ScriptPluginConfig) *ScriptPlugin
NewScriptPlugin 创建脚本插件
func (*ScriptPlugin) Dependencies ¶
func (p *ScriptPlugin) Dependencies() []Dependency
Dependencies 返回插件依赖
func (*ScriptPlugin) GetFunctions ¶
func (p *ScriptPlugin) GetFunctions() []string
GetFunctions 获取函数列表
func (*ScriptPlugin) Initialize ¶
func (p *ScriptPlugin) Initialize(ctx *PluginContext) error
Initialize 初始化插件
type ScriptPluginAdapter ¶
type ScriptPluginAdapter struct {
// contains filtered or unexported fields
}
ScriptPluginAdapter DSL 脚本插件适配器 使用 DSL 语言编写的插件,支持热更新
func NewScriptPluginAdapter ¶
func NewScriptPluginAdapter() *ScriptPluginAdapter
NewScriptPluginAdapter 创建脚本插件适配器
func (*ScriptPluginAdapter) Execute ¶
func (a *ScriptPluginAdapter) Execute(funcName string, args []interface{}) (interface{}, error)
Execute 执行函数调用
func (*ScriptPluginAdapter) GetFunctions ¶
func (a *ScriptPluginAdapter) GetFunctions() map[string]*FunctionSignature
GetFunctions 获取函数签名
func (*ScriptPluginAdapter) GetMetrics ¶
func (a *ScriptPluginAdapter) GetMetrics() *PluginMetrics
GetMetrics 获取运行指标
func (*ScriptPluginAdapter) GetScript ¶
func (a *ScriptPluginAdapter) GetScript() string
GetScript 获取脚本内容
func (*ScriptPluginAdapter) GetScriptPath ¶
func (a *ScriptPluginAdapter) GetScriptPath() string
GetScriptPath 获取脚本路径
func (*ScriptPluginAdapter) Init ¶
func (a *ScriptPluginAdapter) Init(manifest *Manifest, ctx *PluginContext) error
Init 初始化适配器
func (*ScriptPluginAdapter) IsModified ¶
func (a *ScriptPluginAdapter) IsModified() bool
IsModified 检查脚本是否已修改
func (*ScriptPluginAdapter) Reload ¶
func (a *ScriptPluginAdapter) Reload() error
Reload 重新加载脚本(热更新)
type ScriptPluginConfig ¶
type ScriptPluginConfig struct {
Name string
Version string
Description string
Dependencies []Dependency
Script string // DSL 脚本内容
Functions map[string]string
}
ScriptPluginConfig 脚本插件配置
type SystemStatus ¶
type SystemStatus struct {
// Status 总体状态
Status HealthStatus
// Uptime 运行时间
Uptime time.Duration
// PluginCount 插件数量
PluginCount int
// LoadedPlugins 已加载插件数量
LoadedPlugins int
// TotalCalls 总调用次数
TotalCalls int64
// TotalErrors 总错误次数
TotalErrors int64
// MemoryUsage 内存使用
MemoryUsage uint64
// GoRoutines Goroutine 数量
GoRoutines int
// HealthChecks 健康检查结果
HealthChecks []*HealthCheckResult
}
SystemStatus 系统状态
Source Files
¶
- adapter.go
- async.go
- bridge.go
- cache.go
- command_adapter.go
- dependency.go
- diagnostics.go
- discovery.go
- doc.go
- error_isolation.go
- function_bus.go
- go_adapter.go
- hot_reload.go
- jsonlines_protocol.go
- legacy_adapter.go
- manager.go
- manifest.go
- metrics.go
- permission.go
- plugin.go
- process_pool.go
- resource_limits.go
- rpc_adapter.go
- script_adapter.go
- script_plugin.go
- version.go