This repository has been archived by the owner on Mar 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
workflow_executor.go
100 lines (82 loc) · 2.25 KB
/
workflow_executor.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
package sequence
import (
"context"
"errors"
"github.com/frantjc/go-js"
"github.com/frantjc/sequence/pkg/github/actions"
)
var ErrUnmeetableJobNeeds = errors.New("job has an unmeetable needs clause")
func IsErrUnmeetableJobNeeds(err error) bool {
return errors.Is(err, ErrUnmeetableJobNeeds)
}
type workflowExecutor struct {
jobExecutors []*jobExecutor
workflow *Workflow
}
func NewWorkflowExecutor(ctx context.Context, workflow *Workflow, opts ...ExecutorOpt) (Executor, error) {
var (
w = &workflowExecutor{
workflow: workflow,
}
needs = []string{}
jLen = len(workflow.Jobs)
)
// order Jobs so that they don't execute until after
// their needs are met
for len(w.jobExecutors) < jLen {
added := false
for jobName, job := range workflow.Jobs {
jobOpts := opts
jobOpts = append(jobOpts, WithWorkflowName(workflow.Name))
if job.Needs != "" && !js.Includes(needs, job.Needs) {
continue
}
jobID := js.Coalesce(job.Name, jobName)
if js.Includes(needs, jobID) {
continue
}
jobOpts = append(jobOpts, WithJobName(jobID))
executor, err := NewJobExecutor(ctx, job, jobOpts...)
if err != nil {
return nil, err
}
w.jobExecutors = append(w.jobExecutors, executor.(*jobExecutor))
needs = append(needs, jobID)
added = true
}
// if we ever go a full iteration over the Jobs without
// adding a new executor, then we have detected an infinite loop
// due to a job having unmeetable needs
if !added {
return nil, ErrUnmeetableJobNeeds
}
}
return w, nil
}
func (e *workflowExecutor) Execute() error {
return e.ExecuteContext(context.Background())
}
func (e *workflowExecutor) ExecuteContext(ctx context.Context) error {
var (
globalContext *actions.GlobalContext
onWorkflowFinish Hooks[*Workflow]
)
for i, jobExecutor := range e.jobExecutors {
globalContext = jobExecutor.GlobalContext
if i == 0 {
onWorkflowFinish = jobExecutor.OnWorkflowFinish
jobExecutor.OnWorkflowStart.Invoke(&Event[*Workflow]{
Type: e.workflow,
GlobalContext: globalContext,
})
}
if err := jobExecutor.ExecuteContext(ctx); err != nil {
return err
}
}
onWorkflowFinish.Invoke(&Event[*Workflow]{
Type: e.workflow,
GlobalContext: globalContext,
})
return nil
}