-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatcher.go
107 lines (87 loc) · 1.76 KB
/
watcher.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package flowstate
import (
"log"
"time"
)
type Watcher struct {
e Engine
cmd *GetManyCommand
watchCh chan State
closeCh chan struct{}
}
func NewWatcher(e Engine, cmd *GetManyCommand) *Watcher {
copyCmd := &GetManyCommand{
SinceRev: cmd.SinceRev,
SinceTime: cmd.SinceTime,
Labels: copyORLabels(cmd.Labels),
LatestOnly: cmd.LatestOnly,
Limit: cmd.Limit,
}
copyCmd.Prepare()
w := &Watcher{
e: e,
cmd: copyCmd,
watchCh: make(chan State, 1),
closeCh: make(chan struct{}),
}
go w.listen()
return w
}
func (w *Watcher) Next() <-chan State {
return w.watchCh
}
func (w *Watcher) Close() {
close(w.closeCh)
}
func (w *Watcher) listen() {
t := time.NewTicker(time.Millisecond * 100)
defer t.Stop()
for {
select {
case <-t.C:
for {
if more := w.stream(); !more {
break
}
}
case <-w.closeCh:
return
}
}
}
func (w *Watcher) stream() bool {
getManyCmd := w.cmd
getManyCmd.SetResult(nil)
if err := w.e.Do(getManyCmd); err != nil {
log.Printf("ERROR: WatchListener: get many states: %s", err)
return false
}
res, err := getManyCmd.Result()
if err != nil {
log.Printf("ERROR: WatchListener: get many states result: %s", err)
return false
}
if len(res.States) == 0 {
return false
}
for i := range res.States {
select {
case w.watchCh <- res.States[i]:
getManyCmd.SinceRev = res.States[i].Rev
case <-w.closeCh:
return false
}
}
return res.More
}
func copyORLabels(orLabels []map[string]string) []map[string]string {
copyORLabels := make([]map[string]string, 0, len(orLabels))
for _, labels := range orLabels {
copyLabels := make(map[string]string)
for k, v := range labels {
copyLabels[k] = v
}
copyORLabels = append(copyORLabels, copyLabels)
}
return copyORLabels
}