-
Notifications
You must be signed in to change notification settings - Fork 3
/
watch.go
88 lines (78 loc) · 2.1 KB
/
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
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
package etcd
import (
"context"
"sync"
"github.com/abulo/ratel/goroutine"
"github.com/abulo/ratel/logger"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/mvcc/mvccpb"
)
// Watch A watch only tells the latest revision
type Watch struct {
revision int64
cancel context.CancelFunc
eventChan chan *clientv3.Event
lock *sync.RWMutex
incipientKVs []*mvccpb.KeyValue
}
// IncipientKeyValues incipient key and values
func (w *Watch) IncipientKeyValues() []*mvccpb.KeyValue {
return w.incipientKVs
}
// C ...
func (w *Watch) C() chan *clientv3.Event {
return w.eventChan
}
// NewWatch ...
func (client *Client) WatchPrefix(ctx context.Context, prefix string) (*Watch, error) {
resp, err := client.Get(ctx, prefix, clientv3.WithPrefix())
if err != nil {
return nil, err
}
var w = &Watch{
revision: resp.Header.Revision,
eventChan: make(chan *clientv3.Event, 100),
incipientKVs: resp.Kvs,
}
goroutine.Go(func() {
ctx, cancel := context.WithCancel(context.Background())
w.cancel = cancel
rch := client.Client.Watch(ctx, prefix, clientv3.WithPrefix(), clientv3.WithCreatedNotify(), clientv3.WithRev(w.revision))
for {
for n := range rch {
if n.CompactRevision > w.revision {
w.revision = n.CompactRevision
}
if n.Header.GetRevision() > w.revision {
w.revision = n.Header.GetRevision()
}
if err := n.Err(); err != nil {
logger.Logger.Error("watch request err", err, prefix)
continue
}
for _, ev := range n.Events {
select {
case w.eventChan <- ev:
default:
logger.Logger.Error("watch etcd with prefix", "err", "block event chan, drop event message")
}
}
}
ctx, cancel := context.WithCancel(context.Background())
w.cancel = cancel
if w.revision > 0 {
rch = client.Watch(ctx, prefix, clientv3.WithPrefix(), clientv3.WithCreatedNotify(), clientv3.WithRev(w.revision))
} else {
rch = client.Watch(ctx, prefix, clientv3.WithPrefix(), clientv3.WithCreatedNotify())
}
}
})
return w, nil
}
// Close close watch
func (w *Watch) Close() error {
if w.cancel != nil {
w.cancel()
}
return nil
}