forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
78 lines (66 loc) · 1.3 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
package runtimevar
import (
"context"
"errors"
"fmt"
"github.com/alexapps/go-micro/config/source"
"gocloud.dev/runtimevar"
)
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, v *runtimevar.Variable, opts source.Options) (source.Watcher, error) {
return &watcher{
name: name,
opts: opts,
exit: make(chan bool),
v: v,
}, nil
}