Skip to content

Commit 302b067

Browse files
committed
Refactor workflow sorting method to update steps in order
Modified the `sortSteps` method of `Workflow` to update steps in a sorted order based on keys. This refactor ensures that steps are now updated sequentially according to their sorted keys, aligning with the intended workflow processing order.
1 parent f5a8645 commit 302b067

File tree

1 file changed

+35
-6
lines changed

1 file changed

+35
-6
lines changed

pkg/workflow.go

+35-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package workflow
22

3-
import "log"
3+
import (
4+
"log"
5+
"sort"
6+
)
47

58
type LocalTransaction func() error
69
type CompensatingAction func() error
@@ -25,22 +28,48 @@ func (w *Workflow) AddStep(name string, step SagaStep) {
2528
}
2629

2730
func (w *Workflow) Execute() error {
31+
w.sortSteps()
32+
33+
var completedSteps []string
34+
2835
for stepName, stepFunc := range w.Steps {
2936
log.Printf("[Executing step] %s", stepName)
3037

3138
if err := stepFunc.Transaction(); err != nil {
3239
log.Printf("[Error executing step] %s: %s", stepName, err)
3340

34-
for n, f := range w.Steps {
41+
// Perform compensating actions for all previously completed steps
42+
for i := len(completedSteps) - 1; i >= 0; i-- {
43+
n := completedSteps[i]
3544
log.Printf("[Compensating step] %s", n)
36-
f.Compensate()
37-
38-
if stepName == n {
39-
break
45+
if err := w.Steps[n].Compensate(); err != nil {
46+
log.Printf("[Error compensating step] %s: %s", n, err)
47+
// Handle compensation error if needed
4048
}
4149
}
50+
51+
// Stop execution as soon as an error occurs
52+
return err
4253
}
54+
55+
// Track successfully completed steps
56+
completedSteps = append(completedSteps, stepName)
4357
}
4458

4559
return nil
4660
}
61+
62+
func (w *Workflow) sortSteps() {
63+
keys := make([]string, 0, len(w.Steps))
64+
for k := range w.Steps {
65+
keys = append(keys, k)
66+
}
67+
sort.Strings(keys)
68+
69+
sortedSteps := make(map[string]SagaStep, len(w.Steps))
70+
for _, k := range keys {
71+
sortedSteps[k] = w.Steps[k]
72+
}
73+
74+
w.Steps = sortedSteps
75+
}

0 commit comments

Comments
 (0)