请在保持这份流水线代码的同时,降低其圈复杂度和认知复杂度 package main import ( "context" "errors" "fmt" "sync"…
- User
请在保持这份流水线代码的同时,降低其圈复杂度和认知复杂度 package main
import ( "context" "errors" "fmt" "sync" "time" )
// Task 定义任务的数据结构 type Task struct { ID int // 原始任务ID(批次ID) Data interface{} // 输入数据 Result interface{} // 处理结果 Retries int // 重试次数 }
// TaskFunc 定义任务处理函数类型,返回多个结果 type TaskFunc func(ctx context.Context, data interface{}) ([]interface{}, error)
// Layer 定义流水线的每一层 type Layer struct { workerCount int timeout time.Duration maxRetries int taskFunc TaskFunc }
// Pipeline 定义整个流水线结构 type Pipeline struct { layers []*Layer }
// NewPipeline 创建一个新的流水线实例 func NewPipeline() *Pipeline { return &Pipeline{ layers: make([]*Layer, 0), } }
// AddLayer 向流水线中添加一层 func (p *Pipeline) AddLayer(taskFunc TaskFunc, workerCount int, timeout time.Duration, maxRetries int) { layer := &Layer{ workerCount: workerCount, timeout: timeout, maxRetries: maxRetries, taskFunc: taskFunc, } p.layers = append(p.layers, layer) }
// Run 启动流水线处理任务,并在每个任务完成时调用回调函数 func (p *Pipeline) Run(input []interface{}, callback func(task *Task)) error { if len(p.layers) == 0 { return errors.New("pipeline has no layers") }
// 初始化任务通道 inCh := make(chan *Task, len(input)) // 将输入数据封装成任务并发送到第一个通道 go func() { for _, data := range input { // 假设每个输入是批量数据(一个切片) inCh <- &Task{ID: 0, Data: data} } close(inCh) }() // 设置初始输入 currentIn := inCh var currentOut chan *Task // 用于取消整个流水线的上下文(仅在严重错误时使用) ctxPipeline, cancelPipeline := context.WithCancel(context.Background()) defer cancelPipeline() // 遍历每一层,构建流水线 for _, layer := range p.layers { currentOut = make(chan *Task, len(input)*2) // 预留更大的缓冲区以支持任务拆分 var wg sync.WaitGroup // 启动工作协程 for w := 0; w < layer.workerCount; w++ { wg.Add(1) go func(layer *Layer, in <-chan *Task, out chan<- *Task) { defer wg.Done() for task := range in { retries := task.Retries var results []interface{} var err error for { // 创建带超时的上下文 ctx, cancel := context.WithTimeout(ctxPipeline, layer.timeout) results, err = layer.taskFunc(ctx, task.Data) cancel() if err != nil { retries++ if retries > layer.maxRetries { // 超过重试次数,记录失败 fmt.Printf("Task ID %d failed after %d retries: %v\n", task.ID, retries-1, err) task.Result = nil break } task.Retries = retries fmt.Printf("Task ID %d retry %d due to error: %v\n", task.ID, retries, err) continue } task.Result = results break } if err != nil { // 任务失败,传递失败信息 out <- task continue } // 如果有多个结果,创建多个子任务 if len(results) > 1 { for _, res := range results { subTask := &Task{ ID: task.ID, // 保持相同的任务ID Data: res, Result: nil, Retries: task.Retries, } out <- subTask } } else { // 单个结果,直接传递 task.Data = results[0] out <- task } } }(layer, currentIn, currentOut) } // 等待所有工作协程完成后关闭输出通道 go func(wg *sync.WaitGroup, out chan *Task) { wg.Wait() close(out) }(&wg, currentOut) // 准备下一层的输入 currentIn = currentOut } // 最后一层输出处理 var wgFinal sync.WaitGroup wgFinal.Add(1) go func() { defer wgFinal.Done() for task := range currentOut { if task.Result == nil { // 如果某个任务失败,记录错误信息 fmt.Printf("Task ID %d failed during processing.\n", task.ID) // 根据需要处理失败任务,如记录日志或继续 } else { // 调用回调函数处理每个任务的结果 callback(task) } } }() // 等待所有任务完成 wgFinal.Wait() return nil - Assistant