Debian Codegraph @

fastcache.go

raw
1 // Package fastcache implements fast in-memory cache.
2 //
3 // The package has been extracted from https://victoriametrics.com/
4 package fastcache
5
6 import (
7 "fmt"
8 "sync"
9 "sync/atomic"
10
11 xxhash "github.com/cespare/xxhash/v2"
12 )
13
14 const bucketsCount = 512
15
16 const chunkSize = 64 * 1024
17
18 const bucketSizeBits = 40
19
20 const genSizeBits = 64 - bucketSizeBits
21
22 const maxGen = 1<<genSizeBits - 1
23
24 const maxBucketSize uint64 = 1 << bucketSizeBits
25
26 // Stats represents cache stats.
27 //
28 // Use Cache.UpdateStats for obtaining fresh stats from the cache.
29 type Stats struct {
30 // GetCalls is the number of Get calls.
31 GetCalls uint64
32
33 // SetCalls is the number of Set calls.
34 SetCalls uint64
35
36 // Misses is the number of cache misses.
37 Misses uint64
38
39 // Collisions is the number of cache collisions.
40 //
41 // Usually the number of collisions must be close to zero.
42 // High number of collisions suggest something wrong with cache.
43 Collisions uint64
44
45 // Corruptions is the number of detected corruptions of the cache.
46 //
47 // Corruptions may occur when corrupted cache is loaded from file.
48 Corruptions uint64
49
50 // EntriesCount is the current number of entries in the cache.
51 EntriesCount uint64
52
53 // BytesSize is the current size of the cache in bytes.
54 BytesSize uint64
55
56 // MaxBytesSize is the maximum allowed size of the cache in bytes (aka capacity).
57 MaxBytesSize uint64
58
59 // BigStats contains stats for GetBig/SetBig methods.
60 BigStats
61 }
62
63 // Reset resets s, so it may be re-used again in Cache.UpdateStats.
64 func (s *Stats) Reset() {
65 *s = Stats{}
66 }
67
68 // BigStats contains stats for GetBig/SetBig methods.
69 type BigStats struct {
70 // GetBigCalls is the number of GetBig calls.
71 GetBigCalls uint64
72
73 // SetBigCalls is the number of SetBig calls.
74 SetBigCalls uint64
75
76 // TooBigKeyErrors is the number of calls to SetBig with too big key.
77 TooBigKeyErrors uint64
78
79 // InvalidMetavalueErrors is the number of calls to GetBig resulting
80 // to invalid metavalue.
81 InvalidMetavalueErrors uint64
82
83 // InvalidValueLenErrors is the number of calls to GetBig resulting
84 // to a chunk with invalid length.
85 InvalidValueLenErrors uint64
86
87 // InvalidValueHashErrors is the number of calls to GetBig resulting
88 // to a chunk with invalid hash value.
89 InvalidValueHashErrors uint64
90 }
91
92 func (bs *BigStats) reset() {
93 atomic.StoreUint64(&bs.GetBigCalls, 0)
94 atomic.StoreUint64(&bs.SetBigCalls, 0)
95 atomic.StoreUint64(&bs.TooBigKeyErrors, 0)
96 atomic.StoreUint64(&bs.InvalidMetavalueErrors, 0)
97 atomic.StoreUint64(&bs.InvalidValueLenErrors, 0)
98 atomic.StoreUint64(&bs.InvalidValueHashErrors, 0)
99 }
100
101 // Cache is a fast thread-safe inmemory cache optimized for big number
102 // of entries.
103 //
104 // It has much lower impact on GC comparing to a simple `map[string][]byte`.
105 //
106 // Use New or LoadFromFile* for creating new cache instance.
107 // Concurrent goroutines may call any Cache methods on the same cache instance.
108 //
109 // Call Reset when the cache is no longer needed. This reclaims the allocated
110 // memory.
111 type Cache struct {
112 buckets [bucketsCount]bucket
113
114 bigStats BigStats
115 }
116
117 // New returns new cache with the given maxBytes capacity in bytes.
118 //
119 // maxBytes must be smaller than the available RAM size for the app,
120 // since the cache holds data in memory.
121 //
122 // If maxBytes is less than 32MB, then the minimum cache capacity is 32MB.
123 func New(maxBytes int) *Cache {
124 if maxBytes <= 0 {
125 panic(fmt.Errorf("maxBytes must be greater than 0; got %d", maxBytes))
126 }
127 var c Cache
128 maxBucketBytes := uint64((maxBytes + bucketsCount - 1) / bucketsCount)
129 for i := range c.buckets[:] {
130 c.buckets[i].Init(maxBucketBytes)
131 }
132 return &c
133 }
134
135 // Set stores (k, v) in the cache.
136 //
137 // Get must be used for reading the stored entry.
138 //
139 // The stored entry may be evicted at any time either due to cache
140 // overflow or due to unlikely hash collision.
141 // Pass higher maxBytes value to New if the added items disappear
142 // frequently.
143 //
144 // (k, v) entries with summary size exceeding 64KB aren't stored in the cache.
145 // SetBig can be used for storing entries exceeding 64KB.
146 //
147 // k and v contents may be modified after returning from Set.
148 func (c *Cache) Set(k, v []byte) {
149 h := xxhash.Sum64(k)
150 idx := h % bucketsCount
151 c.buckets[idx].Set(k, v, h)
152 }
153
154 // Get appends value by the key k to dst and returns the result.
155 //
156 // Get allocates new byte slice for the returned value if dst is nil.
157 //
158 // Get returns only values stored in c via Set.
159 //
160 // k contents may be modified after returning from Get.
161 func (c *Cache) Get(dst, k []byte) []byte {
162 h := xxhash.Sum64(k)
163 idx := h % bucketsCount
164 dst, _ = c.buckets[idx].Get(dst, k, h, true)
165 return dst
166 }
167
168 // HasGet works identically to Get, but also returns whether the given key
169 // exists in the cache. This method makes it possible to differentiate between a
170 // stored nil/empty value versus and non-existing value.
171 func (c *Cache) HasGet(dst, k []byte) ([]byte, bool) {
172 h := xxhash.Sum64(k)
173 idx := h % bucketsCount
174 return c.buckets[idx].Get(dst, k, h, true)
175 }
176
177 // Has returns true if entry for the given key k exists in the cache.
178 func (c *Cache) Has(k []byte) bool {
179 h := xxhash.Sum64(k)
180 idx := h % bucketsCount
181 _, ok := c.buckets[idx].Get(nil, k, h, false)
182 return ok
183 }
184
185 // Del deletes value for the given k from the cache.
186 //
187 // k contents may be modified after returning from Del.
188 func (c *Cache) Del(k []byte) {
189 h := xxhash.Sum64(k)
190 idx := h % bucketsCount
191 c.buckets[idx].Del(h)
192 }
193
194 // Reset removes all the items from the cache.
195 func (c *Cache) Reset() {
196 for i := range c.buckets[:] {
197 c.buckets[i].Reset()
198 }
199 c.bigStats.reset()
200 }
201
202 // UpdateStats adds cache stats to s.
203 //
204 // Call s.Reset before calling UpdateStats if s is re-used.
205 func (c *Cache) UpdateStats(s *Stats) {
206 for i := range c.buckets[:] {
207 c.buckets[i].UpdateStats(s)
208 }
209 s.GetBigCalls += atomic.LoadUint64(&c.bigStats.GetBigCalls)
210 s.SetBigCalls += atomic.LoadUint64(&c.bigStats.SetBigCalls)
211 s.TooBigKeyErrors += atomic.LoadUint64(&c.bigStats.TooBigKeyErrors)
212 s.InvalidMetavalueErrors += atomic.LoadUint64(&c.bigStats.InvalidMetavalueErrors)
213 s.InvalidValueLenErrors += atomic.LoadUint64(&c.bigStats.InvalidValueLenErrors)
214 s.InvalidValueHashErrors += atomic.LoadUint64(&c.bigStats.InvalidValueHashErrors)
215 }
216
217 type bucket struct {
218 mu sync.RWMutex
219
220 getCalls uint64
221 setCalls uint64
222 misses uint64
223
224 // chunks is a ring buffer with encoded (k, v) pairs.
225 // It consists of 64KB chunks.
226 chunks [][]byte
227
228 // m maps hash(k) to idx of (k, v) pair in chunks.
229 m map[uint64]uint64
230
231 // gen is the generation of chunks.
232 gen uint64
233
234 // idx points to chunks for writing the next (k, v) pair.
235 idx uint64
236
237 collisions uint64
238 corruptions uint64
239 }
240
241 func (b *bucket) Init(maxBytes uint64) {
242 if maxBytes == 0 {
243 panic(fmt.Errorf("maxBytes cannot be zero"))
244 }
245 if maxBytes >= maxBucketSize {
246 panic(fmt.Errorf("too big maxBytes=%d; should be smaller than %d", maxBytes, maxBucketSize))
247 }
248 maxChunks := (maxBytes + chunkSize - 1) / chunkSize
249 b.chunks = make([][]byte, maxChunks)
250 b.m = make(map[uint64]uint64)
251 b.Reset()
252 }
253
254 func (b *bucket) Reset() {
255 b.mu.Lock()
256 chunks := b.chunks
257 for i := range chunks {
258 putChunk(chunks[i])
259 chunks[i] = nil
260 }
261 b.m = make(map[uint64]uint64)
262 b.idx = 0
263 b.gen = 1
264 atomic.StoreUint64(&b.getCalls, 0)
265 atomic.StoreUint64(&b.setCalls, 0)
266 atomic.StoreUint64(&b.misses, 0)
267 atomic.StoreUint64(&b.collisions, 0)
268 atomic.StoreUint64(&b.corruptions, 0)
269 b.mu.Unlock()
270 }
271
272 func (b *bucket) cleanLocked() {
273 bGen := b.gen & ((1 << genSizeBits) - 1)
274 bIdx := b.idx
275 bm := b.m
276 newItems := 0
277 for _, v := range bm {
278 gen := v >> bucketSizeBits
279 idx := v & ((1 << bucketSizeBits) - 1)
280 if (gen+1 == bGen || gen == maxGen && bGen == 1) && idx >= bIdx || gen == bGen && idx < bIdx {
281 newItems++
282 }
283 }
284 if newItems < len(bm) {
285 // Re-create b.m with valid items, which weren't expired yet instead of deleting expired items from b.m.
286 // This should reduce memory fragmentation and the number Go objects behind b.m.
287 // See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/5379
288 bmNew := make(map[uint64]uint64, newItems)
289 for k, v := range bm {
290 gen := v >> bucketSizeBits
291 idx := v & ((1 << bucketSizeBits) - 1)
292 if (gen+1 == bGen || gen == maxGen && bGen == 1) && idx >= bIdx || gen == bGen && idx < bIdx {
293 bmNew[k] = v
294 }
295 }
296 b.m = bmNew
297 }
298 }
299
300 func (b *bucket) UpdateStats(s *Stats) {
301 s.GetCalls += atomic.LoadUint64(&b.getCalls)
302 s.SetCalls += atomic.LoadUint64(&b.setCalls)
303 s.Misses += atomic.LoadUint64(&b.misses)
304 s.Collisions += atomic.LoadUint64(&b.collisions)
305 s.Corruptions += atomic.LoadUint64(&b.corruptions)
306
307 b.mu.RLock()
308 s.EntriesCount += uint64(len(b.m))
309 bytesSize := uint64(0)
310 for _, chunk := range b.chunks {
311 bytesSize += uint64(cap(chunk))
312 }
313 s.BytesSize += bytesSize
314 s.MaxBytesSize += uint64(len(b.chunks)) * chunkSize
315 b.mu.RUnlock()
316 }
317
318 func (b *bucket) Set(k, v []byte, h uint64) {
319 atomic.AddUint64(&b.setCalls, 1)
320 if len(k) >= (1<<16) || len(v) >= (1<<16) {
321 // Too big key or value - its length cannot be encoded
322 // with 2 bytes (see below). Skip the entry.
323 return
324 }
325 var kvLenBuf [4]byte
326 kvLenBuf[0] = byte(uint16(len(k)) >> 8)
327 kvLenBuf[1] = byte(len(k))
328 kvLenBuf[2] = byte(uint16(len(v)) >> 8)
329 kvLenBuf[3] = byte(len(v))
330 kvLen := uint64(len(kvLenBuf) + len(k) + len(v))
331 if kvLen >= chunkSize {
332 // Do not store too big keys and values, since they do not
333 // fit a chunk.
334 return
335 }
336
337 b.mu.Lock()
338 chunks := b.chunks
339 needClean := false
340 idx := b.idx
341 idxNew := idx + kvLen
342 chunkIdx := idx / chunkSize
343 chunkIdxNew := idxNew / chunkSize
344 if chunkIdxNew > chunkIdx {
345 if chunkIdxNew >= uint64(len(chunks)) {
346 idx = 0
347 idxNew = kvLen
348 chunkIdx = 0
349 b.gen++
350 if b.gen&((1<<genSizeBits)-1) == 0 {
351 b.gen++
352 }
353 needClean = true
354 } else {
355 idx = chunkIdxNew * chunkSize
356 idxNew = idx + kvLen
357 chunkIdx = chunkIdxNew
358 }
359 chunks[chunkIdx] = chunks[chunkIdx][:0]
360 }
361 chunk := chunks[chunkIdx]
362 if chunk == nil {
363 chunk = getChunk()
364 chunk = chunk[:0]
365 }
366 chunk = append(chunk, kvLenBuf[:]...)
367 chunk = append(chunk, k...)
368 chunk = append(chunk, v...)
369 chunks[chunkIdx] = chunk
370 b.m[h] = idx | (b.gen << bucketSizeBits)
371 b.idx = idxNew
372 if needClean {
373 b.cleanLocked()
374 }
375 b.mu.Unlock()
376 }
377
378 func (b *bucket) Get(dst, k []byte, h uint64, returnDst bool) ([]byte, bool) {
379 b.mu.RLock()
380 atomic.AddUint64(&b.getCalls, 1)
381 found := false
382 chunks := b.chunks
383 v := b.m[h]
384 bGen := b.gen & ((1 << genSizeBits) - 1)
385 if v > 0 {
386 gen := v >> bucketSizeBits
387 idx := v & ((1 << bucketSizeBits) - 1)
388 if gen == bGen && idx < b.idx || gen+1 == bGen && idx >= b.idx || gen == maxGen && bGen == 1 && idx >= b.idx {
389 chunkIdx := idx / chunkSize
390 if chunkIdx >= uint64(len(chunks)) {
391 // Corrupted data during the load from file. Just skip it.
392 atomic.AddUint64(&b.corruptions, 1)
393 goto end
394 }
395 chunk := chunks[chunkIdx]
396 idx %= chunkSize
397 if idx+4 >= chunkSize {
398 // Corrupted data during the load from file. Just skip it.
399 atomic.AddUint64(&b.corruptions, 1)
400 goto end
401 }
402 kvLenBuf := chunk[idx : idx+4]
403 keyLen := (uint64(kvLenBuf[0]) << 8) | uint64(kvLenBuf[1])
404 valLen := (uint64(kvLenBuf[2]) << 8) | uint64(kvLenBuf[3])
405 idx += 4
406 if idx+keyLen+valLen >= chunkSize {
407 // Corrupted data during the load from file. Just skip it.
408 atomic.AddUint64(&b.corruptions, 1)
409 goto end
410 }
411 if string(k) == string(chunk[idx:idx+keyLen]) {
412 idx += keyLen
413 if returnDst {
414 dst = append(dst, chunk[idx:idx+valLen]...)
415 }
416 found = true
417 } else {
418 atomic.AddUint64(&b.collisions, 1)
419 }
420 }
421 }
422 end:
423 b.mu.RUnlock()
424 if !found {
425 atomic.AddUint64(&b.misses, 1)
426 }
427 return dst, found
428 }
429
430 func (b *bucket) Del(h uint64) {
431 b.mu.Lock()
432 delete(b.m, h)
433 b.mu.Unlock()
434 }