-
Notifications
You must be signed in to change notification settings - Fork 9
/
observer.go
71 lines (58 loc) · 2.01 KB
/
observer.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
package ckit
import (
"sort"
"github.com/grafana/ckit/peer"
)
// An Observer watches a Node, waiting for its peers to change.
type Observer interface {
// NotifyPeersChanged is invoked any time the set of Peers for a node
// changes. The slice of peers should not be modified.
//
// The real list of peers may have changed; call Node.Peers to get the
// current list.
//
// If NotifyPeersChanged returns false, the Observer will no longer receive
// any notifications. This can be used for single-use watches.
NotifyPeersChanged(peers []peer.Peer) (reregister bool)
}
// FuncObserver implements Observer.
type FuncObserver func(peers []peer.Peer) (reregister bool)
// NotifyPeersChanged implements Observer.
func (f FuncObserver) NotifyPeersChanged(peers []peer.Peer) (reregister bool) { return f(peers) }
// ParticipantObserver wraps an observer and filters out events where the list
// of peers in the Participants state haven't changed. When the set of
// participants have changed, next.NotifyPeersChanged will be invoked with the
// full set of peers (i.e., not just participants).
func ParticipantObserver(next Observer) Observer {
return &participantObserver{next: next}
}
type participantObserver struct {
lastParticipants []peer.Peer // Participants ordered by name
next Observer
}
func (po *participantObserver) NotifyPeersChanged(peers []peer.Peer) (reregister bool) {
// Filter peers down to those in StateParticipant.
participants := make([]peer.Peer, 0, len(peers))
for _, p := range peers {
if p.State == peer.StateParticipant {
participants = append(participants, p)
}
}
sort.Slice(participants, func(i, j int) bool { return participants[i].Name < participants[j].Name })
if peersEqual(participants, po.lastParticipants) {
return true
}
po.lastParticipants = participants
return po.next.NotifyPeersChanged(peers)
}
func peersEqual(a, b []peer.Peer) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}