dag

package
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Overview

Package dag 提供一个轻量的有向无环图(DAG)执行器: 按依赖关系将节点拓扑分层,同一层内的节点并行执行,层间串行。 不绑定任何数据库 / 调度器 / 任务体系——每个节点的工作由 Node.Run 闭包描述。

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DAG

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

DAG 是一组按依赖关系执行的节点。零值不可用,请用 New 构造。

Example
// build -> [test, lint] -> deploy
d := New().Add(
	Node{Name: "build", Run: func(ctx context.Context) error { return nil }},
	Node{Name: "test", DependsOn: []string{"build"}, Run: func(ctx context.Context) error { return nil }},
	Node{Name: "lint", DependsOn: []string{"build"}, Run: func(ctx context.Context) error { return nil }},
	Node{Name: "deploy", DependsOn: []string{"test", "lint"}, Run: func(ctx context.Context) error { return nil }},
)
if err := d.Run(context.Background()); err != nil {
	panic(err)
}

func New

func New(opts ...Option) *DAG

New 创建一个 DAG。

func (*DAG) Add

func (d *DAG) Add(nodes ...Node) *DAG

Add 追加一个或多个节点,返回自身以便链式调用。

func (*DAG) Run

func (d *DAG) Run(ctx context.Context) error

Run 校验并执行整个 DAG。层间串行,层内并行,遵循 ctx 取消。

  • FailFast:返回首个失败层的错误(多个失败用 errors.Join 合并)。
  • ContinueOnError:执行完所有层,返回所有错误的 errors.Join(无错误则 nil)。

func (*DAG) Validate

func (d *DAG) Validate() error

Validate 校验图的合法性:节点名不重复、依赖均存在、无循环依赖。

type Node

type Node struct {
	// Name 节点唯一标识,用于被其它节点在 DependsOn 中引用。
	Name string
	// DependsOn 前置依赖节点名;这些节点全部成功(或在 ContinueOnError 下执行完)后本节点才会运行。
	DependsOn []string
	// Run 节点要执行的工作。为 nil 时视为空节点(仅占位/聚合依赖)。
	Run func(ctx context.Context) error
}

Node 是 DAG 中的一个工作单元及其依赖。

type Option

type Option func(*DAG)

Option 配置 DAG。

func WithMaxParallel

func WithMaxParallel(n int) Option

WithMaxParallel 限制同一层内并发执行的节点数(信号量),避免大扇出层 一次性起成千上万个 goroutine。n<=0(默认)表示不限制。

func WithStrategy

func WithStrategy(s Strategy) Option

WithStrategy 设置错误处理策略,默认 FailFast。

type Strategy

type Strategy int

Strategy 控制某个节点返回错误时的行为。

const (
	// FailFast(默认):当前层一旦有节点失败,等本层执行完后即停止,不再调度后续层。
	FailFast Strategy = iota
	// ContinueOnError:忽略错误继续执行所有层,最终汇总所有错误返回。
	ContinueOnError
)

Jump to

Keyboard shortcuts

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