forked from etcd-io/etcd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
batcher.go
72 lines (59 loc) · 1.26 KB
/
batcher.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
package rafthttp
import (
"time"
"github.com/coreos/etcd/raft/raftpb"
)
var (
emptyMsgProp = raftpb.Message{Type: raftpb.MsgProp}
)
type Batcher struct {
batchedN int
batchedT time.Time
batchN int
batchD time.Duration
}
func NewBatcher(n int, d time.Duration) *Batcher {
return &Batcher{
batchN: n,
batchD: d,
batchedT: time.Now(),
}
}
func (b *Batcher) ShouldBatch(now time.Time) bool {
b.batchedN++
batchedD := now.Sub(b.batchedT)
if b.batchedN >= b.batchN || batchedD >= b.batchD {
b.Reset(now)
return false
}
return true
}
func (b *Batcher) Reset(t time.Time) {
b.batchedN = 0
b.batchedT = t
}
func canBatch(m raftpb.Message) bool {
return m.Type == raftpb.MsgAppResp && m.Reject == false
}
type ProposalBatcher struct {
*Batcher
raftpb.Message
}
func NewProposalBatcher(n int, d time.Duration) *ProposalBatcher {
return &ProposalBatcher{
Batcher: NewBatcher(n, d),
Message: emptyMsgProp,
}
}
func (b *ProposalBatcher) Batch(m raftpb.Message) {
b.Message.From = m.From
b.Message.To = m.To
b.Message.Entries = append(b.Message.Entries, m.Entries...)
}
func (b *ProposalBatcher) IsEmpty() bool {
return len(b.Message.Entries) == 0
}
func (b *ProposalBatcher) Reset(t time.Time) {
b.Batcher.Reset(t)
b.Message = emptyMsgProp
}