-
Notifications
You must be signed in to change notification settings - Fork 0
/
dag.go
287 lines (260 loc) · 7.42 KB
/
dag.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package lambdag
import (
"context"
"errors"
"log"
"sort"
"sync"
"github.com/Songmu/flextime"
libdag "github.com/heimdalr/dag"
"github.com/samber/lo"
"golang.org/x/sync/errgroup"
)
type DAG struct {
id string
opts DAGOptions
dependencies *libdag.DAG
}
type DAGOptions struct {
newLoggerFunc func(context.Context, *DAGRunContext) (*log.Logger, error)
numOfTasksInSingleInvoke int
circuitBreaker int
}
func WithDAGLogger(fn func(context.Context, *DAGRunContext) (*log.Logger, error)) func(opts *DAGOptions) error {
return func(opts *DAGOptions) error {
opts.newLoggerFunc = fn
return nil
}
}
func WithNumOfTasksInSingleInvoke(num int) func(opts *DAGOptions) error {
return func(opts *DAGOptions) error {
opts.numOfTasksInSingleInvoke = num
return nil
}
}
func WithCircuitBreaker(num int) func(opts *DAGOptions) error {
return func(opts *DAGOptions) error {
opts.circuitBreaker = num
return nil
}
}
func NewDAG(id string, optFns ...func(opts *DAGOptions) error) (*DAG, error) {
dag := &DAG{
id: id,
dependencies: libdag.NewDAG(),
}
for _, optFn := range optFns {
if err := optFn(&dag.opts); err != nil {
return nil, err
}
}
return dag, nil
}
func (dag *DAG) ID() string {
return dag.id
}
func (dag *DAG) NewTask(taskID string, handler TaskHandler, optFns ...func(opts *TaskOptions) error) (*Task, error) {
task, err := newTask(dag, taskID, handler, optFns...)
if err != nil {
return nil, err
}
if err := dag.dependencies.AddVertexByID(taskID, task); err != nil {
var ide libdag.IDDuplicateError
if errors.As(err, &ide) {
return nil, &TaskIDDuplicateError{
TaskID: taskID,
}
}
return nil, UnknownError{err: err}
}
return task, err
}
func (dag *DAG) NewLogger(ctx context.Context, dagRunCtx *DAGRunContext) (*log.Logger, error) {
if dag.opts.newLoggerFunc == nil {
return log.Default(), nil
}
return dag.opts.newLoggerFunc(ctx, dagRunCtx)
}
func (dag *DAG) NumOfTasksInSingleInvoke() int {
if dag.opts.numOfTasksInSingleInvoke <= 0 {
return 1
}
return dag.opts.numOfTasksInSingleInvoke
}
const defaultCircuitBreaker = 10000
func (dag *DAG) CircuitBreaker() int {
if dag.opts.circuitBreaker <= 0 {
return defaultCircuitBreaker
}
return dag.opts.circuitBreaker
}
func (dag *DAG) AddDependency(ancestor *Task, descendant *Task) error {
if err := dag.dependencies.AddEdge(ancestor.ID(), descendant.ID()); err != nil {
var ede libdag.EdgeDuplicateError
if errors.As(err, &ede) {
return &TaskDependencyDuplicateError{
Ancestor: ancestor,
Descendant: descendant,
}
}
var sdee libdag.SrcDstEqualError
if errors.As(err, &sdee) {
return &AncestorDescendantSameError{
Ancestor: ancestor,
Descendant: descendant,
}
}
var ele libdag.EdgeLoopError
if errors.As(err, &ele) {
return &CycleDetectedInDAGError{
Start: ancestor,
End: descendant,
}
}
return UnknownError{err: err}
}
return nil
}
func (dag *DAG) GetTask(taskID string) (*Task, bool) {
v, err := dag.dependencies.GetVertex(taskID)
if err != nil {
return nil, false
}
return v.(*Task), true
}
func (dag *DAG) GetAllTasks() []*Task {
vs := dag.dependencies.GetVertices()
return convertTasks(vs)
}
func (dag *DAG) GetStartTasks() []*Task {
return convertTasks(dag.dependencies.GetRoots())
}
func (dag *DAG) GetDownstreamTasks(taskID string) []*Task {
vs, err := dag.dependencies.GetChildren(taskID)
if err != nil {
return []*Task{}
}
return convertTasks(vs)
}
func (dag *DAG) GetUpstreamTasks(taskID string) []*Task {
vs, err := dag.dependencies.GetParents(taskID)
if err != nil {
return []*Task{}
}
return convertTasks(vs)
}
func (dag *DAG) GetAncestorTasks(taskID string) []*Task {
ancestorTaskIDs, err := dag.dependencies.GetOrderedAncestors(taskID)
if err != nil {
return []*Task{}
}
return lo.FilterMap(ancestorTaskIDs, func(ancestorTaskID string, _ int) (*Task, bool) {
return dag.GetTask(ancestorTaskID)
})
}
func (dag *DAG) GetDescendantTasks(taskID string) []*Task {
descendantTaskIDs, err := dag.dependencies.GetOrderedDescendants(taskID)
if err != nil {
return []*Task{}
}
return lo.FilterMap(descendantTaskIDs, func(descendantTaskID string, _ int) (*Task, bool) {
return dag.GetTask(descendantTaskID)
})
}
func convertTasks(vs map[string]interface{}) []*Task {
tasks := lo.Map(lo.Values(vs), func(v interface{}, _ int) *Task {
return v.(*Task)
})
sort.SliceStable(tasks, func(i, j int) bool {
return tasks[i].id < tasks[j].id
})
return tasks
}
func (dag *DAG) GetExecutableTasks(finishedTaskIDs []string) []*Task {
tasks := dag.GetAllTasks()
return lo.Filter(tasks, func(task *Task, _ int) bool {
return !lo.Contains(finishedTaskIDs, task.ID()) && dag.IsExecutableTask(task.ID(), finishedTaskIDs)
})
}
func (dag *DAG) IsExecutableTask(taskID string, finishedTaskIDs []string) bool {
upstreamTasks := dag.GetUpstreamTasks(taskID)
nonFinishedUpstreamTasks := lo.Filter(upstreamTasks, func(task *Task, _ int) bool {
return !lo.Contains(finishedTaskIDs, task.ID())
})
return len(nonFinishedUpstreamTasks) == 0
}
func (dag *DAG) WarkAllDependencies(fn func(ancestor *Task, descendant *Task) error) error {
tasks := dag.GetAllTasks()
for _, ancestor := range tasks {
for _, descendant := range tasks {
if descendant.ID() == ancestor.ID() {
continue
}
if edge, err := dag.dependencies.IsEdge(ancestor.ID(), descendant.ID()); err != nil {
return err
} else if edge {
if err := fn(ancestor, descendant); err != nil {
return err
}
}
}
}
return nil
}
func (dag *DAG) Execute(ctx context.Context, dagRunCtx *DAGRunContext) (*DAGRunContext, error) {
l, err := dag.NewLogger(ctx, dagRunCtx)
if err != nil {
return dagRunCtx, err
}
if dagRunCtx.LambdaCallCount == 0 {
l.Printf("[info] start new DAG: DAGRunId %s", dagRunCtx.DAGRunID)
}
dagRunCtx.LambdaCallCount++
if dagRunCtx.LambdaCallCount >= dag.CircuitBreaker() {
l.Printf("[info] DAG run CircuitBreak: DAGRunId %s Lambda call Count %d", dagRunCtx.DAGRunID, dagRunCtx.LambdaCallCount)
dagRunCtx.Continue = false
dagRunCtx.IsCircuitBreak = true
return dagRunCtx, nil
}
finishedTasks := lo.Keys(dagRunCtx.TaskResponses)
executableTasks := dag.GetExecutableTasks(finishedTasks)
dagRunCtx.Continue = true
if len(executableTasks) == 0 {
now := flextime.Now()
l.Printf("[info] end DAG: DAGRunId %s DAG Run duration %s", dagRunCtx.DAGRunID, now.Sub(dagRunCtx.DAGRunStartAt))
dagRunCtx.Continue = false
return dagRunCtx, nil
}
eg, egCtx := errgroup.WithContext(ctx)
var mu sync.Mutex
for i := 0; i < dag.NumOfTasksInSingleInvoke(); i++ {
if i >= len(executableTasks) {
break
}
task := executableTasks[i]
eg.Go(func() error {
taskID := task.ID()
l.Printf("[info] start task: DAGRunId %s TaskId %s", dagRunCtx.DAGRunID, taskID)
resp, err := task.Execute(egCtx, dagRunCtx)
l.Printf("[info] end task: DAGRunId %s TaskId %s Success %v", dagRunCtx.DAGRunID, taskID, err == nil)
if err != nil {
return err
}
mu.Lock()
defer mu.Unlock()
dagRunCtx.TaskResponses[taskID] = resp
finishedTasks = append(finishedTasks, taskID)
return nil
})
}
if err := eg.Wait(); err != nil {
return dagRunCtx, err
}
executableTasks = dag.GetExecutableTasks(finishedTasks)
if len(executableTasks) == 0 {
now := flextime.Now()
l.Printf("[info] end DAG: DAGRunId %s DAG Run duration %s", dagRunCtx.DAGRunID, now.Sub(dagRunCtx.DAGRunStartAt))
dagRunCtx.Continue = false
}
return dagRunCtx, nil
}