forked from vmware-archive/atc
/
notifier.go
92 lines (73 loc) · 1.48 KB
/
notifier.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
85
86
87
88
89
90
91
92
package db
import "time"
//go:generate counterfeiter . Notifier
type Notifier interface {
Notify() <-chan struct{}
Close() error
}
func newConditionNotifier(bus NotificationsBus, channel string, cond func() (bool, error)) (Notifier, error) {
notified, err := bus.Listen(channel)
if err != nil {
return nil, err
}
notifier := &conditionNotifier{
cond: cond,
bus: bus,
channel: channel,
notified: notified,
notify: make(chan struct{}, 1),
stop: make(chan struct{}),
}
go notifier.watch()
return notifier, nil
}
type conditionNotifier struct {
cond func() (bool, error)
bus NotificationsBus
channel string
notified chan bool
notify chan struct{}
stop chan struct{}
}
func (notifier *conditionNotifier) Notify() <-chan struct{} {
return notifier.notify
}
func (notifier *conditionNotifier) Close() error {
close(notifier.stop)
return notifier.bus.Unlisten(notifier.channel, notifier.notified)
}
func (notifier *conditionNotifier) watch() {
for {
c, err := notifier.cond()
if err != nil {
select {
case <-time.After(5 * time.Second):
continue
case <-notifier.stop:
return
}
}
if c {
notifier.sendNotification()
}
dance:
for {
select {
case <-notifier.stop:
return
case ok := <-notifier.notified:
if ok {
notifier.sendNotification()
} else {
break dance
}
}
}
}
}
func (notifier *conditionNotifier) sendNotification() {
select {
case notifier.notify <- struct{}{}:
default:
}
}