LightFlow:一个基于函数式编程的任务编排框架

在现代软件开发中,任务流的管理常常让人头疼。现在,LightFlow 诞生了!这是一个基于 Go 语言的任务编排框架,旨在简化复杂任务流的设计与管理。通过函数式编程,LightFlow 使开发者能够在代码中直接定义任务流,将重点放在任务的执行时机,而无需繁琐的配置文件和规则。

为什么选择 LightFlow?#

  1. 简化任务流管理:告别外部规则语言,LightFlow 允许开发者在代码中定义所有任务依赖,减少频繁切换上下文的烦恼。
  2. 专注执行时机:只需明确任务的依赖步骤,框架将自动处理任务执行顺序,极大降低全局依赖管理的复杂性。
  3. 提升维护性和可扩展性:即使任务流不断扩展,确定任务执行时机仍然是一项简单而基本的工作。

核心特性#

快速上手#

安装#

通过以下命令轻松安装 LightFlow:

go get github.com/Bilibotter/light-flow/flow

示例代码#

以下示例展示了如何使用 LightFlow 进行任务编排:

package main

import (
    "fmt"
    "github.com/Bilibotter/light-flow/flow"
)

func First(step flow.Step) (any, error) {
    if input, exist := step.Get("input"); exist {
        fmt.Printf("[Step: %s] get input: %v\n", step.Name(), input)
    }
    step.Set("key", "value")
    return "result", nil
}

func Second(step flow.Step) (any, error) {
    if value, exist := step.Get("key"); exist {
        fmt.Printf("[Step: %s] get key: %v\n", step.Name(), value)
    }
    if result, exist := step.Result(step.Dependents()[0]); exist {
        fmt.Printf("[Step: %s] get result: %v\n", step.Name(), result)
    }
    return nil, nil
}

func ErrorStep(step flow.Step) (any, error) {
    if value, exist := step.Get("key"); exist {
        fmt.Printf("[Step: %s] get key: %v\n", step.Name(), value)
    } else {
        fmt.Printf("[Step: %s] cannot get key \n", step.Name())
    }
    return nil, fmt.Errorf("execute failed")
}

func ErrorHandler(step flow.Step) (bool, error) {
    if step.Has(flow.Failed) {
        fmt.Printf("[Step: %s] has failed\n", step.Name())
    } else {
        fmt.Printf("[Step: %s] success\n", step.Name())
    }
    return true, nil
}

func init() {
    process := flow.FlowWithProcess("Example")
    process.Follow(First, Second)
    process.Follow(ErrorStep)
    process.AfterStep(true, ErrorHandler)
}

func main() {
    flow.DoneFlow("Example", map[string]any{"input": "Hello world"})
}

输出示例#

执行上述代码后,你将看到如下输出:

[Step: First] get input: Hello world
[Step: First] success
[Step: Second] get key: value
[Step: Second] get result: result
[Step: Second] success
[Step: ErrorStep] cannot get key 
[Step: ErrorStep] has failed

使用步骤#

  1. 定义步骤:编写你的 Step 函数,使用 step.Getstep.Set 与上下文交互。查看文档
  2. 创建流程:在 init 函数中定义流程并添加步骤。查看文档
  3. 错误处理:利用回调管理各种错误情况。查看文档
  4. 启动执行:调用 flow.DoneFlow 方法开始执行流程,传入必要的输入数据。

LightFlow 设计为尽可能执行所有任务,即便某个任务失败,只有依赖于该任务的后续任务会被跳过,而其他不相关的任务仍将继续运行。
这种设计支持断点恢复,确保在错误发生时系统仍能有效执行未受影响的部分。

本作品采用《CC 协议》,转载必须注明作者和本文链接