-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmember.go
84 lines (71 loc) · 1.34 KB
/
member.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
package swimy
import (
"net"
"slices"
"time"
)
type memberState int
const (
statusUnknown memberState = iota
statusAlive
statusDead
statusSuspect
statusLeft
)
type Member struct {
addr net.Addr
state memberState
since time.Time
}
func newAliveMember(addr net.Addr) Member {
return Member{
addr: addr,
state: statusAlive,
since: time.Now().UTC(),
}
}
func (m Member) Addr() net.Addr {
return m.addr
}
func (ms *Membership) alives(excludes ...net.Addr) []Member {
ms.membersMu.RLock()
defer ms.membersMu.RUnlock()
var res []Member
for _, m := range ms.others {
if slices.Contains(excludes, m.Addr()) {
continue
}
if m.state == statusAlive {
res = append(res, m)
}
}
return res
}
func (ms *Membership) setAlives(members ...Member) {
ms.membersMu.Lock()
defer ms.membersMu.Unlock()
now := time.Now().UTC()
for _, m := range members {
m.state = statusAlive
m.since = now
}
}
func (ms *Membership) setState(state memberState, addrs ...net.Addr) {
ms.membersMu.Lock()
defer ms.membersMu.Unlock()
now := time.Now().UTC()
for _, addr := range addrs {
if m, ok := ms.others[addr]; ok {
m.state = state
m.since = now
ms.others[addr] = m
}
}
}
func (ms *Membership) becomeMembers(members ...Member) {
ms.membersMu.Lock()
for _, m := range members {
ms.others[m.Addr()] = m
}
ms.membersMu.Unlock()
}