ograph

package module
v0.0.0-...-0dd650e Latest Latest
Warning

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

Go to latest
Published: May 21, 2024 License: MIT Imports: 14 Imported by: 0

README

                ________________                     ______  
                __  __ \_  ____/____________ ___________  /_ 
                _  / / /  / __ __  ___/  __ `/__  __ \_  __ \
                / /_/ // /_/ / _  /   / /_/ /__  /_/ /  / / /
                \____/ \____/  /_/    \__,_/ _  .___//_/ /_/ 
			                                 /_/             

OGraph: A simple way to build a pipeline with Go

languages os

中文 | English

OGraph 是一个用 Go 实现的图流程执行框架。

你可以通过构建Pipeline(流水线),来控制依赖元素依次顺序执行、非依赖元素并发执行的调度功能。

此外,OGraph 还提供了丰富的重试,超时限制,执行追踪等开箱即用的特征。

同类项目对比

OGraph 受启发于另一个 C++项目 CGraph。但 OGraph 并不等于 Go 版本的 CGraph。

功能对比

和 CGraph 一样,OGraph 也提供基本的构图和调度执行能力,但有以下几点关键不同:

  • 用 Go 实现,使用协程而非线程进行调度,更轻量灵活

  • 支持通过 Wrapper 来自定义循环、执行条件判断、错误处理等逻辑,并可以随意组合

  • 支持导出图结构,再在别处导入执行(符合限制的情况下)

  • 灵活的虚节点设置,用以简化依赖关系,以及延迟到运行时决定实际执行的节点,实现多态

性能对比

经过 Benchmark 测试,OGraph 和 CGraph 的性能在同一水平。如果在 io 密集场景下,OGraph 更有优势。

CGraph 性能测试参考

OGraph 性能测试参考

限制 8 核,三个场景(并发32节点,串行32节点,复杂情况模拟6节点)分别执行 100 w 次

cd test
go test -bench='(Concurrent_32|Serial_32|Complex_6)$' -benchtime=1000000x -benchmem -cpu=8

输出结果

goos: linux
goarch: amd64
pkg: github.com/symphony09/ograph/test
cpu: AMD Ryzen 5 5600G with Radeon Graphics         
BenchmarkConcurrent_32-8         1000000              9669 ns/op            2212 B/op         64 allocs/op
BenchmarkSerial_32-8             1000000              1761 ns/op             712 B/op         15 allocs/op
BenchmarkComplex_6-8             1000000              3118 ns/op            1152 B/op         26 allocs/op
PASS
ok      github.com/symphony09/ograph/test       14.553s

快速开始

第一步:声明一个 Node 接口实现
type Person struct {
	ograph.BaseNode
}

func (person *Person) Run(ctx context.Context, state ogcore.State) error {
	fmt.Printf("Hello, i am %s.\n", person.Name())
	return nil
}

上面代码中 Person 组合了 BaseNode,并覆写了 Node 接口方法 Run。

第二步:构建一个 Pipeline 并运行
func TestHello(t *testing.T) {
	pipeline := ograph.NewPipeline()

	zhangSan := ograph.NewElement("ZhangSan").UseNode(&Person{})
	liSi := ograph.NewElement("LiSi").UseNode(&Person{})

	pipeline.Register(zhangSan).
		Register(liSi, ograph.DependOn(zhangSan))

	if err := pipeline.Run(context.TODO(), nil); err != nil {
		t.Error(err)
	}
}

上面代码在 pipeline 中注册了两个 Person 节点(zhangSan、liSi),并指定 liSi 依赖于 zhangSan。

输出结果

Hello, i am ZhangSan.
Hello, i am LiSi.

更多示例

更多示例代码,请参考 example 目录下代码。

示例文件名 示例说明
e01_hello_test.go 演示基本流程
e02_state_test.go 演示如何在节点间分享状态数据
e03_factory_test.go 演示如何用工厂模式创建节点
e04_param_test.go 演示如何设置节点参数
e05_wrapper_test.go 演示如何使用 wrapper 增强节点功能
e06_cluster_test.go 演示如何使用 cluster 灵活调度多个节点
e07_global_test.go 演示如何全局注册工厂函数
e08_virtual_test.go 演示如何使用虚拟节点简化依赖关系
e09_interrupter_test.go 演示如何在pipeline运行过程中插入中断
e10_compose_test.go 演示怎么组合嵌套pipeline
e11_advance_test.go 一些进阶用法,包含图校验、导出,池预热等

Q&A

导出导入图的限制是什么?

所有节点需要是以工厂方式创建,导入图的 pipeline 需要已注册节点对应的工厂。

为什么提供多种节点创建方式(UseNode,UseFactory,UseFn)?

对于简单场景直接注册单例和运行函数比较方便,但要考虑 pipeline 并发执行问题和图导入导出时,就需要使用工厂方式。

State 存取是并发安全的吗?

默认使用的 state 是并发安全的,但如果是使用了自定义实现则无法保证并发安全。

怎么达到最佳性能,有最佳实践吗?

由于协程轻量灵活,一般不用做调整优化,如果节点初始化比较慢可以考虑预热 worker 池。

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Branch = func(elements ...*Element) Op {
	return func(pipeline *Pipeline, element *Element) {
		if len(elements) == 0 {
			return
		}

		var prev, next *Element

		prev = element

		for i := range elements {
			next = elements[i]

			if pipeline.elements[next.Name] == nil {
				pipeline.Register(next)
			}

			if pipeline.elements[next.Name] == next {
				pipeline.graph.AddEdge(prev.Name, next.Name)
			}

			prev = next
		}
	}
}

Register(a, ograph.Branch(b, c, d)) => a->b->c->d

View Source
var DependOn = func(dependencies ...*Element) Op {
	return func(pipeline *Pipeline, element *Element) {
		for _, dep := range dependencies {
			if pipeline.elements[dep.Name] == nil {
				pipeline.Register(dep)
			}

			if pipeline.elements[dep.Name] == dep {
				pipeline.graph.AddEdge(dep.Name, element.Name)
			}
		}
	}
}
View Source
var ErrFactoryNotFound error = errors.New("factory not found")
View Source
var Then = func(nextElements ...*Element) Op {
	return func(pipeline *Pipeline, element *Element) {
		for _, next := range nextElements {
			if pipeline.elements[next.Name] == nil {
				pipeline.Register(next)
			}

			if pipeline.elements[next.Name] == next {
				pipeline.graph.AddEdge(element.Name, next.Name)
			}
		}
	}
}

Functions

func LoadPrivateState

func LoadPrivateState[SK ~string, SV any](state ogcore.State, key string) SV

func LoadState

func LoadState[SV any](state ogcore.State, key string) SV

func SavePrivateState

func SavePrivateState[SK ~string](state ogcore.State, key string, val any, overwrite bool)

func SaveState

func SaveState(state ogcore.State, key string, val any, overwrite bool)

func UpdatePrivateState

func UpdatePrivateState[SK ~string, SV any](state ogcore.State, key string, updateFunc func(oldVal SV) (val SV)) error

func UpdateState

func UpdateState[SV any](state ogcore.State, key string, updateFunc func(oldVal SV) (val SV)) error

Types

type BaseCluster

type BaseCluster struct {
	BaseNode

	Group   []ogcore.Node
	NodeMap map[string]ogcore.Node
}

func (*BaseCluster) Join

func (cluster *BaseCluster) Join(nodes []ogcore.Node)

func (BaseCluster) Run

func (cluster BaseCluster) Run(ctx context.Context, state ogcore.State) error

type BaseNode

type BaseNode struct {
	Action ogcore.Action
	// contains filtered or unexported fields
}

func (*BaseNode) Name

func (node *BaseNode) Name() string

func (BaseNode) Run

func (node BaseNode) Run(ctx context.Context, state ogcore.State) error

func (*BaseNode) SetName

func (node *BaseNode) SetName(name string)

type BaseState

type BaseState struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewState

func NewState() *BaseState

func (*BaseState) Get

func (state *BaseState) Get(key any) (any, bool)

func (*BaseState) Set

func (state *BaseState) Set(key any, val any)

func (*BaseState) Update

func (state *BaseState) Update(key any, updateFunc func(val any) any)

type BaseWrapper

type BaseWrapper struct {
	BaseNode

	ogcore.Node
}

func (BaseWrapper) Run

func (wrapper BaseWrapper) Run(ctx context.Context, state ogcore.State) error

func (*BaseWrapper) Wrap

func (wrapper *BaseWrapper) Wrap(node ogcore.Node)

type Builder

type Builder struct {
	Factories *ogcore.Factories
}

func (*Builder) RegisterFactory

func (builder *Builder) RegisterFactory(name string, factory func() ogcore.Node) *Builder

func (*Builder) RegisterPrototype

func (builder *Builder) RegisterPrototype(name string, prototype ogcore.Cloneable) *Builder

type Element

type Element struct {
	Virtual     bool
	Name        string
	FactoryName string
	Wrappers    []string
	ParamsMap   map[string]any
	DefaultImpl string

	Singleton ogcore.Node `json:"-"`

	PrivateFactory func() ogcore.Node `json:"-"`

	SubElements  []*Element
	ImplElements []*Element
}

func NewElement

func NewElement(name string) *Element

func (*Element) AsVirtual

func (e *Element) AsVirtual() *Element

func (*Element) GetRequiredFactories

func (e *Element) GetRequiredFactories() map[string]bool

func (*Element) Implement

func (e *Element) Implement(virtualElem *Element, isDefault bool) *Element

func (*Element) Params

func (e *Element) Params(key string, val any) *Element

func (*Element) SetVirtual

func (e *Element) SetVirtual(isVirtual bool) *Element

func (*Element) UseFactory

func (e *Element) UseFactory(name string, subElements ...*Element) *Element

func (*Element) UseFn

func (e *Element) UseFn(fn func() error) *Element

func (*Element) UseNode

func (e *Element) UseNode(node ogcore.Node) *Element

func (*Element) UsePrivateFactory

func (e *Element) UsePrivateFactory(factory func() ogcore.Node, subElements ...*Element) *Element

func (*Element) Wrap

func (e *Element) Wrap(wrappers ...string) *Element

type FuncNode

type FuncNode struct {
	BaseNode

	RunFunc func(ctx context.Context, state ogcore.State) error
}

func NewFuncNode

func NewFuncNode(runFunc func(ctx context.Context, state ogcore.State) error) *FuncNode

func (*FuncNode) Run

func (node *FuncNode) Run(ctx context.Context, state ogcore.State) error

type Op

type Op func(pipeline *Pipeline, element *Element)

type PGraph

type PGraph = internal.Graph[*Element]

type Pipeline

type Pipeline struct {
	BaseNode
	Builder

	Interrupters     []ogcore.Interrupter
	ParallelismLimit int
	DisablePool      bool
	// contains filtered or unexported fields
}

func NewPipeline

func NewPipeline() *Pipeline

func (*Pipeline) Check

func (pipeline *Pipeline) Check() error

func (*Pipeline) DumpDOT

func (pipeline *Pipeline) DumpDOT() ([]byte, error)

func (*Pipeline) DumpGraph

func (pipeline *Pipeline) DumpGraph() ([]byte, error)

func (*Pipeline) ForEachElem

func (pipeline *Pipeline) ForEachElem(op func(e *Element)) *Pipeline

func (*Pipeline) LoadGraph

func (pipeline *Pipeline) LoadGraph(data []byte) error

func (*Pipeline) Register

func (pipeline *Pipeline) Register(e *Element, ops ...Op) *Pipeline

func (*Pipeline) RegisterInterrupt

func (pipeline *Pipeline) RegisterInterrupt(handler ogcore.InterruptHandler, on ...string) *Pipeline

func (*Pipeline) ResetPool

func (pipeline *Pipeline) ResetPool()

func (*Pipeline) Run

func (pipeline *Pipeline) Run(ctx context.Context, state ogcore.State) error

func (*Pipeline) SetPoolCache

func (pipeline *Pipeline) SetPoolCache(size int, warmup bool) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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