core/plugins/register.go

145 lines
3.2 KiB
Go

// Package plugins ...
//
// Description : plugins ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-11-13 17:57
package plugins
import (
"errors"
"git.zhangdeman.cn/gateway/core/define"
"git.zhangdeman.cn/gateway/core/plugins/abstract"
"git.zhangdeman.cn/zhangdeman/trace"
"strings"
"sync"
"time"
)
var (
lock = &sync.RWMutex{}
)
// pluginTable 全局插件注册表
var pluginTable = map[string]abstract.IPlugin{}
// Register 注册插件
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 17:58 2024/11/13
func Register(plugin abstract.IPlugin) error {
if nil == plugin {
return errors.New("plugin instance is nil")
}
lock.Lock()
defer lock.Unlock()
if len(plugin.ID()) == 0 {
return errors.New("plugin id empty")
}
if _, exist := pluginTable[plugin.ID()]; exist {
return errors.New(plugin.ID() + " : plugin instance already exist")
}
pluginTable[plugin.ID()] = plugin
return nil
}
// Get 获取插件实例
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:02 2024/11/13
func Get(pluginID string) (abstract.IPlugin, error) {
lock.RLock()
lock.RUnlock()
if _, exist := pluginTable[pluginID]; !exist {
return nil, errors.New(pluginID + " : plugin instance not found")
}
return pluginTable[pluginID], nil
}
// NewPluginResult 获取plugin的执行结果实例
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:19 2024/11/13
func NewPluginResult(rc *define.RequestContext) *define.PluginResult {
return &define.PluginResult{
Trace: trace.NewRuntime(rc.TraceID(), 1),
StartTime: time.Now().UnixMilli(),
FinishTime: 0,
IsSuccess: false,
SkipFailure: false,
Data: make(map[string]any),
ErrMsg: "",
Config: make(map[string]any),
}
}
// Dispatch 调度执行插件
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:07 2024/11/13
func Dispatch(rc *define.RequestContext, pluginIDList []string) error {
l := &sync.RWMutex{}
errList := []string{}
wg := &sync.WaitGroup{}
for _, itemPluginID := range pluginIDList {
wg.Add(1)
go func(pluginID string) {
defer func() {
wg.Done()
if r := recover(); r != nil {
l.Lock()
errList = append(errList, r.(error).Error())
l.Unlock()
}
}()
pluginInstance, err := Get(pluginID)
if nil != err {
l.Lock()
errList = append(errList, err.Error())
l.Unlock()
return
}
pluginCfg, err := pluginInstance.Config()
if nil != err {
l.Lock()
errList = append(errList, err.Error())
l.Unlock()
return
}
pluginResult := pluginInstance.Logic(rc, pluginCfg)
if nil == pluginResult {
l.Lock()
errList = append(errList, "plugin result is nil")
l.Unlock()
return
}
rc.SetPluginResult(pluginResult)
}(itemPluginID)
}
wg.Wait()
if len(errList) > 0 {
return errors.New(strings.Join(errList, "|"))
}
return nil
}
// InitDefault 初始化注册默认的插件
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 18:04 2024/11/13
func InitDefault() error {
defaultPluginList := []abstract.IPlugin{}
for _, itemPlugin := range defaultPluginList {
if err := Register(itemPlugin); err != nil {
return err
}
}
return nil
}