-
Notifications
You must be signed in to change notification settings - Fork 938
/
Copy pathcacheset.go
245 lines (194 loc) · 4.47 KB
/
cacheset.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package cacheset
import (
"fmt"
"reflect"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
type Manager struct {
slots []*Slot
TTL time.Duration
started bool
}
func NewManager(ttl time.Duration) *Manager {
return &Manager{
TTL: ttl,
}
}
func (m *Manager) RunGCLoop() {
m.started = true
if len(m.slots) < 1 {
// No slots?
return
}
t := time.NewTicker(time.Minute)
i := 0
for {
<-t.C
slot := m.slots[i]
slot.gc(time.Now())
i++
if i >= len(m.slots) {
i = 0
}
}
}
func (m *Manager) EvictSlotEntry(slot string, key interface{}) {
for _, v := range m.slots {
if v.name == slot {
v.Delete(key)
}
}
}
func (m *Manager) FindSlot(slot string) *Slot {
for _, v := range m.slots {
if v.name == slot {
return v
}
}
return nil
}
type FetcherFunc = func(key interface{}) (interface{}, error)
// RegisterSlot register a new cached "thing"
// this is only safe to called during init() and friends
func (m *Manager) RegisterSlot(name string, fetcher FetcherFunc, keyType interface{}) *Slot {
if m.started {
panic("tried adding slots after manager had started")
}
for _, v := range m.slots {
if v.name == name {
panic(fmt.Sprintf("Key %s already used!", name))
}
}
slot := &Slot{
manager: m,
name: name,
fetcher: fetcher,
values: make(map[interface{}]*cachedEntry),
fetching: make(map[interface{}]*sync.Cond),
keyType: reflect.TypeOf(keyType),
}
m.slots = append(m.slots, slot)
return slot
}
type Slot struct {
manager *Manager
name string
fetcher FetcherFunc
valuesmu sync.RWMutex
values map[interface{}]*cachedEntry
fetching map[interface{}]*sync.Cond
keyType reflect.Type
}
func (s *Slot) Name() string {
return s.name
}
type cachedEntry struct {
value interface{}
expiresAt time.Time
accessCounter *int64
}
func (s *Slot) Get(key interface{}) (interface{}, error) {
return s.GetCustomFetch(key, s.fetcher)
}
func (s *Slot) GetCustomFetch(key interface{}, fetcher FetcherFunc) (interface{}, error) {
// fast path
if v := s.getNoFetch(key); v != nil {
metricsCacheHits.Add(1)
return v, nil
}
metricsCacheMisses.Add(1)
// item was not in cache, we need to fetch it
s.valuesmu.Lock()
for {
if v := s.getValueLocked(key); v != nil {
// we have the value now!
s.valuesmu.Unlock()
return v, nil
}
if c, ok := s.fetching[key]; ok {
// someone else is fetching this item, wait
c.Wait()
} else {
// we are not currently fetching this item, perform a a fetch
c = sync.NewCond(&s.valuesmu)
s.fetching[key] = c
// unlock while were fetching to allow work on other guild's values
s.valuesmu.Unlock()
v, err := s.fetch(fetcher, key)
s.valuesmu.Lock()
if err == nil {
// we successfully retrieved a value, put it in a cached
s.values[key] = &cachedEntry{
value: v,
expiresAt: time.Now().Add(s.manager.TTL),
accessCounter: new(int64),
}
}
// no longer fetching this item
delete(s.fetching, key)
// wake up all waiters
c.Broadcast()
s.valuesmu.Unlock()
return v, err
}
}
}
func (s *Slot) getNoFetch(key interface{}) interface{} {
s.valuesmu.RLock()
defer s.valuesmu.RUnlock()
return s.getValueLocked(key)
}
func (s *Slot) getValueLocked(key interface{}) interface{} {
if v, ok := s.values[key]; ok {
return v.value
}
return nil
}
func (s *Slot) Delete(key interface{}) {
s.valuesmu.Lock()
defer s.valuesmu.Unlock()
delete(s.values, key)
}
func (s *Slot) DeleteFunc(f func(key interface{}, value interface{}) bool) int {
s.valuesmu.Lock()
defer s.valuesmu.Unlock()
n := 0
for k, v := range s.values {
if f(k, v.value) {
delete(s.values, k)
n++
}
}
return n
}
func (s *Slot) fetch(fetcher FetcherFunc, key interface{}) (interface{}, error) {
return fetcher(key)
}
func (s *Slot) gc(t time.Time) {
s.valuesmu.Lock()
defer s.valuesmu.Unlock()
for k, v := range s.values {
if v.expired(t) {
delete(s.values, k)
}
}
}
func (s *Slot) NewKey() interface{} {
return reflect.New(s.keyType).Interface()
}
func (e *cachedEntry) expired(t time.Time) bool {
return t.After(e.expiresAt)
}
var (
metricsCacheHits = promauto.NewCounter(prometheus.CounterOpts{
Name: "yagpdb_cacheset_cache_hits_total",
Help: "Cache hits in the satte cache",
})
metricsCacheMisses = promauto.NewCounter(prometheus.CounterOpts{
Name: "yagpdb_cacheset_cache_misses_total",
Help: "Cache misses in the sate cache",
})
)