-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstate.go
More file actions
88 lines (73 loc) · 1.33 KB
/
state.go
File metadata and controls
88 lines (73 loc) · 1.33 KB
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
package election
import (
"sync"
"sync/atomic"
)
type Role uint32
const (
Leader = iota
Follower
Candidate
Shutdown
)
func (r Role) String() string {
switch r {
case Leader:
return "Leader"
case Follower:
return "Follower"
case Candidate:
return "Candidate"
case Shutdown:
return "Shutdown"
default:
return "Unknown"
}
}
type Stat struct {
Term uint64
Role Role
}
type state struct {
currentTerm uint64
currentRole Role
vote map[uint64]struct{}
mu sync.RWMutex
}
func newState() *state {
return &state{
currentTerm: 0,
currentRole: Shutdown,
vote: make(map[uint64]struct{}),
}
}
func (s *state) stat() Stat {
s.mu.Lock()
defer s.mu.Unlock()
return Stat{s.currentTerm, s.currentRole}
}
func (s *state) voted(term uint64) bool {
s.mu.RLock()
defer s.mu.RUnlock()
_, ok := s.vote[term]
return ok
}
func (s *state) voting(term uint64) {
s.mu.Lock()
defer s.mu.Unlock()
s.vote[term] = struct{}{}
}
func (s *state) term() uint64 {
return atomic.LoadUint64(&s.currentTerm)
}
func (s *state) setTerm(term uint64) {
atomic.StoreUint64(&s.currentTerm, term)
}
func (s *state) role() Role {
roleAddr := (*uint32)(&s.currentRole)
return Role(atomic.LoadUint32(roleAddr))
}
func (s *state) setRole(r Role) {
stateAddr := (*uint32)(&s.currentRole)
atomic.StoreUint32(stateAddr, uint32(r))
}