2026-06-06 19:31:16 +08:00
|
|
|
|
package runner
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
2026-07-26 22:19:41 +08:00
|
|
|
|
"context"
|
2026-06-06 19:31:16 +08:00
|
|
|
|
"fmt"
|
2026-07-26 22:19:41 +08:00
|
|
|
|
"sort"
|
|
|
|
|
|
"sync"
|
2026-06-06 19:31:16 +08:00
|
|
|
|
|
|
|
|
|
|
"github.com/ssdomei232/goodBaby/model"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2026-09-12 15:32:27 +08:00
|
|
|
|
// RuleExecutor 规则执行器接口。
|
|
|
|
|
|
//
|
|
|
|
|
|
// 执行一条规则需要的一切(规则本体、账号凭据)都由上层组装成 model.RuleTask,
|
|
|
|
|
|
// driver 只负责把动作做出去:不查数据库、不写日志,因此每个实现都能单独测试。
|
2026-06-06 19:31:16 +08:00
|
|
|
|
type RuleExecutor interface {
|
2026-07-26 22:19:41 +08:00
|
|
|
|
// Execute 执行规则,ctx 决定了重试的最长时间
|
2026-09-12 15:32:27 +08:00
|
|
|
|
Execute(ctx context.Context, task *model.RuleTask) error
|
2026-06-06 19:31:16 +08:00
|
|
|
|
// GetType 获取执行器支持的规则类型
|
|
|
|
|
|
GetType() string
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// ExecutorRegistry 执行器注册表
|
|
|
|
|
|
type ExecutorRegistry struct {
|
|
|
|
|
|
executors map[string]RuleExecutor
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// NewExecutorRegistry 创建新的执行器注册表
|
|
|
|
|
|
func NewExecutorRegistry() *ExecutorRegistry {
|
|
|
|
|
|
return &ExecutorRegistry{
|
|
|
|
|
|
executors: make(map[string]RuleExecutor),
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Register 注册规则执行器
|
|
|
|
|
|
func (er *ExecutorRegistry) Register(executor RuleExecutor) {
|
|
|
|
|
|
er.executors[executor.GetType()] = executor
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Execute 根据规则类型执行规则
|
2026-09-12 15:32:27 +08:00
|
|
|
|
func (er *ExecutorRegistry) Execute(ctx context.Context, task *model.RuleTask) error {
|
|
|
|
|
|
executor, exists := er.executors[task.Rule.Type]
|
2026-06-06 19:31:16 +08:00
|
|
|
|
if !exists {
|
2026-09-12 15:32:27 +08:00
|
|
|
|
return fmt.Errorf("不支持的规则类型: %s", task.Rule.Type)
|
2026-06-06 19:31:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-09-12 15:32:27 +08:00
|
|
|
|
return executor.Execute(ctx, task)
|
2026-06-06 19:31:16 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// GetSupportedTypes 获取所有支持的规则类型
|
|
|
|
|
|
func (er *ExecutorRegistry) GetSupportedTypes() []string {
|
|
|
|
|
|
types := make([]string, 0, len(er.executors))
|
|
|
|
|
|
for t := range er.executors {
|
|
|
|
|
|
types = append(types, t)
|
|
|
|
|
|
}
|
2026-07-26 22:19:41 +08:00
|
|
|
|
sort.Strings(types)
|
2026-06-06 19:31:16 +08:00
|
|
|
|
return types
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-26 22:19:41 +08:00
|
|
|
|
var (
|
|
|
|
|
|
registryOnce sync.Once
|
|
|
|
|
|
globalExecutorRegistry *ExecutorRegistry
|
|
|
|
|
|
)
|
2026-06-06 19:31:16 +08:00
|
|
|
|
|
|
|
|
|
|
// GetGlobalExecutorRegistry 获取全局执行器注册表
|
|
|
|
|
|
func GetGlobalExecutorRegistry() *ExecutorRegistry {
|
|
|
|
|
|
if globalExecutorRegistry == nil {
|
|
|
|
|
|
panic("执行器注册表未初始化,请先调用 InitExecutorRegistry()")
|
|
|
|
|
|
}
|
|
|
|
|
|
return globalExecutorRegistry
|
|
|
|
|
|
}
|