forked from infobloxopen/atlas-app-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
290 lines (251 loc) · 8.48 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
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package gorm
import (
"context"
"database/sql"
"errors"
"reflect"
"sync"
"github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/infobloxopen/atlas-app-toolkit/v2/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...)
}
// BeginFromContext will extract transaction wrapper from context and start new transaction.
// As result new instance of `*gorm.DB` will be returned.
// Error will be returned in case either transaction or db connection info is missing in context.
// Gorm specific error can be checked by `*gorm.DB.Error`.
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.beginWithContext(ctx)
if db.Error != nil {
return nil, db.Error
}
return db, nil
}
// BeginWithOptionsFromContext will extract transaction wrapper from context and start new transaction,
// options can be specified to control isolation level for transaction.
// As result new instance of `*gorm.DB` will be returned.
// Error will be returned in case either transaction or db connection info is missing in context.
// Gorm specific error can be checked by `*gorm.DB.Error`.
func BeginWithOptionsFromContext(ctx context.Context, opts *sql.TxOptions) (*gorm.DB, error) {
txn, ok := FromContext(ctx)
if !ok {
return nil, ErrCtxTxnMissing
}
if txn.parent == nil {
return nil, ErrCtxTxnNoDB
}
db := txn.beginWithContextAndOptions(ctx, opts)
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 {
return t.beginWithContext(context.Background())
}
func (t *Transaction) beginWithContext(ctx context.Context) *gorm.DB {
t.mu.Lock()
defer t.mu.Unlock()
if t.current == nil {
t.current = t.parent.BeginTx(ctx, nil)
}
return t.current
}
// BeginWithOptions starts new transaction by calling `*gorm.DB.BeginTx()`
// Returns new instance of `*gorm.DB` (error can be checked by `*gorm.DB.Error`)
func (t *Transaction) BeginWithOptions(opts *sql.TxOptions) *gorm.DB {
return t.beginWithContextAndOptions(context.Background(), opts)
}
func (t *Transaction) beginWithContextAndOptions(ctx context.Context, opts *sql.TxOptions) *gorm.DB {
t.mu.Lock()
defer t.mu.Unlock()
if t.current == nil {
t.current = t.parent.BeginTx(ctx, opts)
}
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 {
t.mu.Lock()
defer t.mu.Unlock()
if t.current == nil {
return nil
}
if reflect.ValueOf(t.current.CommonDB()).IsNil() {
return status.Error(codes.Unavailable, "Database connection not available")
}
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 {
t.mu.Lock()
defer t.mu.Unlock()
if t.current == nil || reflect.ValueOf(t.current.CommonDB()).IsNil() {
return nil
}
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 {
txn := &Transaction{parent: db}
return UnaryServerInterceptorTxn(txn)
}
func UnaryServerInterceptorTxn(txn *Transaction) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
// Deep copy is necessary as a tansaction should be created per request.
txn := &Transaction{parent: txn.parent, afterCommitHook: txn.afterCommitHook}
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
}
}
// StreamServerInterceptor returns grpc.StreamServerInterceptor that manages
// a `*Transaction` instance.
// New *Transaction instance is created before grpc.StreamHandler call.
// Client is responsible to call `txn.Begin()` to open transaction.
// If call of grpc.StreamHandler returns with an error the transaction
// is aborted, otherwise committed.
func StreamServerInterceptor(db *gorm.DB) grpc.StreamServerInterceptor {
txn := &Transaction{parent: db}
return StreamServerInterceptorTxn(txn)
}
func StreamServerInterceptorTxn(txn *Transaction) grpc.StreamServerInterceptor {
return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
// Deep copy is necessary as a tansaction should be created per request.
txn := &Transaction{parent: txn.parent, afterCommitHook: txn.afterCommitHook}
ctx := NewContext(stream.Context(), txn)
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()
}
}()
wrapped := grpc_middleware.WrapServerStream(stream)
wrapped.WrappedContext = ctx
err = handler(srv, wrapped)
return err
}
}