-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache.go
80 lines (71 loc) · 1.75 KB
/
cache.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
package main
import (
"encoding/binary"
"errors"
"github.com/allegro/bigcache"
log "github.com/sirupsen/logrus"
"time"
)
type ProxyCache interface {
Set(key string, val []byte, ttl time.Duration) error
Get(key string) []byte
Clear() error
}
type BigCacheTTL struct {
*bigcache.BigCache
}
func NewBigCacheTTL(maxTTL, cleanWindow time.Duration, maxSizeMb int) *BigCacheTTL {
c, err := bigcache.NewBigCache(bigcache.Config{
Shards: calcShards(maxSizeMb),
LifeWindow: maxTTL,
CleanWindow: cleanWindow,
MaxEntriesInWindow: 1000 * 10 * 60,
MaxEntrySize: 500,
Verbose: true,
Hasher: fnv64a{},
HardMaxCacheSize: maxSizeMb,
Logger: log.StandardLogger(),
})
if err != nil {
panic(err)
}
return &BigCacheTTL{c}
}
func (c *BigCacheTTL) Set(key string, val []byte, ttl time.Duration) error {
v := make([]byte, 8+len(val))
binary.LittleEndian.PutUint64(v[:], uint64(time.Now().Add(ttl).UnixNano()))
copy(v[8:], val)
return c.BigCache.Set(key, v)
}
func (c *BigCacheTTL) Get(key string) []byte {
val, err := c.BigCache.Get(key)
if err != nil {
if !errors.Is(err, bigcache.ErrEntryNotFound) {
log.WithError(err).WithField("key", key).Debug("error while getting cache")
}
return nil
}
if len(val) < 8 {
return nil
}
evict := time.Unix(0, int64(binary.LittleEndian.Uint64(val)))
if !time.Now().Before(evict) {
err := c.BigCache.Delete(key)
if err != nil {
log.WithError(err).WithField("key", key).Debug("delete cache error")
}
return nil
}
return val[8:]
}
func (c *BigCacheTTL) Clear() error {
return c.BigCache.Reset()
}
func (c *BigCacheTTL) Iterator() {}
func calcShards(maxMb int) int {
n := maxMb * 1024 / 256
if n > 1024 {
return 1024
}
return n
}