/
watcher.go
79 lines (67 loc) · 1.37 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
package runtimevar
import (
"context"
"errors"
"fmt"
"github.com/google/go-cloud/runtimevar"
"github.com/google/go-cloud/runtimevar/driver"
"github.com/bull-b/go-config/source"
)
type watcher struct {
name string
opts source.Options
exit chan bool
v *runtimevar.Variable
}
func (w *watcher) Next() (*source.ChangeSet, error) {
// check exit status
select {
case <-w.exit:
return nil, errors.New("watcher stopped")
default:
}
// create a context with cancellation to kill watcher
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
// if the watcher stops then cancel
select {
case <-w.exit:
cancel()
}
}()
s, err := w.v.Watch(ctx)
if err != nil {
return nil, err
}
// assuming value is bytes
b, err := w.opts.Encoder.Encode(s.Value.([]byte))
if err != nil {
return nil, fmt.Errorf("error reading source: %v", err)
}
cs := &source.ChangeSet{
Timestamp: s.UpdateTime,
Format: w.opts.Encoder.String(),
Source: w.name,
Data: b,
}
cs.Checksum = cs.Sum()
return cs, nil
}
func (w *watcher) Stop() error {
select {
case <-w.exit:
return nil
default:
close(w.exit)
return nil
}
}
func newWatcher(name string, dv driver.Watcher, opts source.Options) (source.Watcher, error) {
return &watcher{
name: name,
opts: opts,
exit: make(chan bool),
v: runtimevar.New(dv),
}, nil
}