-
Notifications
You must be signed in to change notification settings - Fork 25
/
watch.go
148 lines (119 loc) · 2.51 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
package CouloyDB
import (
"context"
"github.com/Kirov7/CouloyDB/public/ds"
"sync"
"time"
)
type eventType byte
const (
PutEvent eventType = iota
DelEvent
)
type watchEvent struct {
key string
value []byte
eventType eventType
}
type watcherManager struct {
lock *sync.RWMutex
watchers map[string]map[*Watcher]struct{} // key to watchers
queue *ds.EventQueue
closeCh chan struct{}
}
func newWatcherManager() *watcherManager {
return &watcherManager{
lock: &sync.RWMutex{},
watchers: make(map[string]map[*Watcher]struct{}),
queue: ds.NewEventQueue(),
closeCh: make(chan struct{}),
}
}
func (wm *watcherManager) closeWatcherListener(watcher *Watcher) {
select {
case <-watcher.ctx.Done():
wm.lock.Lock()
wm.unWatch(watcher)
wm.lock.Unlock()
case <-wm.closeCh:
return
}
}
func (wm *watcherManager) watch(ctx context.Context, key string) <-chan *watchEvent {
watcher := &Watcher{
key: key,
ctx: ctx,
respCh: make(chan *watchEvent, 128),
canceled: false,
}
wm.lock.Lock()
defer wm.lock.Unlock()
_, ok := wm.watchers[key]
if !ok {
wm.watchers[key] = make(map[*Watcher]struct{})
}
wm.watchers[key][watcher] = struct{}{}
go wm.closeWatcherListener(watcher)
return watcher.respCh
}
func (wm *watcherManager) unWatch(watcher *Watcher) {
if !watcher.canceled {
close(watcher.respCh)
watcher.canceled = true
}
delete(wm.watchers[watcher.key], watcher)
if len(wm.watchers[watcher.key]) == 0 {
delete(wm.watchers, watcher.key)
}
}
func (wm *watcherManager) watched(key string) bool {
_, ok := wm.watchers[key]
return ok
}
func (wm *watcherManager) notify(watchEvent *watchEvent) {
wm.queue.Write(watchEvent)
}
func (wm *watcherManager) start() {
for {
event, ok := wm.queue.Read().(*watchEvent)
if !ok {
break
}
wm.lock.RLock()
for watcher := range wm.watchers[event.key] {
watcher := watcher
if watcher.canceled {
continue
}
go watcher.sendResp(event)
}
wm.lock.RUnlock()
}
}
func (wm *watcherManager) stop() {
wm.queue.Close()
close(wm.closeCh)
wm.lock.Lock()
defer wm.lock.Unlock()
for _, watchers := range wm.watchers {
for watcher := range watchers {
wm.unWatch(watcher)
}
}
}
type Watcher struct {
key string
ctx context.Context
respCh chan *watchEvent
canceled bool
}
func (w *Watcher) sendResp(event *watchEvent) {
timeout := 100 * time.Millisecond
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case w.respCh <- event:
case <-w.ctx.Done():
case <-timer.C:
}
}