/
store.go
94 lines (79 loc) · 1.68 KB
/
store.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
package kubernetes
import (
"sync"
"k8s.io/client-go/tools/cache"
)
// Event type is an enum of ADD, UPDATE and DELETE
type Event int
// Watch type is for callbacks when somethings happens to the store.
type Watch func(Event, interface{})
// Event enum values.
const (
ADD Event = iota
UPDATE
DELETE
)
type eventStore struct {
mtx sync.Mutex
watch Watch
keyFunc cache.KeyFunc
cache.Store
}
// NewEventStore creates a new Store which triggers watch whenever
// an object is added, removed or updated.
func NewEventStore(watch Watch, keyFunc cache.KeyFunc) cache.Store {
return &eventStore{
keyFunc: keyFunc,
watch: watch,
Store: cache.NewStore(keyFunc),
}
}
func (e *eventStore) Add(o interface{}) error {
e.mtx.Lock()
defer e.mtx.Unlock()
e.watch(ADD, o)
return e.Store.Add(o)
}
func (e *eventStore) Update(o interface{}) error {
e.mtx.Lock()
defer e.mtx.Unlock()
e.watch(UPDATE, o)
return e.Store.Update(o)
}
func (e *eventStore) Delete(o interface{}) error {
e.mtx.Lock()
defer e.mtx.Unlock()
e.watch(DELETE, o)
return e.Store.Delete(o)
}
func (e *eventStore) Replace(os []interface{}, ver string) error {
e.mtx.Lock()
defer e.mtx.Unlock()
indexed := map[string]interface{}{}
for _, o := range os {
key, err := e.keyFunc(o)
if err != nil {
return err
}
indexed[key] = o
}
existing := map[string]interface{}{}
for _, o := range e.Store.List() {
key, err := e.keyFunc(o)
if err != nil {
return err
}
existing[key] = o
if _, ok := indexed[key]; !ok {
e.watch(DELETE, o)
}
}
for key, o := range indexed {
if _, ok := existing[key]; !ok {
e.watch(ADD, o)
} else {
e.watch(UPDATE, o)
}
}
return e.Store.Replace(os, ver)
}