-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathcoordinator.go
226 lines (188 loc) · 5.65 KB
/
coordinator.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
package saga
import (
"context"
"encoding/json"
"fmt"
"log"
"math/rand"
"reflect"
"time"
)
func NewCoordinator(funcsCtx, compensateFuncsCtx context.Context, saga *Saga, logStore Store, executionID ...string) *ExecutionCoordinator {
c := &ExecutionCoordinator{
funcsCtx: funcsCtx,
compensateFuncsCtx: compensateFuncsCtx,
saga: saga,
logStore: logStore,
}
if len(executionID) > 0 {
c.ExecutionID = executionID[0]
} else {
c.ExecutionID = RandString()
}
return c
}
type ExecutionCoordinator struct {
ExecutionID string
aborted bool
executionError error
compensateErrors []error
funcsCtx context.Context
compensateFuncsCtx context.Context
saga *Saga
logStore Store
}
func (c *ExecutionCoordinator) Play() *Result {
executionStart := time.Now()
checkErr(c.logStore.AppendLog(&Log{
ExecutionID: c.ExecutionID,
Name: c.saga.Name,
Time: time.Now(),
Type: LogTypeStartSaga,
}))
for i := 0; i < len(c.saga.steps); i++ {
c.execStep(i)
}
checkErr(c.logStore.AppendLog(&Log{
ExecutionID: c.ExecutionID,
Name: c.saga.Name,
Time: time.Now(),
Type: LogTypeSagaComplete,
StepDuration: time.Since(executionStart),
}))
return &Result{ExecutionError: c.executionError, CompensateErrors: c.compensateErrors}
}
func (c *ExecutionCoordinator) execStep(i int) {
if c.aborted {
return
}
start := time.Now()
f := c.saga.steps[i].Func
params := []reflect.Value{reflect.ValueOf(c.funcsCtx)}
resp := getFuncValue(f).Call(params)
err := isReturnError(resp)
marshaledResp, marshalErr := marshalResp(resp[:len(resp)-1])
checkErr(marshalErr)
stepLog := &Log{
ExecutionID: c.ExecutionID,
Name: c.saga.Name,
Time: time.Now(),
Type: LogTypeSagaStepExec,
StepNumber: &i,
StepName: &c.saga.steps[i].Name,
StepPayload: marshaledResp,
StepDuration: time.Since(start),
}
if err != nil {
errStr := err.Error()
stepLog.StepError = &errStr
}
checkErr(c.logStore.AppendLog(stepLog))
stepLog.StepDuration = time.Since(start)
if err != nil {
c.executionError = err
c.abort()
}
}
func marshalResp(resp []reflect.Value) ([]byte, error) {
slice := make([]interface{}, 0, len(resp))
for _, value := range resp {
slice = append(slice, value.Interface())
}
return json.Marshal(slice)
}
func (c *ExecutionCoordinator) abort() {
toCompensateLogs, err := c.logStore.GetStepLogsToCompensate(c.ExecutionID)
checkErr(err, "c.logStore.GetAllLogsByExecutionID(c.ExecutionID)")
stepsToCompensate := len(toCompensateLogs)
checkErr(c.logStore.AppendLog(&Log{
ExecutionID: c.ExecutionID,
Name: c.saga.Name,
Time: time.Now(),
Type: LogTypeSagaAbort,
StepNumber: &stepsToCompensate,
}))
c.aborted = true
for i := 0; i < stepsToCompensate; i++ {
toCompensateLog := toCompensateLogs[i]
compensateFuncRaw := c.saga.steps[*toCompensateLog.StepNumber].CompensateFunc
compensateFuncValue := getFuncValue(compensateFuncRaw)
compensateRuncType := reflect.TypeOf(compensateFuncRaw)
types := make([]reflect.Type, 0, compensateRuncType.NumIn())
for i := 1; i < compensateRuncType.NumIn(); i++ {
types = append(types, compensateRuncType.In(i))
}
unmarshal, err := unmarshalParams(types, toCompensateLog.StepPayload)
checkErr(err, "unmarshalParams()")
params := make([]reflect.Value, 0)
params = append(params, reflect.ValueOf(c.compensateFuncsCtx))
params = append(params, unmarshal...)
if err := c.compensateStep(*toCompensateLog.StepNumber, params, compensateFuncValue); err != nil {
c.compensateErrors = append(c.compensateErrors, err)
}
}
}
func unmarshalParams(types []reflect.Type, payload []byte) ([]reflect.Value, error) {
rawVals := make([]interface{}, 0, len(types))
for _, typ := range types {
rawVals = append(rawVals, reflect.New(typ).Interface())
}
checkErr(json.Unmarshal(payload, &rawVals), "json.Unmarshal(payload, &rawVals)")
res := make([]reflect.Value, 0, len(types))
for i := 0; i < len(rawVals); i++ {
objV := reflect.ValueOf(rawVals[i])
if rawVals[i] == nil {
objV = reflect.Zero(types[i])
} else if reflect.TypeOf(rawVals[i]).Kind() == reflect.Ptr && objV.Type() != types[i] {
objV = objV.Elem()
}
res = append(res, objV)
}
return res, nil
}
func (c *ExecutionCoordinator) compensateStep(i int, params []reflect.Value, compensateFunc reflect.Value) error {
checkErr(c.logStore.AppendLog(&Log{
ExecutionID: c.ExecutionID,
Name: c.saga.Name,
Time: time.Now(),
Type: LogTypeSagaStepCompensate,
StepNumber: &i,
StepName: &c.saga.steps[i].Name,
}))
res := compensateFunc.Call(params)
if err := isReturnError(res); err != nil {
return err
}
return nil
}
func isReturnError(result []reflect.Value) error {
if len(result) > 0 && !result[len(result)-1].IsNil() {
return result[len(result)-1].Interface().(error)
}
return nil
}
func getFuncValue(obj interface{}) reflect.Value {
funcValue := reflect.ValueOf(obj)
checkOK(funcValue.Kind() == reflect.Func, fmt.Sprintf("registered object must be a func but was %s", funcValue.Kind()))
checkOK(funcValue.Type().NumIn() >= 1 && funcValue.Type().In(0) == reflect.TypeOf((*context.Context)(nil)).Elem(), "invalid func")
return funcValue
}
func checkErr(err error, msg ...string) {
if err != nil {
log.Panicln(msg, err)
}
}
func checkOK(ok bool, msg ...string) {
if !ok {
log.Panicln(msg)
}
}
// RandString simply generates random string of length n
func RandString() string {
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]rune, 10)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}