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
- Variables
- func DefaultAlertTemplate() *template.Template
- func TaskExecuteSource(t Task) string
- func TaskHash(t Task) string
- func WithTaskNotSendAlertsOnFailures(config *TaskConfig)
- func WithTaskSendAlertOnRetries(config *TaskConfig)
- type Attr
- type Dag
- func (d *Dag) AddAttributes(attr Attr) *Dag
- func (d *Dag) AddRoot(node *Node) *Dag
- func (d *Dag) AddSchedule(sched schedule.Schedule) *Dag
- func (d *Dag) Done() Dag
- func (d *Dag) Flatten() []Task
- func (d *Dag) FlattenNodes() []NodeInfo
- func (d *Dag) GetNode(taskId string) (*Node, error)
- func (d *Dag) GetTask(taskId string) (Task, error)
- func (d *Dag) HashDagMeta() string
- func (d *Dag) HashTasks() string
- func (d *Dag) IsValid() bool
- func (d *Dag) String() string
- func (d *Dag) TaskParents() map[string][]string
- type Id
- type Node
- type NodeInfo
- type Registry
- type RunInfo
- type RunStatus
- type Task
- type TaskConfig
- type TaskConfigFunc
- func WithCustomFailureAlertTemplate(tmpl notify.Template) TaskConfigFunc
- func WithCustomNotifier(notifier notify.Sender) TaskConfigFunc
- func WithCustomRetryAlertTemplate(tmpl notify.Template) TaskConfigFunc
- func WithTaskRetries(retries int) TaskConfigFunc
- func WithTaskRetriesDelay(delay time.Duration) TaskConfigFunc
- func WithTaskTimeout(timeout time.Duration) TaskConfigFunc
- type TaskContext
- type TaskRunInfo
- type TaskStatus
Constants ¶
const MAX_RECURSION = 10000
Variables ¶
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.
var ErrDagAlreadyInRegistry = errors.New("given DAG ID is already in the Registry")
var ErrTaskNotFoundInDag = errors.New("task was not found in the DAG")
Functions ¶
func DefaultAlertTemplate ¶
Default template for alerts.
func TaskExecuteSource ¶
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 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 ¶
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 (*Dag) AddAttributes ¶
AddAttributes adds Dag attributes.
func (*Dag) AddSchedule ¶
AddSchedule adds Dag schedule.
func (*Dag) Done ¶
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) FlattenNodes ¶
FlattenNodes flatten DAG into list of Nodes with enriched information in BFS order.
func (*Dag) GetNode ¶
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 ¶
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 ¶
HashAttr calculates SHA256 hash based on DAG attribues, start time and schedule.
func (*Dag) HashTasks ¶
HashTasks calculates SHA256 hash based on concatanated body sources of Execute methods for all tasks.
func (*Dag) IsValid ¶
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) TaskParents ¶
TaskParents returns mapping of DAG task IDs onto its parents task IDs.
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 ¶
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 ¶
Hash calculates SHA256 hash based on concatenated body sources of Execute methods of all children recursively.
func (*Node) Next ¶
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 ¶
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]
type NodeInfo ¶
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 RunStatus ¶
type RunStatus int
RunStatus enumerates possible DAG run states.
func ParseRunStatus ¶
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.
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 ¶
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.