-
Notifications
You must be signed in to change notification settings - Fork 158
/
lru.go
341 lines (313 loc) · 6.97 KB
/
lru.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package rueidis
import (
"container/list"
"context"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/redis/rueidis/internal/cmds"
)
const (
entrySize = int(unsafe.Sizeof(cacheEntry{})) + int(unsafe.Sizeof(&cacheEntry{}))
keyCacheSize = int(unsafe.Sizeof(keyCache{})) + int(unsafe.Sizeof(&keyCache{}))
elementSize = int(unsafe.Sizeof(list.Element{})) + int(unsafe.Sizeof(&list.Element{}))
stringSSize = int(unsafe.Sizeof(""))
entryBaseSize = (keyCacheSize + entrySize + elementSize + stringSSize*2) * 3 / 2
entryMinSize = entryBaseSize + messageStructSize
moveThreshold = uint32(1024 - 1)
)
type cacheEntry struct {
err error
ch chan struct{}
kc *keyCache
cmd string
val RedisMessage
size int
}
func (e *cacheEntry) Wait(ctx context.Context) (RedisMessage, error) {
if ch := ctx.Done(); ch == nil {
<-e.ch
} else {
select {
case <-ch:
return RedisMessage{}, ctx.Err()
case <-e.ch:
}
}
return e.val, e.err
}
type keyCache struct {
cache map[string]*list.Element
key string
hits uint32
miss uint32
}
var _ CacheStore = (*lru)(nil)
type lru struct {
store map[string]*keyCache
list *list.List
mu sync.RWMutex
size int
max int
}
func newLRU(opt CacheStoreOption) CacheStore {
return &lru{
max: opt.CacheSizeEachConn,
store: make(map[string]*keyCache),
list: list.New(),
}
}
func (c *lru) Flight(key, cmd string, ttl time.Duration, now time.Time) (v RedisMessage, ce CacheEntry) {
var ok bool
var kc *keyCache
var ele, back *list.Element
var e *cacheEntry
c.mu.RLock()
if kc, ok = c.store[key]; ok {
if ele = kc.cache[cmd]; ele != nil {
e = ele.Value.(*cacheEntry)
v = e.val
back = c.list.Back()
}
}
c.mu.RUnlock()
if e != nil && (v.typ == 0 || v.relativePTTL(now) > 0) {
hits := atomic.AddUint32(&kc.hits, 1)
if ele != back && hits&moveThreshold == 0 {
c.mu.Lock()
if c.list != nil {
c.list.MoveToBack(ele)
}
c.mu.Unlock()
}
return v, e
}
v = RedisMessage{}
e = nil
c.mu.Lock()
if kc, ok = c.store[key]; !ok {
if c.store == nil {
goto ret
}
kc = &keyCache{cache: make(map[string]*list.Element, 1), key: key}
c.store[key] = kc
}
if ele = kc.cache[cmd]; ele != nil {
if e = ele.Value.(*cacheEntry); e.val.typ == 0 || e.val.relativePTTL(now) > 0 {
atomic.AddUint32(&kc.hits, 1)
v = e.val
c.list.MoveToBack(ele)
ce = e
goto ret
} else {
c.list.Remove(ele)
c.size -= e.size
}
}
atomic.AddUint32(&kc.miss, 1)
v.setExpireAt(now.Add(ttl).UnixMilli())
kc.cache[cmd] = c.list.PushBack(&cacheEntry{cmd: cmd, kc: kc, val: v, ch: make(chan struct{})})
ret:
c.mu.Unlock()
return v, ce
}
func (c *lru) Flights(now time.Time, multi []CacheableTTL, results []RedisResult, entries map[int]CacheEntry) (missed []int) {
var moves []*list.Element
c.mu.RLock()
for i, ct := range multi {
key, cmd := cmds.CacheKey(ct.Cmd)
if kc, ok := c.store[key]; ok {
if ele := kc.cache[cmd]; ele != nil {
e := ele.Value.(*cacheEntry)
v := e.val
if v.typ == 0 {
entries[i] = e
} else if v.relativePTTL(now) > 0 {
results[i] = newResult(v, nil)
} else {
goto miss1
}
if atomic.AddUint32(&kc.hits, 1)&moveThreshold == 0 {
if moves == nil {
moves = make([]*list.Element, 0, len(multi))
}
moves = append(moves, ele)
}
continue
}
}
miss1:
if missed == nil {
missed = make([]int, 0, len(multi))
}
missed = append(missed, i)
}
c.mu.RUnlock()
if len(moves) > 0 {
c.mu.Lock()
if c.list != nil {
for _, ele := range moves {
c.list.MoveToBack(ele)
}
}
c.mu.Unlock()
}
if len(missed) == 0 {
return missed
}
j := 0
c.mu.Lock()
if c.store == nil {
c.mu.Unlock()
return missed
}
for _, i := range missed {
key, cmd := cmds.CacheKey(multi[i].Cmd)
kc, ok := c.store[key]
if !ok {
kc = &keyCache{cache: make(map[string]*list.Element, 1), key: key}
c.store[key] = kc
}
if ele := kc.cache[cmd]; ele != nil {
e := ele.Value.(*cacheEntry)
v := e.val
if v.typ == 0 {
entries[i] = e
} else if v.relativePTTL(now) > 0 {
results[i] = newResult(v, nil)
} else {
c.list.Remove(ele)
c.size -= e.size
goto miss2
}
atomic.AddUint32(&kc.hits, 1)
c.list.MoveToBack(ele)
continue
}
miss2:
atomic.AddUint32(&kc.miss, 1)
v := RedisMessage{}
v.setExpireAt(now.Add(multi[i].TTL).UnixMilli())
kc.cache[cmd] = c.list.PushBack(&cacheEntry{cmd: cmd, kc: kc, val: v, ch: make(chan struct{})})
missed[j] = i
j++
}
c.mu.Unlock()
return missed[:j]
}
func (c *lru) Update(key, cmd string, value RedisMessage) (pxat int64) {
var ch chan struct{}
c.mu.Lock()
if kc, ok := c.store[key]; ok {
if ele := kc.cache[cmd]; ele != nil {
if e := ele.Value.(*cacheEntry); e.val.typ == 0 {
pxat = value.getExpireAt()
cpttl := e.val.getExpireAt()
if cpttl < pxat || pxat == 0 {
// server side ttl should only shorten client side ttl
pxat = cpttl
value.setExpireAt(pxat)
}
e.val = value
e.size = entryBaseSize + 2*(len(key)+len(cmd)) + value.approximateSize()
c.size += e.size
ch = e.ch
}
ele = c.list.Front()
for c.size > c.max && ele != nil {
if e := ele.Value.(*cacheEntry); e.val.typ != 0 { // do not delete pending entries
kc := e.kc
if delete(kc.cache, e.cmd); len(kc.cache) == 0 {
delete(c.store, kc.key)
}
c.list.Remove(ele)
c.size -= e.size
}
ele = ele.Next()
}
}
}
c.mu.Unlock()
if ch != nil {
close(ch)
}
return
}
func (c *lru) Cancel(key, cmd string, err error) {
var ch chan struct{}
c.mu.Lock()
if kc, ok := c.store[key]; ok {
if ele := kc.cache[cmd]; ele != nil {
if e := ele.Value.(*cacheEntry); e.val.typ == 0 {
e.err = err
ch = e.ch
if delete(kc.cache, cmd); len(kc.cache) == 0 {
delete(c.store, key)
}
c.list.Remove(ele)
}
}
}
c.mu.Unlock()
if ch != nil {
close(ch)
}
}
func (c *lru) GetTTL(key, cmd string) (ttl time.Duration) {
c.mu.Lock()
if kc, ok := c.store[key]; ok && kc.cache[cmd] != nil {
ttl = time.Duration(kc.cache[cmd].Value.(*cacheEntry).val.relativePTTL(time.Now())) * time.Millisecond
}
if ttl <= 0 {
ttl = -2
}
c.mu.Unlock()
return
}
func (c *lru) purge(key string, kc *keyCache) {
if kc != nil {
for cmd, ele := range kc.cache {
if ele != nil {
e := ele.Value.(*cacheEntry)
if e.val.typ == 0 { // do not delete pending entries
continue
}
c.list.Remove(ele)
c.size -= e.size
}
if delete(kc.cache, cmd); len(kc.cache) == 0 {
delete(c.store, key)
}
}
}
}
func (c *lru) Delete(keys []RedisMessage) {
c.mu.Lock()
if keys == nil {
for key, kc := range c.store {
c.purge(key, kc)
}
} else {
for _, k := range keys {
c.purge(k.string, c.store[k.string])
}
}
c.mu.Unlock()
}
func (c *lru) Close(err error) {
c.mu.Lock()
for _, kc := range c.store {
for _, ele := range kc.cache {
if ele != nil {
if e := ele.Value.(*cacheEntry); e.val.typ == 0 {
e.err = err
close(e.ch)
}
}
}
}
c.store = nil
c.list = nil
c.mu.Unlock()
}