forked from zeromicro/go-zero
/
statewatcher.go
65 lines (55 loc) · 1.35 KB
/
statewatcher.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
//go:generate mockgen -package internal -destination statewatcher_mock.go -source statewatcher.go etcdConn
package internal
import (
"context"
"sync"
"google.golang.org/grpc/connectivity"
)
type (
etcdConn interface {
GetState() connectivity.State
WaitForStateChange(ctx context.Context, sourceState connectivity.State) bool
}
stateWatcher struct {
disconnected bool
currentState connectivity.State
listeners []func()
// lock only guards listeners, because only listens can be accessed by other goroutines.
lock sync.Mutex
}
)
func newStateWatcher() *stateWatcher {
return new(stateWatcher)
}
func (sw *stateWatcher) addListener(l func()) {
sw.lock.Lock()
sw.listeners = append(sw.listeners, l)
sw.lock.Unlock()
}
func (sw *stateWatcher) notifyListeners() {
sw.lock.Lock()
defer sw.lock.Unlock()
for _, l := range sw.listeners {
l()
}
}
func (sw *stateWatcher) updateState(conn etcdConn) {
sw.currentState = conn.GetState()
switch sw.currentState {
case connectivity.TransientFailure, connectivity.Shutdown:
sw.disconnected = true
case connectivity.Ready:
if sw.disconnected {
sw.disconnected = false
sw.notifyListeners()
}
}
}
func (sw *stateWatcher) watch(conn etcdConn) {
sw.currentState = conn.GetState()
for {
if conn.WaitForStateChange(context.Background(), sw.currentState) {
sw.updateState(conn)
}
}
}