dag

package
v0.0.11 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2024 License: Apache-2.0 Imports: 14 Imported by: 3

Documentation

Overview

Package dag provides DAG definition and related functionalities.

Introduction

Package dag provides a way to express your business process in form of a DAG (directed acyclic graph) using type Dag. Dag contains information about the process schedule, attributes and actual graph of tasks.

Creating new DAG

Recommended way to define a DAG is via fluent API provided by the package. For example:

task1 := NewNode(emptyTask{taskId: "task1"})
task2 := NewNode(emptyTask{taskId: "task2"}, WithTaskRetries(3))
task1.Next(task2)

everyHour := schedule.NewCron().AtMinute(5)
myDag := New(Id("sample_dag")).
	AddRoot(&task1).
	AddSchedule(everyHour).
	Done()

DAGs are usually stored in a single Registry (Id -> Dag mapping).

dags := Registry{}
addErr := dags.Add(myDag)

Task configuration

Task configuration is kept on the Node level. This is because Task is all about implementing Execute method and information about DAG structure and configuration is kept on Node level. It’s a implementation detail though. Node type contains Config field of type TaskConfig. The most convenient way to setup custom task configuration is by creating a new node using NewNode function.

var task dag.Task = createSomeTask()

// task with default config
n1 := dag.NewNode(task)

// task with 3 retries
n2 := dag.NewNode(task, dag.WithTaskRetries(3))

// task with 3 retries and 5 minutes delay between those retries
n3 := dag.NewNode(

	task,
	dag.WithTaskRetries(3),
	dag.WithTaskRetriesDelay(5 * 60 * time.Second),

)

// when the following task would fail, then email notification would be sent
var emailNotifier notify.Sender = setupEmailNotifier() // mock
n4 := dag.NewNode(task, dag.WithCustomNotifier(emailNotifier))

// setting up the same config for few tasks

	myTaskConfig := func(tc *TaskConfig) {
		tc.TimeoutSeconds = 60
		tc.Retries = 3
		tc.RetriesDelaySeconds = (1800 * time.Milliseconds).Seconds()
	}

m1 := dag.NewNode(task1, myTaskConfig)
m2 := dag.NewNode(task2, myTaskConfig)
// ...
mN := dag.NewNode(taskN, myTaskConfig)

Reference

For more examples and high-level description, please visit: https://ppacer.org/internals/dags/.

Index

Constants

View Source
const MAX_RECURSION = 10000

Variables

View Source
var DefaultTaskConfig = TaskConfig{
	TimeoutSeconds:         10.0 * 60,
	Retries:                0,
	RetriesDelaySeconds:    0.0,
	SendAlertOnRetry:       false,
	SendAlertOnFailure:     true,
	AlertOnRetryTemplate:   DefaultAlertTemplate(),
	AlertOnFailureTemplate: DefaultAlertTemplate(),

	Notifier: nil,
}

Default task configuration. If not specified otherwise the following configuration values would be used for Task scheduling and execution.

View Source
var ErrDagAlreadyInRegistry = errors.New("given DAG ID is already in the Registry")
View Source
var ErrTaskNotFoundInDag = errors.New("task was not found in the DAG")

Functions

func DefaultAlertTemplate

func DefaultAlertTemplate() *template.Template

Default template for alerts.

func TaskExecuteSource

func TaskExecuteSource(t Task) string

TaskExecuteSource returns Task's source code of its Execute() method. In case when method source code cannot be found in the AST (meta.PackagesASTsMap) string with message "NO IMPLEMENTATION FOUND..." would be returned. Though it should be the case only when whole new package is not added to the embedding (src/embed.go).

func TaskHash

func TaskHash(t Task) string

TaskHash returns SHA256 of given Task Execute method body source.

func WithTaskNotSendAlertsOnFailures

func WithTaskNotSendAlertsOnFailures(config *TaskConfig)

WithTaskNotSendAlertsOnFailures is a TaskConfigFunc which sets off sending alerts on task failure.

func WithTaskSendAlertOnRetries

func WithTaskSendAlertOnRetries(config *TaskConfig)

WithTaskSendAlertOnRetries is a TaskConfigFunc which sets sending alerts on task retries.

Types

type Attr

type Attr struct {
	// If set to true schedule dag run would be catch up since last run or
	// Start.
	CatchUp bool     `json:"catchUp"`
	Tags    []string `json:"tags"`
}

Attr represents additional attributes and parameters about Dag and its scheduling. This object is stored in the database as single value by serializing it to JSON.

type Dag

type Dag struct {
	Id       Id
	Schedule *schedule.Schedule
	Attr     Attr
	Root     *Node
}

Dag represents a single process that can be scheduled by ppacer. It contains metadata of the process like identifiers, its schedule and a pointer to actual DAG of tasks to be executed within the process.

Recommended way to create new Dag is to use provided fluent API:

myDag := New(Id("sample_dag")).
  AddSchedule(schedule.NewFixed(startTs, 60 * time.Second)).
  AddRoot(&root).
  AddAttributes(Attr{CatchUp: True}).
  Done()

func New

func New(id Id) *Dag

New creates new Dag instance for given DAG identifier.

func (*Dag) AddAttributes

func (d *Dag) AddAttributes(attr Attr) *Dag

AddAttributes adds Dag attributes.

func (*Dag) AddRoot

func (d *Dag) AddRoot(node *Node) *Dag

AddRoot set Dag Root to given node.

func (*Dag) AddSchedule

func (d *Dag) AddSchedule(sched schedule.Schedule) *Dag

AddSchedule adds Dag schedule.

func (*Dag) Done

func (d *Dag) Done() Dag

Done returns self Dag instance. It's meant to that after calling this method our Dag is defined and shouldn't really by modified further.

func (*Dag) Flatten

func (d *Dag) Flatten() []Task

Flatten DAG into list of Tasks in BFS order.

func (*Dag) FlattenNodes

func (d *Dag) FlattenNodes() []NodeInfo

FlattenNodes flatten DAG into list of Nodes with enriched information in BFS order.

func (*Dag) GetNode

func (d *Dag) GetNode(taskId string) (*Node, error)

GetNoe return DAG Node by task identifier. In case when there is no Task within the DAG of given taskId, then non-nil error will be returned (ErrTaskNotFoundInDag).

func (*Dag) GetTask

func (d *Dag) GetTask(taskId string) (Task, error)

GetTask return task by its identifier. In case when there is no Task within the DAG of given taskId, then non-nil error will be returned (ErrTaskNotFoundInDag).

func (*Dag) HashDagMeta

func (d *Dag) HashDagMeta() string

HashAttr calculates SHA256 hash based on DAG attribues, start time and schedule.

func (*Dag) HashTasks

func (d *Dag) HashTasks() string

HashTasks calculates SHA256 hash based on concatanated body sources of Execute methods for all tasks.

func (*Dag) IsValid

func (d *Dag) IsValid() bool

Graph is a valid DAG when the following conditions are met:

  • Is acyclic (does not have cycles)
  • Task identifiers are unique within the graph
  • Graph is no deeper then MAX_RECURSION

func (*Dag) String

func (d *Dag) String() string

String return string with information about Dag Id, its schedule and tasks.

func (*Dag) TaskParents

func (d *Dag) TaskParents() map[string][]string

TaskParents returns mapping of DAG task IDs onto its parents task IDs.

type Id

type Id string

DAG string identifier.

type Node

type Node struct {
	Task     Task
	Config   TaskConfig
	Children []*Node
}

Node represents single node (vertex) in the DAG.

func NewNode

func NewNode(task Task, configFuncs ...TaskConfigFunc) *Node

NewNode initialize Node with given task and returns the reference. For custom configuration a set of TaskConfigFunc can be passed. For example:

var t Task = T()
n1 := NewNode(t, WithTaskTimeout(30 * time.Second), WithTaskRetries(3))

var t2 Task = T2()
n2 := NewNode(t2, func(config *TaskConfig) {
		config.TimeoutSeconds = 10
		config.SendAlertOnRetry = true
	})

In case when no configFuncs are passed, then DefaultTaskConfig would be used.

func (*Node) Flatten

func (dn *Node) Flatten() []NodeInfo

Flattens tree (DAG) into a list of NodeInfo. Flattening is done in BFS order. Result slice does not contain duplicates. List of nodes might be incomplete if depth of the graph exceeds MAX_RECURSION value.

func (*Node) Hash

func (dn *Node) Hash() string

Hash calculates SHA256 hash based on concatenated body sources of Execute methods of all children recursively.

func (*Node) Next

func (dn *Node) Next(node *Node) *Node

Next adds given node as a child and returns it's reference. That means Next can be chained (eg: n1.Next(n2).Next(n3)...).

func (*Node) NextAsyncAndMerge

func (dn *Node) NextAsyncAndMerge(asyncNodes []*Node, mergeNode *Node) *Node

NextAsyncAndMerge adds given slice of nodes as children which then have one shared child (mergeNode). That shared child reference is returned. That situation can be visualized like this:

      an[0]
    /       \
   /  an[1]  \
  / /      \  \
dn -- an[2] ---- mergeNode
  \ \      /  /
   \  an[3]  /
    \  ...  /
      an[N]

func (*Node) NextTask

func (dn *Node) NextTask(task Task) *Node

NextTask wraps given task into a Node and calls regular Next method. It exists mainly for shorter notation.

func (*Node) String

func (n *Node) String(ident int) string

type NodeInfo

type NodeInfo struct {
	Node    *Node
	Depth   int
	Width   int
	Parents []*Node
}

NodeInfo represents enriched information about node in the DAG. It's used mostly for convenience. In particular it's used to flatten DAG into slice of NodeInfo.

type Registry

type Registry map[Id]Dag

Registry for DAGs.

func (Registry) Add

func (r Registry) Add(d Dag) error

Add adds given DAG to registry. If there is already a DAG in registry with the same identifier as given DAG, then ErrDagAlreadyInRegistry is returned.

type RunInfo

type RunInfo struct {
	DagId  Id
	ExecTs time.Time
}

TODO

type RunStatus

type RunStatus int

RunStatus enumerates possible DAG run states.

const (
	RunReadyToSchedule RunStatus = iota
	RunScheduled
	RunRunning
	RunSuccess
	RunFailed
)

func ParseRunStatus

func ParseRunStatus(s string) (RunStatus, error)

ParseRunStatus parses run status based on given string. If given string does not match any run status, then non-nil error is returned. Statuses are case-sensitive.

func (RunStatus) String

func (s RunStatus) String() string

String serialize RunStatus.

type Task

type Task interface {
	Id() string
	Execute(TaskContext) error
}

Task represents single step in DAG which is going to be scheduled and executed via executors. TaskContext for Execute method is usually provided by executors where tasks are being executed.

type TaskConfig

type TaskConfig struct {
	TimeoutSeconds      float64 `json:"timeoutSeconds"`
	Retries             int     `json:"retries"`
	RetriesDelaySeconds float64 `json:"retriesDelaySeconds"`
	SendAlertOnRetry    bool    `json:"sendAlertOnRetry"`
	SendAlertOnFailure  bool    `json:"sendAlertOnFailure"`

	// Notification sender for that task. By default is nil which mean that
	// notifier set on scheduler or executor level would be used. If we want to
	// use non-default notification sender for this task, we should set
	// Notifier field to non-nil instance. One can use WithCustomNotifier
	// method, to do so.
	Notifier notify.Sender `json:"-"`

	AlertOnRetryTemplate   notify.Template `json:"-"`
	AlertOnFailureTemplate notify.Template `json:"-"`
}

TaskConfig represents Task configuration. It contains information about configuration of a task execution, like a timeout for executing given task or how many times scheduler should retry in case of failures.

type TaskConfigFunc

type TaskConfigFunc func(*TaskConfig)

TaskConfigFunc is a family of functions which takes a TaskConfig and potentially updates values of given configuration.

func WithCustomFailureAlertTemplate

func WithCustomFailureAlertTemplate(tmpl notify.Template) TaskConfigFunc

WithCustomFailureAlertTemplate returns TaskConfigFunc for setting a custom template for alerts in cases when Task execution has failed.

func WithCustomNotifier

func WithCustomNotifier(notifier notify.Sender) TaskConfigFunc

WithCustomNotifier returns TaskConfigFunc for setting a custom notification sender for the task.

func WithCustomRetryAlertTemplate

func WithCustomRetryAlertTemplate(tmpl notify.Template) TaskConfigFunc

WithCustomRetryAlertTemplate returns TaskConfigFunc for setting a custom template for alerts in cases when Task execution has failed and will be retried.

func WithTaskRetries

func WithTaskRetries(retries int) TaskConfigFunc

WithTaskRetries returns TaskConfigFunc for setting number of retries for task execution.

func WithTaskRetriesDelay

func WithTaskRetriesDelay(delay time.Duration) TaskConfigFunc

WithTaskRetriesDelay returns TaskConfigFunc for setting delay duration between next retries of task execution.

func WithTaskTimeout

func WithTaskTimeout(timeout time.Duration) TaskConfigFunc

WithTaskTimeout returns TaskConfigFunc for setting a timeout for task execution.

type TaskContext

type TaskContext struct {
	Context context.Context
	Logger  *slog.Logger
	DagRun  RunInfo

	// Notifier can be used to send external notifications from inside of a
	// task, additionally to standard notitifactions on task execution failures
	// or retries provided by the TaskScheduler.
	Notifier notify.Sender
}

TaskContext is a context for Task execute method.

type TaskRunInfo

type TaskRunInfo struct {
	DagId  Id
	ExecTs time.Time
	TaskId string
}

DAG run task information context.

type TaskStatus

type TaskStatus int

TaskStatus enumerates possible Task states within the DAG run.

const (
	TaskScheduled TaskStatus = iota
	TaskRunning
	TaskFailed
	TaskFailedPendingRetry
	TaskSuccess
	TaskUpstreamFailed
	TaskNoStatus
	TaskRestarting
)

func ParseTaskStatus

func ParseTaskStatus(s string) (TaskStatus, error)

ParseTaskStatus parses task status based on given string. If given string does not match any task status, then non-nil error is returned. Statuses are case-sensitive.

func (TaskStatus) CanProceed

func (s TaskStatus) CanProceed() bool

func (TaskStatus) IsTerminal

func (s TaskStatus) IsTerminal() bool

func (TaskStatus) String

func (s TaskStatus) String() string

String serializes TaskStatus to its upper case string.

Directories

Path Synopsis
Package schedule contains implementations of ppacer Schedules.
Package schedule contains implementations of ppacer Schedules.
Package tasklog implements ppacer Task loggers.
Package tasklog implements ppacer Task loggers.

Jump to

Keyboard shortcuts

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