-
Notifications
You must be signed in to change notification settings - Fork 8
/
watcher_generic.go
104 lines (86 loc) · 2.24 KB
/
watcher_generic.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
package metadata
import (
"context"
"reflect"
"time"
)
const DefaultWatcherInterval = 5 * time.Minute
// WatcherOption represents an option that can be used to configure
// a watcher.
type WatcherOption func(options *watcherConfig)
type watcherConfig struct {
Interval time.Duration
}
type resourceFetchFunc[T any] func(ctx context.Context) (T, error)
// genericWatcher is a resource-agnostic watcher that allows
// us to re-use polling logic across various watcher implementations.
type genericWatcher[T any] struct {
Updates chan T
Errors chan error
cancel chan bool
fetchResource resourceFetchFunc[T]
interval time.Duration
}
// Start starts the watcher.
func (watcher *genericWatcher[T]) Start(ctx context.Context) {
var oldData T
ticker := time.NewTicker(watcher.interval)
defer ticker.Stop()
defer func() {
close(watcher.Updates)
close(watcher.Errors)
close(watcher.cancel)
}()
for {
select {
case <-ctx.Done():
return
case <-watcher.cancel:
return
case <-ticker.C:
data, err := watcher.fetchResource(ctx)
if err != nil {
watcher.Errors <- err
}
if !reflect.DeepEqual(data, oldData) {
watcher.Updates <- data
oldData = data
}
}
}
}
// Close closes the watcher and all related channels.
func (watcher *genericWatcher[T]) Close() {
// Send a signal to cancel the poller.
// All channels wil be implicitly cleaned up in
// the start goroutine, else they will be
// cleaned up by the garbage collector.
watcher.cancel <- true
}
// newGenericWatcher creates a new instance of an endpoint-agnostic watcher.
func newGenericWatcher[T any](
fetchResource resourceFetchFunc[T],
opts ...WatcherOption,
) *genericWatcher[T] {
watcherOpts := watcherConfig{
Interval: DefaultWatcherInterval,
}
for _, opt := range opts {
opt(&watcherOpts)
}
return &genericWatcher[T]{
Updates: make(chan T),
Errors: make(chan error),
cancel: make(chan bool, 1),
interval: watcherOpts.Interval,
fetchResource: fetchResource,
}
}
// WatcherWithInterval configures the interval at which
// a watcher should poll for changes.
// Default: 5 minutes
func WatcherWithInterval(duration time.Duration) WatcherOption {
return func(options *watcherConfig) {
options.Interval = duration
}
}