-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate_bolt.go
78 lines (69 loc) · 1.96 KB
/
state_bolt.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
package raft
import (
"encoding/binary"
"github.com/ugorji/go/codec"
"go.etcd.io/bbolt"
)
const (
boltStateStoreBucketStates = "states"
boltStateStoreKeyCurrentTerm = "current_term"
boltStateStoreKeyLastVote = "last_vote"
)
type BoltStateStore struct {
db *bbolt.DB
}
func NewBoltStateStore(db *bbolt.DB) *BoltStateStore {
return &BoltStateStore{db: db}
}
func (s *BoltStateStore) CurrentTerm() (uint64, error) {
currentTerm := uint64(0)
if err := s.db.View(func(t *bbolt.Tx) error {
if bucket := t.Bucket([]byte(boltStateStoreBucketStates)); bucket != nil {
if b := bucket.Get([]byte(boltStateStoreKeyCurrentTerm)); b != nil {
currentTerm = binary.BigEndian.Uint64(b)
}
}
return nil
}); err != nil {
return 0, err
}
return currentTerm, nil
}
func (s *BoltStateStore) SetCurrentTerm(currentTerm uint64) error {
return s.db.Update(func(t *bbolt.Tx) error {
bucket, err := t.CreateBucketIfNotExists([]byte(boltStateStoreBucketStates))
if err != nil {
return nil
}
return bucket.Put([]byte(boltStateStoreKeyCurrentTerm), EncodeUint64(currentTerm))
})
}
func (s *BoltStateStore) LastVote() (voteSummary, error) {
summary := nilVoteSummary
if err := s.db.View(func(t *bbolt.Tx) error {
if bucket := t.Bucket([]byte(boltStateStoreBucketStates)); bucket != nil {
if b := bucket.Get([]byte(boltStateStoreKeyLastVote)); b != nil {
if err := codec.NewDecoderBytes(b, &codec.MsgpackHandle{}).Decode(&summary); err != nil {
return err
}
}
}
return nil
}); err != nil {
return nilVoteSummary, err
}
return summary, nil
}
func (s *BoltStateStore) SetLastVote(summary voteSummary) error {
return s.db.Update(func(t *bbolt.Tx) error {
bucket, err := t.CreateBucketIfNotExists([]byte(boltStateStoreBucketStates))
if err != nil {
return nil
}
var b []byte
if err := codec.NewEncoderBytes(&b, &codec.MsgpackHandle{}).Encode(b); err != nil {
return err
}
return bucket.Put([]byte(boltStateStoreKeyLastVote), b)
})
}