plugin

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 8, 2026 License: MIT Imports: 23 Imported by: 0

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

View Source
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

View Source
var (
	ErrExecutorNotRunning = &asyncError{"executor not running"}
	ErrQueueFull          = &asyncError{"task queue full"}
	ErrTimeout            = &asyncError{"operation timeout"}
)

错误定义

Functions

func GetAllPermissions

func GetAllPermissions() []string

GetAllPermissions 获取所有已知权限

func IsLegacyPlugin

func IsLegacyPlugin(plugin Plugin) bool

IsLegacyPlugin 检查插件是否为 v1.1 插件

func IsPermissionDenied

func IsPermissionDenied(err error) bool

IsPermissionDenied 检查错误是否为权限拒绝错误

func IsPluginError

func IsPluginError(err error) bool

IsPluginError 检查是否是插件错误

func MigrateLegacyPlugin

func MigrateLegacyPlugin(plugin Plugin) (PluginAdapter, *Manifest)

MigrateLegacyPlugin 迁移 v1.1 插件到 v1.2 返回适配器和生成的 manifest

func ValidateManifest

func ValidateManifest(manifest *Manifest) error

ValidateManifest 验证插件清单

func ValidatePermissions

func ValidatePermissions(perms []string) error

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 带上下文的异步调用

func (*AsyncExecutor) Start

func (e *AsyncExecutor) Start()

Start 启动异步执行器

func (*AsyncExecutor) Stop

func (e *AsyncExecutor) Stop()

Stop 停止异步执行器

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) Get

func (f *AsyncFuture) Get() *AsyncResult

Get 获取结果(阻塞)

func (*AsyncFuture) GetWithTimeout

func (f *AsyncFuture) GetWithTimeout(timeout time.Duration) *AsyncResult

GetWithTimeout 带超时获取结果

func (*AsyncFuture) IsDone

func (f *AsyncFuture) IsDone() bool

IsDone 是否完成

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 缓存配置

func DefaultCacheConfig

func DefaultCacheConfig() *CacheConfig

DefaultCacheConfig 默认缓存配置

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 设置默认超时时间

func (*CommandPluginAdapter) Stop

func (a *CommandPluginAdapter) Stop() error

Stop 停止适配器

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 NewDependencyGraph

func NewDependencyGraph() *DependencyGraph

NewDependencyGraph 创建依赖图

func (*DependencyGraph) Add

func (g *DependencyGraph) Add(plugin Plugin) error

Add 添加插件到依赖图

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 NewDiagnostics

func NewDiagnostics() *Diagnostics

NewDiagnostics 创建诊断工具

func (*Diagnostics) FormatStatus

func (d *Diagnostics) FormatStatus() string

FormatStatus 格式化状态输出

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) GetUptime

func (d *Diagnostics) GetUptime() time.Duration

GetUptime 获取运行时间

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

type ErrorHandler func(pluginName string, funcName string, err error)

ErrorHandler 错误处理器

type ErrorIsolator

type ErrorIsolator struct {
	// contains filtered or unexported fields
}

ErrorIsolator 错误隔离器 确保插件错误不会影响其他插件或主程序

func NewErrorIsolator

func NewErrorIsolator() *ErrorIsolator

NewErrorIsolator 创建错误隔离器

func (*ErrorIsolator) Disable

func (e *ErrorIsolator) Disable()

Disable 禁用错误隔离

func (*ErrorIsolator) Enable

func (e *ErrorIsolator) Enable()

Enable 启用错误隔离

func (*ErrorIsolator) Execute

func (e *ErrorIsolator) Execute(
	pluginName string,
	funcName string,
	fn func() (interface{}, error),
) (result interface{}, err error)

Execute 安全执行函数(带 panic 恢复)

func (*ErrorIsolator) IsEnabled

func (e *ErrorIsolator) IsEnabled() bool

IsEnabled 是否启用

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 NewFunctionBus

func NewFunctionBus() *FunctionBus

NewFunctionBus 创建函数总线

func (*FunctionBus) Call

func (fb *FunctionBus) Call(funcName string, args []interface{}) (interface{}, error)

Call 调用函数 funcName: 要调用的函数名 args: 函数参数 返回函数执行结果和可能的错误

func (*FunctionBus) Clear

func (fb *FunctionBus) Clear()

Clear 清空所有注册的函数

func (*FunctionBus) Count

func (fb *FunctionBus) Count() int

Count 返回已注册函数的数量

func (*FunctionBus) GetAdapter

func (fb *FunctionBus) GetAdapter(funcName string) (PluginAdapter, error)

GetAdapter 获取函数对应的适配器

func (*FunctionBus) Has

func (fb *FunctionBus) Has(funcName string) bool

Has 检查函数是否已注册

func (*FunctionBus) List

func (fb *FunctionBus) List() []string

List 列出所有已注册的函数

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 创建函数缓存

func (*FunctionCache) Cleanup

func (c *FunctionCache) Cleanup() int

Cleanup 清理过期条目

func (*FunctionCache) Clear

func (c *FunctionCache) Clear()

Clear 清空缓存

func (*FunctionCache) Delete

func (c *FunctionCache) Delete(key string)

Delete 删除缓存值

func (*FunctionCache) Disable

func (c *FunctionCache) Disable()

Disable 禁用缓存

func (*FunctionCache) Enable

func (c *FunctionCache) Enable()

Enable 启用缓存

func (*FunctionCache) Get

func (c *FunctionCache) Get(key string) (interface{}, bool)

Get 获取缓存值

func (*FunctionCache) IsEnabled

func (c *FunctionCache) IsEnabled() bool

IsEnabled 是否启用

func (*FunctionCache) Set

func (c *FunctionCache) Set(key string, value interface{})

Set 设置缓存值

func (*FunctionCache) Size

func (c *FunctionCache) Size() int

Size 返回缓存大小

func (*FunctionCache) Stats

func (c *FunctionCache) Stats() *CacheStats

Stats 返回缓存统计

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 NewGoPluginAdapter

func NewGoPluginAdapter() *GoPluginAdapter

NewGoPluginAdapter 创建 Go 插件适配器

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 初始化适配器

func (*GoPluginAdapter) Stop

func (a *GoPluginAdapter) Stop() error

Stop 停止适配器

type HealthCheckFunc

type HealthCheckFunc func() *HealthCheckResult

HealthCheckFunc 健康检查函数

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) Disable

func (h *HotReloader) Disable()

Disable 禁用热加载

func (*HotReloader) Enable

func (h *HotReloader) Enable() error

Enable 启用热加载

func (*HotReloader) GetAdapter

func (h *HotReloader) GetAdapter(path string) PluginAdapter

GetAdapter 获取适配器

func (*HotReloader) GetAdapters

func (h *HotReloader) GetAdapters() map[string]PluginAdapter

GetAdapters 获取所有适配器

func (*HotReloader) IsEnabled

func (h *HotReloader) IsEnabled() bool

IsEnabled 是否启用热加载

func (*HotReloader) LoadAll

func (h *HotReloader) LoadAll() error

LoadAll 加载所有发现的插件

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 设置重新加载延迟

func (*HotReloader) Start

func (h *HotReloader) Start(dirs []string) error

Start 启动热加载(添加目录并开始监听)

func (*HotReloader) Stop

func (h *HotReloader) Stop()

Stop 停止热加载

func (*HotReloader) UnloadAll

func (h *HotReloader) UnloadAll()

UnloadAll 卸载所有插件

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 初始化适配器

func (*IsolatedAdapter) Stop

func (a *IsolatedAdapter) Stop() error

Stop 停止适配器

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 调用函数(带超时)

func (*JSONLinesProtocol) Close

func (p *JSONLinesProtocol) Close() error

Close 关闭协议

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 初始化适配器

func (*LegacyPluginAdapter) Stop

func (a *LegacyPluginAdapter) Stop() error

Stop 停止适配器

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 日志记录器接口

func NewDefaultLogger

func NewDefaultLogger() Logger

NewDefaultLogger 创建默认日志记录器

type ManagerConfig

type ManagerConfig struct {
	// PluginDirs 插件目录列表
	PluginDirs []string

	// EnableHotReload 是否启用热加载
	EnableHotReload bool

	// EnableMetrics 是否启用指标收集
	EnableMetrics bool

	// EnableDiagnostics 是否启用诊断
	EnableDiagnostics bool

	// ResourceLimits 资源限制配置
	ResourceLimits *ResourceLimits

	// Logger 日志记录器
	Logger Logger
}

ManagerConfig 管理器配置

func DefaultManagerConfig

func DefaultManagerConfig() *ManagerConfig

DefaultManagerConfig 默认管理器配置

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

func CreateManifestFromPlugin(plugin Plugin) *Manifest

CreateManifestFromPlugin 从 v1.1 插件创建 Manifest 用于将 v1.1 插件的元数据转换为 v1.2 的 Manifest 格式

func ParseManifest

func ParseManifest(path string) (*Manifest, error)

ParseManifest 解析插件清单文件

func (*Manifest) GetFunction

func (m *Manifest) GetFunction(name string) *FunctionDeclaration

GetFunction 根据名称获取函数声明

func (*Manifest) HasPermission

func (m *Manifest) HasPermission(perm string) bool

HasPermission 检查是否有指定权限

func (*Manifest) ToJSON

func (m *Manifest) ToJSON() (string, error)

ToJSON 将清单转换为 JSON 字符串

type MetricsCollector

type MetricsCollector struct {
	// contains filtered or unexported fields
}

MetricsCollector 指标收集器 收集插件运行时的各种指标

func NewMetricsCollector

func NewMetricsCollector() *MetricsCollector

NewMetricsCollector 创建指标收集器

func (*MetricsCollector) Disable

func (c *MetricsCollector) Disable()

Disable 禁用指标收集

func (*MetricsCollector) Enable

func (c *MetricsCollector) Enable()

Enable 启用指标收集

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) IsEnabled

func (c *MetricsCollector) IsEnabled() bool

IsEnabled 是否启用

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) Reset

func (c *MetricsCollector) Reset()

Reset 重置所有指标

func (*MetricsCollector) Summary

func (c *MetricsCollector) Summary() string

Summary 生成摘要报告

func (*MetricsCollector) ToPrometheus

func (c *MetricsCollector) ToPrometheus() string

ToPrometheus 导出为 Prometheus 格式

func (*MetricsCollector) UnregisterPlugin

func (c *MetricsCollector) UnregisterPlugin(name string)

UnregisterPlugin 注销插件

type PanicHandler

type PanicHandler func(pluginName string, funcName string, panicValue interface{}, stack []byte)

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) Grant

func (pc *PermissionChecker) Grant(perm string)

Grant 授予权限

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 检查是否有任意一个权限

func (*PermissionChecker) List

func (pc *PermissionChecker) List() []string

List 列出所有已授予的权限

func (*PermissionChecker) Revoke

func (pc *PermissionChecker) Revoke(perm string)

Revoke 撤销权限

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) Sync

func (b *PluginBridge) Sync() error

Sync 同步插件函数到注册表 添加新函数,移除已删除的函数

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 NewPluginContext

func NewPluginContext() *PluginContext

NewPluginContext 创建插件上下文

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 NewPluginDiscovery

func NewPluginDiscovery() *PluginDiscovery

NewPluginDiscovery 创建插件发现器

func (*PluginDiscovery) AddDirectory

func (d *PluginDiscovery) AddDirectory(dir string) error

AddDirectory 添加监听目录

func (*PluginDiscovery) Clear

func (d *PluginDiscovery) Clear()

Clear 清除所有发现的插件

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) IsWatching

func (d *PluginDiscovery) IsWatching() bool

IsWatching 是否正在监听

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 设置扫描间隔

func (*PluginDiscovery) StopWatch

func (d *PluginDiscovery) StopWatch()

StopWatch 停止监听

func (*PluginDiscovery) Watch

func (d *PluginDiscovery) Watch() error

Watch 开始监听文件变更

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 插件错误

func GetPluginError

func GetPluginError(err error) *PluginError

GetPluginError 获取插件错误

func (*PluginError) Error

func (e *PluginError) Error() string

Error 实现 error 接口

func (*PluginError) Unwrap

func (e *PluginError) Unwrap() error

Unwrap 返回原始错误

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) Start

func (pm *PluginManager) Start() error

Start 启动插件管理器

func (*PluginManager) Stop

func (pm *PluginManager) Stop() error

Stop 停止插件管理器

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) ErrorRate

func (m *PluginMetrics) ErrorRate() float64

ErrorRate 计算错误率

func (*PluginMetrics) RecordCall

func (m *PluginMetrics) RecordCall(duration time.Duration, err error)

RecordCall 记录一次函数调用

func (*PluginMetrics) Reset

func (m *PluginMetrics) Reset()

Reset 重置指标

func (*PluginMetrics) SuccessRate

func (m *PluginMetrics) SuccessRate() float64

SuccessRate 计算成功率

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
)

func (PluginStatus) String

func (s PluginStatus) String() string

String 返回状态的字符串表示

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"
)

func (PluginType) IsValid

func (t PluginType) IsValid() bool

IsValid 检查插件类型是否有效

func (PluginType) String

func (t PluginType) String() string

String 返回插件类型的字符串表示

type Process

type Process struct {
	// contains filtered or unexported fields
}

Process 进程包装

type ProcessPool

type ProcessPool struct {
	// contains filtered or unexported fields
}

ProcessPool 进程池 管理命令行插件的子进程,避免频繁创建进程的开销

func NewProcessPool

func NewProcessPool(config ProcessPoolConfig) (*ProcessPool, error)

NewProcessPool 创建进程池

func (*ProcessPool) Acquire

func (p *ProcessPool) Acquire(ctx context.Context) (*Process, error)

Acquire 获取一个进程

func (*ProcessPool) Available

func (p *ProcessPool) Available() int

Available 返回可用进程数

func (*ProcessPool) Close

func (p *ProcessPool) Close() error

Close 关闭进程池

func (*ProcessPool) Release

func (p *ProcessPool) Release(proc *Process) error

Release 归还进程

func (*ProcessPool) Size

func (p *ProcessPool) Size() int

Size 返回当前进程数

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 设置默认超时时间

func (*RPCPluginAdapter) Stop

func (a *RPCPluginAdapter) Stop() error

Stop 停止适配器

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) Disable

func (r *ResourceLimiter) Disable()

Disable 禁用资源限制

func (*ResourceLimiter) Enable

func (r *ResourceLimiter) Enable()

Enable 启用资源限制

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) IsEnabled

func (r *ResourceLimiter) IsEnabled() bool

IsEnabled 是否启用

func (*ResourceLimiter) ReleaseCall

func (r *ResourceLimiter) ReleaseCall()

ReleaseCall 释放调用许可

func (*ResourceLimiter) Reset

func (r *ResourceLimiter) Reset()

Reset 重置计数器

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) Description

func (p *ScriptPlugin) Description() string

Description 返回插件描述

func (*ScriptPlugin) GetFunctions

func (p *ScriptPlugin) GetFunctions() []string

GetFunctions 获取函数列表

func (*ScriptPlugin) GetScript

func (p *ScriptPlugin) GetScript() string

GetScript 获取脚本内容

func (*ScriptPlugin) Initialize

func (p *ScriptPlugin) Initialize(ctx *PluginContext) error

Initialize 初始化插件

func (*ScriptPlugin) Name

func (p *ScriptPlugin) Name() string

Name 返回插件名称

func (*ScriptPlugin) Shutdown

func (p *ScriptPlugin) Shutdown() error

Shutdown 卸载插件

func (*ScriptPlugin) Start

func (p *ScriptPlugin) Start() error

Start 启动插件

func (*ScriptPlugin) Status

func (p *ScriptPlugin) Status() PluginStatus

Status 获取插件状态

func (*ScriptPlugin) Stop

func (p *ScriptPlugin) Stop() error

Stop 停止插件

func (*ScriptPlugin) Version

func (p *ScriptPlugin) Version() string

Version 返回插件版本

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 重新加载脚本(热更新)

func (*ScriptPluginAdapter) Stop

func (a *ScriptPluginAdapter) Stop() error

Stop 停止适配器

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 系统状态

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL