/
watch.go
58 lines (50 loc) · 973 Bytes
/
watch.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
package construkt
import "k8s.io/apimachinery/pkg/watch"
type Watch[T HasMeta] interface {
ResultChan() <-chan Event[T]
Stop()
}
type watchWrapper[T HasMeta] struct {
watch watch.Interface
results chan Event[T]
}
func (w *watchWrapper[T]) ResultChan() <-chan Event[T] {
return w.results
}
func (w *watchWrapper[T]) Stop() {
w.watch.Stop()
}
func (w *watchWrapper[T]) run() {
defer close(w.results)
for {
select {
case event, ok := <-w.watch.ResultChan():
if !ok {
return
}
if event.Type == watch.Error {
w.results <- Event[T]{
Type: watch.Error,
Object: nil,
}
return
}
w.results <- Event[T]{
Type: event.Type,
Object: event.Object.(*object[T]),
}
}
}
}
func newWatch[T HasMeta](actual watch.Interface) Watch[T] {
w := &watchWrapper[T]{
results: make(chan Event[T]),
watch: actual,
}
go w.run()
return w
}
type Event[T HasMeta] struct {
Type watch.EventType
Object *object[T]
}