-
Notifications
You must be signed in to change notification settings - Fork 8
/
update.go
96 lines (77 loc) · 2.63 KB
/
update.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
package workflow
import (
"context"
"fmt"
"k8s.io/utils/clock"
"github.com/luno/workflow/internal/graph"
"github.com/luno/workflow/internal/metrics"
)
type (
lookupFunc func(ctx context.Context, runID string) (*Record, error)
storeFunc func(ctx context.Context, record *Record) error
updater[Type any, Status StatusType] func(ctx context.Context, current Status, next Status, run *Run[Type, Status]) error
)
func newUpdater[Type any, Status StatusType](lookup lookupFunc, store storeFunc, graph *graph.Graph, clock clock.Clock) updater[Type, Status] {
return func(ctx context.Context, current Status, next Status, record *Run[Type, Status]) error {
object, err := Marshal(&record.Object)
if err != nil {
return err
}
runState := RunStateRunning
isEnd := graph.IsTerminal(int(next))
if isEnd {
runState = RunStateCompleted
}
updatedRecord := &Record{
WorkflowName: record.WorkflowName,
ForeignID: record.ForeignID,
RunID: record.RunID,
RunState: runState,
Status: int(next),
Object: object,
CreatedAt: record.CreatedAt,
UpdatedAt: clock.Now(),
}
latest, err := lookup(ctx, updatedRecord.RunID)
if err != nil {
return err
}
// Ensure that the record still has the intended status. If not then another consumer will be processing this
// record.
if Status(latest.Status) != current {
return nil
}
err = validateTransition(current, next, graph)
if err != nil {
return err
}
// Push run state changes for observability
metrics.RunStateChanges.WithLabelValues(record.WorkflowName, record.RunState.String(), updatedRecord.RunState.String()).Inc()
return store(ctx, updatedRecord)
}
}
func validateTransition[Status StatusType](current, next Status, graph *graph.Graph) error {
// Lookup all available transitions from the current status
nodes := graph.Transitions(int(current))
if len(nodes) == 0 {
return fmt.Errorf("current status not defined in graph: current=%s", current)
}
var found bool
// Attempt to find the next status amongst the list of valid transitions
for _, node := range nodes {
if node == int(next) {
found = true
break
}
}
// If no valid transition matches that of the next status then error.
if !found {
return fmt.Errorf("current status not defined in graph: current=%s, next=%s", current, next)
}
return nil
}
func updateRecord(ctx context.Context, store storeFunc, record *Record, previousRunState RunState) error {
// Push run state changes for observability
metrics.RunStateChanges.WithLabelValues(record.WorkflowName, previousRunState.String(), record.RunState.String()).Inc()
return store(ctx, record)
}