forked from infobloxopen/atlas-app-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransaction.go
179 lines (154 loc) · 4.69 KB
/
transaction.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 gorm
import (
"context"
"errors"
"reflect"
"sync"
netctx "golang.org/x/net/context"
"github.com/infobloxopen/atlas-app-toolkit/rpc/errdetails"
"github.com/jinzhu/gorm"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// ctxKey is an unexported type for keys defined in this package.
// This prevents collisions with keys defined in other packages.
type ctxKey int
// txnKey is the key for `*Transaction` values in `context.Context`.
// It is unexported; clients use NewContext and FromContext
// instead of using this key directly.
var txnKey ctxKey
var (
ErrCtxTxnMissing = errors.New("Database transaction for request missing in context")
ErrCtxTxnNoDB = errors.New("Transaction in context, but DB is nil")
)
// NewContext returns a new Context that carries value txn.
func NewContext(parent context.Context, txn *Transaction) context.Context {
return context.WithValue(parent, txnKey, txn)
}
// FromContext returns the *Transaction value stored in ctx, if any.
func FromContext(ctx context.Context) (txn *Transaction, ok bool) {
txn, ok = ctx.Value(txnKey).(*Transaction)
return
}
// Transaction serves as a wrapper around `*gorm.DB` instance.
// It works as a singleton to prevent an application of creating more than one
// transaction instance per incoming request.
type Transaction struct {
mu sync.Mutex
parent *gorm.DB
current *gorm.DB
afterCommitHook []func(context.Context)
}
func NewTransaction(db *gorm.DB) Transaction {
return Transaction{parent: db}
}
func (t *Transaction) AddAfterCommitHook(hooks ...func(context.Context)) {
t.afterCommitHook = append(t.afterCommitHook, hooks...)
}
func BeginFromContext(ctx context.Context) (*gorm.DB, error) {
txn, ok := FromContext(ctx)
if !ok {
return nil, ErrCtxTxnMissing
}
if txn.parent == nil {
return nil, ErrCtxTxnNoDB
}
db := txn.Begin()
if db.Error != nil {
return nil, db.Error
}
return db, nil
}
// Begin starts new transaction by calling `*gorm.DB.Begin()`
// Returns new instance of `*gorm.DB` (error can be checked by `*gorm.DB.Error`)
func (t *Transaction) Begin() *gorm.DB {
t.mu.Lock()
defer t.mu.Unlock()
if t.current == nil {
t.current = t.parent.Begin()
}
return t.current
}
// Rollback terminates transaction by calling `*gorm.DB.Rollback()`
// Reset current transaction and returns an error if any.
func (t *Transaction) Rollback() error {
if t.current == nil {
return nil
}
if reflect.ValueOf(t.current.CommonDB()).IsNil() {
return status.Error(codes.Unavailable, "Database connection not available")
}
t.mu.Lock()
defer t.mu.Unlock()
t.current.Rollback()
err := t.current.Error
t.current = nil
return err
}
// Commit finishes transaction by calling `*gorm.DB.Commit()`
// Reset current transaction and returns an error if any.
func (t *Transaction) Commit(ctx context.Context) error {
if t.current == nil || reflect.ValueOf(t.current.CommonDB()).IsNil() {
return nil
}
t.mu.Lock()
defer t.mu.Unlock()
t.current.Commit()
err := t.current.Error
if err == nil {
for i := range t.afterCommitHook {
t.afterCommitHook[i](ctx)
}
}
t.current = nil
return err
}
// UnaryServerInterceptor returns grpc.UnaryServerInterceptor that manages
// a `*Transaction` instance.
// New *Transaction instance is created before grpc.UnaryHandler call.
// Client is responsible to call `txn.Begin()` to open transaction.
// If call of grpc.UnaryHandler returns with an error the transaction
// is aborted, otherwise committed.
func UnaryServerInterceptor(db *gorm.DB) grpc.UnaryServerInterceptor {
return func(ctx netctx.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
// prepare new *Transaction instance
txn := &Transaction{parent: db}
defer func() {
// simple panic handler
if perr := recover(); perr != nil {
// we do not try to safe the world -
// just attempt to close our transaction
// re-raise panic and let someone to handle it
txn.Rollback()
panic(perr)
}
var terr error
if err != nil {
terr = txn.Rollback()
} else {
if terr = txn.Commit(ctx); terr != nil {
err = status.Error(codes.Internal, "failed to commit transaction")
}
}
if terr == nil {
return
}
// Catch the status: UNAVAILABLE error that Rollback might return
if _, ok := status.FromError(terr); ok {
err = terr
return
}
st := status.Convert(err)
st, serr := st.WithDetails(errdetails.New(codes.Internal, "gorm", terr.Error()))
// do not override error if failed to attach details
if serr == nil {
err = st.Err()
}
return
}()
ctx = NewContext(ctx, txn)
resp, err = handler(ctx, req)
return resp, err
}
}