Skip to content

Commit d33a2a8

Browse files
committed
Update total cache size when updating the item
Signed-off-by: alanprot <[email protected]>
1 parent 61b3138 commit d33a2a8

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed

pkg/storage/tsdb/expanded_postings_cache.go

+14-1
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,6 @@ func (c *fifoCache[V]) getPromiseForKey(k string, fetch func() (V, int64, error)
304304
r := &cacheEntryPromise[V]{
305305
done: make(chan struct{}),
306306
}
307-
308307
defer close(r.done)
309308

310309
if !c.cfg.Enabled {
@@ -326,8 +325,11 @@ func (c *fifoCache[V]) getPromiseForKey(k string, fetch func() (V, int64, error)
326325
if ok && loaded.(*cacheEntryPromise[V]).isExpired(c.cfg.Ttl, c.timeNow()) {
327326
if c.cachedValues.CompareAndSwap(k, loaded, r) {
328327
r.v, r.sizeBytes, r.err = fetch()
328+
r.sizeBytes += int64(len(k))
329+
c.updateSize(loaded.(*cacheEntryPromise[V]).sizeBytes, r.sizeBytes)
329330
loaded = r
330331
r.ts = c.timeNow()
332+
ok = false
331333
}
332334
}
333335

@@ -377,6 +379,17 @@ func (c *fifoCache[V]) created(key string, sizeBytes int64) {
377379
c.cachedBytes += sizeBytes
378380
}
379381

382+
func (c *fifoCache[V]) updateSize(oldSize, newSizeBytes int64) {
383+
384+
if oldSize == newSizeBytes {
385+
return
386+
}
387+
388+
c.cachedMtx.Lock()
389+
defer c.cachedMtx.Unlock()
390+
c.cachedBytes += newSizeBytes - oldSize
391+
}
392+
380393
type cacheEntryPromise[V any] struct {
381394
ts time.Time
382395
sizeBytes int64

pkg/storage/tsdb/expanded_postings_cache_test.go

+10-6
Original file line numberDiff line numberDiff line change
@@ -104,19 +104,23 @@ func TestFifoCacheExpire(t *testing.T) {
104104
require.Equal(t, c.expectedFinalItems, totalCacheSize)
105105

106106
if c.ttlExpire {
107+
cache.timeNow = func() time.Time {
108+
return timeNow().Add(2 * c.cfg.Ttl)
109+
}
110+
107111
for i := 0; i < numberOfKeys; i++ {
108112
key := RepeatStringIfNeeded(fmt.Sprintf("key%d", i), keySize)
109-
cache.timeNow = func() time.Time {
110-
return timeNow().Add(2 * c.cfg.Ttl)
111-
}
112-
p, _ := cache.getPromiseForKey(key, func() (int, int64, error) {
113-
return 2, 8, nil
113+
originalSize := cache.cachedBytes
114+
p, loaded := cache.getPromiseForKey(key, func() (int, int64, error) {
115+
return 2, 18, nil
114116
})
115-
//require.False(t, loaded)
117+
require.False(t, loaded)
116118
v, err := p.result(context.Background())
117119
require.NoError(t, err)
118120
// New value
119121
require.Equal(t, 2, v)
122+
// Total Size Updated
123+
require.Equal(t, originalSize+10, cache.cachedBytes)
120124
}
121125
}
122126
})

0 commit comments

Comments
 (0)