-
Notifications
You must be signed in to change notification settings - Fork 0
/
step.go
245 lines (231 loc) · 7.64 KB
/
step.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
package opinionatedsagas
import (
"context"
"database/sql"
"errors"
"fmt"
"reflect"
"time"
events "github.com/markusylisiurunen/go-opinionatedevents"
)
type Step struct {
db *sql.DB
schema string
publisher *events.Publisher
receiver *events.Receiver
queue string
HandleFunc any
CompensateFunc any
MaxAttempts int
}
func (s *Step) init(db *sql.DB, schema string, publisher *events.Publisher, receiver *events.Receiver, queue string) {
s.db = db
s.schema = schema
s.publisher = publisher
s.receiver = receiver
s.queue = queue
}
func (s *Step) getMaxAttempts() int {
return s.MaxAttempts
}
func (s *Step) isForTask(task task) bool {
handleFuncValue := reflect.ValueOf(s.HandleFunc)
return handleFuncValue.Type().In(1) == reflect.TypeOf(task)
}
func (s *Step) isValid() error {
if err := s.handleFuncIsValid(); err != nil {
return err
}
if err := s.compensateFuncIsValid(); err != nil {
return err
}
return nil
}
func (s *Step) handleFuncIsValid() error {
if s.HandleFunc == nil {
return errors.New("the handle func must be provided")
}
funcValue := reflect.ValueOf(s.HandleFunc)
// get the count of function arguments and return values
inCount := funcValue.Type().NumIn()
outCount := funcValue.Type().NumOut()
// validate all cases of 2 arguments
if inCount == 2 {
if !isInterface[context.Context](funcValue.Type().In(0)) {
return errors.New("the first handle func argument must implement 'context.Context'")
}
if !isInterface[task](funcValue.Type().In(1)) {
return errors.New("the second handle func argument must implement 'task'")
}
// validate the case of 2 -> 1
if outCount == 1 {
if !isInterface[error](funcValue.Type().Out(0)) {
return errors.New("the first handle func return value must implement 'error'")
}
return nil
}
// validate the case of 2 -> 3
if outCount == 3 {
if !isInterface[task](funcValue.Type().Out(0)) {
return errors.New("the first handle func return value must implement 'task'")
}
if !isInterface[task](funcValue.Type().Out(1)) {
return errors.New("the second handle func return value must implement 'task'")
}
if !isInterface[error](funcValue.Type().Out(2)) {
return errors.New("the third handle func return value must implement 'error'")
}
return nil
}
}
return errors.New("an unknown combination of handle func arguments and return values")
}
func (s *Step) compensateFuncIsValid() error {
if s.CompensateFunc == nil {
return nil
}
funcValue := reflect.ValueOf(s.CompensateFunc)
// get the count of function arguments and return values
inCount := funcValue.Type().NumIn()
outCount := funcValue.Type().NumOut()
// validate the case of 2 -> 1
if inCount == 2 && outCount == 1 {
if !isInterface[context.Context](funcValue.Type().In(0)) {
return errors.New("the first compensate func argument must implement 'context.Context'")
}
if !isInterface[task](funcValue.Type().In(1)) {
return errors.New("the second compensate func argument must implement 'task'")
}
if !isInterface[error](funcValue.Type().Out(0)) {
return errors.New("the first compensate func return value must implement 'error'")
}
return nil
}
return errors.New("an unknown combination of compensate func arguments and return values")
}
func (s *Step) mountHandleFunc() error {
name := reflect.New(reflect.ValueOf(s.HandleFunc).Type().In(1).Elem()).Interface().(task).TaskName()
handle := func(ctx context.Context, delivery events.Delivery) error {
handleFuncValue := reflect.ValueOf(s.HandleFunc)
handleFuncTaskType := handleFuncValue.Type().In(1)
// initialize an empty task (based on the handle func's parameter type)
taskMessage := newTaskMessage(reflect.New(handleFuncTaskType.Elem()).Interface().(task))
// attempt to parse the payload
if err := delivery.GetMessage().GetPayload(taskMessage); err != nil {
// TODO: what to do if the message could not be parsed?
return err
}
// execute the handle func with the task
outValue := reflect.ValueOf(s.HandleFunc).Call([]reflect.Value{
reflect.ValueOf(ctx),
reflect.ValueOf(taskMessage.Task),
})
var (
resultValue reflect.Value
compensateTaskValue reflect.Value
nextTaskValue reflect.Value
)
if len(outValue) == 1 {
resultValue = outValue[0]
// check the result, if it's not success, return it right away
if !resultValue.IsNil() {
return resultValue.Interface().(error)
}
return nil
}
if len(outValue) == 3 {
compensateTaskValue = outValue[0]
nextTaskValue = outValue[1]
resultValue = outValue[2]
// check the result, if it's not success, return it right away
if !resultValue.IsNil() {
return resultValue.Interface().(error)
}
}
// if there is no next task to be published, just return the result
if nextTaskValue.IsNil() {
return nil
}
// construct and publish the next task
rollbackHistory := taskMessage.RollbackStack.copy()
if !compensateTaskValue.IsNil() {
compensateTaskMessage := newTaskMessage(compensateTaskValue.Interface().(task))
rollbackHistory.push(compensateTaskMessage.asRollbackStackItem())
}
nextTaskMessage := newTaskMessageWithRollbackHistory(
nextTaskValue.Interface().(task),
rollbackHistory,
)
nextTaskOpinionatedMessage, err := nextTaskMessage.toOpinionatedMessage()
if err != nil {
// FIXME: this entire function must be somehow atomic
return err
}
if err := s.publisher.Publish(ctx, nextTaskOpinionatedMessage); err != nil {
// FIXME: this entire function must be somehow atomic
return err
}
// return the result
return nil
}
return s.receiver.On(s.queue, fmt.Sprintf("tasks.%s", name),
middlewares{
// 10s, 15s, 30s, 1m21s, 4m11s, 13m35s, 30m0s, 30m0s
events.WithBackoff(events.ExponentialBackoff(10, 2, 1.2, 30*time.Minute)),
withRollback(s.publisher, s.getMaxAttempts()),
withIdempotent(s.db, s.schema),
}.
wrap(handle),
)
}
func (s *Step) mountCompensateFunc() error {
if s.CompensateFunc == nil {
return nil
}
name := reflect.New(reflect.ValueOf(s.CompensateFunc).Type().In(1).Elem()).Interface().(task).TaskName()
handle := func(ctx context.Context, delivery events.Delivery) error {
compensateFuncValue := reflect.ValueOf(s.CompensateFunc)
compensateFuncTaskType := compensateFuncValue.Type().In(1)
// initialize an empty task (based on the handle func's parameter type)
taskMessage := newTaskMessage(reflect.New(compensateFuncTaskType.Elem()).Interface().(task))
// attempt to parse the payload
if err := delivery.GetMessage().GetPayload(taskMessage); err != nil {
// TODO: what to do if the message could not be parsed?
return err
}
// execute the handle func with the task
outValue := reflect.ValueOf(s.CompensateFunc).Call([]reflect.Value{
reflect.ValueOf(ctx),
reflect.ValueOf(taskMessage.Task),
})
resultValue := outValue[0]
// check the result, if it's not success, return it right away
if !resultValue.IsNil() {
return resultValue.Interface().(error)
}
// success, publish the next rollback message from the stack
rollbackMessage, ok := taskMessage.rollback()
if !ok {
return nil
}
rollbackOpinionatedMessage, err := rollbackMessage.toOpinionatedMessage()
if err != nil {
// FIXME: this entire function must be somehow atomic
return err
}
if err := s.publisher.Publish(ctx, rollbackOpinionatedMessage); err != nil {
// FIXME: this entire function must be somehow atomic
return err
}
// return the result
return nil
}
return s.receiver.On(s.queue, fmt.Sprintf("tasks.%s", name),
middlewares{
// 10s, 15s, 30s, 1m21s, 4m11s, 13m35s, 30m0s, 30m0s
events.WithBackoff(events.ExponentialBackoff(10, 2, 1.2, 30*time.Minute)),
withIdempotent(s.db, s.schema),
}.
wrap(handle),
)
}