forked from fagongzi/manba
-
Notifications
You must be signed in to change notification settings - Fork 0
/
txn.go
58 lines (48 loc) · 1.14 KB
/
txn.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
package store
import (
"time"
"github.com/coreos/etcd/clientv3"
"github.com/fagongzi/log"
"golang.org/x/net/context"
)
// slowLogTxn wraps etcd transaction and log slow one.
type slowLogTxn struct {
clientv3.Txn
cancel context.CancelFunc
}
func newSlowLogTxn(client *clientv3.Client) clientv3.Txn {
ctx, cancel := context.WithTimeout(client.Ctx(), DefaultRequestTimeout)
return &slowLogTxn{
Txn: client.Txn(ctx),
cancel: cancel,
}
}
func (t *slowLogTxn) If(cs ...clientv3.Cmp) clientv3.Txn {
return &slowLogTxn{
Txn: t.Txn.If(cs...),
cancel: t.cancel,
}
}
func (t *slowLogTxn) Then(ops ...clientv3.Op) clientv3.Txn {
return &slowLogTxn{
Txn: t.Txn.Then(ops...),
cancel: t.cancel,
}
}
// Commit implements Txn Commit interface.
func (t *slowLogTxn) Commit() (*clientv3.TxnResponse, error) {
start := time.Now()
resp, err := t.Txn.Commit()
t.cancel()
cost := time.Now().Sub(start)
if cost > DefaultSlowRequestTime {
log.Warn("slow: txn runs too slow, resp=<%v> cost=<%s> errors:\n %+v",
resp,
cost,
err)
}
return resp, err
}
func (e *EtcdStore) txn() clientv3.Txn {
return newSlowLogTxn(e.rawClient)
}