-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstate_machine.go
48 lines (39 loc) · 1016 Bytes
/
state_machine.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
package saga
import (
"context"
"errors"
)
var (
errDuplicateState = errors.New("saga: duplicate state")
errInvalidStateChange = errors.New("saga: invalid state change")
errNoAggregator = errors.New("saga: no aggregator found")
)
type smImpl struct {
aggMap map[State]Aggregator
validChanges map[State]map[State]bool
}
func (s *smImpl) run(ctx context.Context, tx Transaction) (Transaction, error) {
agg := s.aggMap[tx.State()]
if agg == nil {
return nil, errNoAggregator
}
nextTx, err := agg.Execute(ctx, tx)
if err != nil {
return nil, err
}
if !s.validChanges[tx.State()][nextTx.State()] {
return nil, errInvalidStateChange
}
return nextTx, nil
}
func (s *smImpl) addState(state State, agg Aggregator, validNextStates ...State) error {
if s.aggMap[state] != nil {
return errDuplicateState
}
s.aggMap[state] = agg
s.validChanges[state] = map[State]bool{}
for _, validState := range validNextStates {
s.validChanges[state][validState] = true
}
return nil
}