This repository has been archived by the owner on Apr 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 58
/
saga.go
179 lines (159 loc) · 4.2 KB
/
saga.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
// Package saga provide a framework for Saga-pattern to solve distribute transaction problem.
// In saga-pattern, Saga is a long-lived transaction came up with many small sub-transaction.
// ExecutionCoordinator(SEC) is coordinator for sub-transactions execute and saga-log written.
// Sub-transaction is normal business operation, it contain a Action and action's Compensate.
// Saga-Log is used to record saga process, and SEC will use it to decide next step and how to recovery from error.
//
// There is a great speak for Saga-pattern at https://www.youtube.com/watch?v=xDuwrtwYHu8
package saga
import (
"reflect"
"time"
"github.com/lysu/go-saga/storage"
"golang.org/x/net/context"
"log"
"os"
)
const LogPrefix = "saga_"
var Logger *log.Logger
var StorageConfig storage.StorageConfig
var StorageProvider storage.StorageProvider
func LogStorage() storage.Storage {
return StorageProvider(StorageConfig)
}
func init() {
Logger = log.New(os.Stdout, "[Saga]", log.LstdFlags)
}
func SetLogger(l *log.Logger) {
Logger = l
}
// Saga presents current execute transaction.
// A Saga constituted by small sub-transactions.
type Saga struct {
id uint64
logID string
context context.Context
sec *ExecutionCoordinator
}
func (s *Saga) startSaga() {
log := &Log{
Type: SagaStart,
Time: time.Now(),
}
err := LogStorage().AppendLog(s.logID, log.mustMarshal())
if err != nil {
panic("Add log Failure")
}
}
// ExecSub executes a sub-transaction for given subTxID(which define in SEC initialize) and arguments.
// it returns current Saga.
func (s *Saga) ExecSub(subTxID string, args ...interface{}) *Saga {
subTxDef := s.sec.MustFindSubTxDef(subTxID)
log := &Log{
Type: ActionStart,
SubTxID: subTxID,
Time: time.Now(),
Params: MarshalParam(s.sec, args),
}
err := LogStorage().AppendLog(s.logID, log.mustMarshal())
if err != nil {
panic("Add log Failure")
}
params := make([]reflect.Value, 0, len(args)+1)
params = append(params, reflect.ValueOf(s.context))
for _, arg := range args {
params = append(params, reflect.ValueOf(arg))
}
result := subTxDef.action.Call(params)
if isReturnError(result) {
s.Abort()
return s
}
log = &Log{
Type: ActionEnd,
SubTxID: subTxID,
Time: time.Now(),
}
err = LogStorage().AppendLog(s.logID, log.mustMarshal())
if err != nil {
panic("Add log Failure")
}
return s
}
// EndSaga finishes a Saga's execution.
func (s *Saga) EndSaga() {
log := &Log{
Type: SagaEnd,
Time: time.Now(),
}
err := LogStorage().AppendLog(s.logID, log.mustMarshal())
if err != nil {
panic("Add log Failure")
}
err = LogStorage().Cleanup(s.logID)
if err != nil {
panic("Clean up topic failure")
}
}
// Abort stop and compensate to rollback to start situation.
// This method will stop continue sub-transaction and do Compensate for executed sub-transaction.
// SubTx will call this method internal.
func (s *Saga) Abort() {
logs, err := LogStorage().Lookup(s.logID)
if err != nil {
panic("Abort Panic")
}
alog := &Log{
Type: SagaAbort,
Time: time.Now(),
}
err = LogStorage().AppendLog(s.logID, alog.mustMarshal())
if err != nil {
panic("Add log Failure")
}
for i := len(logs) - 1; i >= 0; i-- {
logData := logs[i]
log := mustUnmarshalLog(logData)
if log.Type == ActionStart {
if err := s.compensate(log); err != nil {
panic("Compensate Failure..")
}
}
}
}
func (s *Saga) compensate(tlog Log) error {
clog := &Log{
Type: CompensateStart,
SubTxID: tlog.SubTxID,
Time: time.Now(),
}
err := LogStorage().AppendLog(s.logID, clog.mustMarshal())
if err != nil {
panic("Add log Failure")
}
args := UnmarshalParam(s.sec, tlog.Params)
params := make([]reflect.Value, 0, len(args)+1)
params = append(params, reflect.ValueOf(s.context))
params = append(params, args...)
subDef := s.sec.MustFindSubTxDef(tlog.SubTxID)
result := subDef.compensate.Call(params)
if isReturnError(result) {
s.Abort()
}
clog = &Log{
Type: CompensateEnd,
SubTxID: tlog.SubTxID,
Time: time.Now(),
}
err = LogStorage().AppendLog(s.logID, clog.mustMarshal())
if err != nil {
panic("Add log Failure")
}
return nil
}
func isReturnError(result []reflect.Value) bool {
if len(result) == 1 && !result[0].IsNil() {
return true
}
return false
}