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
|
package zip
import (
"time"
"github.com/karlseguin/ccache/v2"
"gitlab.com/gitlab-org/gitlab-pages/metrics"
)
type lruCache struct {
op string
duration time.Duration
cache *ccache.Cache
}
func newLruCache(op string, maxEntries uint32, duration time.Duration) *lruCache {
configuration := ccache.Configure()
configuration.MaxSize(int64(maxEntries))
configuration.ItemsToPrune(maxEntries / 16)
configuration.GetsPerPromote(64) // if item gets requested frequently promote it
configuration.OnDelete(func(*ccache.Item) {
metrics.ZipCachedEntries.WithLabelValues(op).Dec()
})
c := &lruCache{
cache: ccache.New(configuration),
duration: duration,
}
return c
}
func (c *lruCache) findOrFetch(namespace, key string, fetchFn func() (interface{}, error)) (interface{}, error) {
item := c.cache.Get(namespace + key)
if item != nil && !item.Expired() {
metrics.ZipCacheRequests.WithLabelValues(c.op, "hit").Inc()
return item.Value(), nil
}
value, err := fetchFn()
if err != nil {
metrics.ZipCacheRequests.WithLabelValues(c.op, "error").Inc()
return nil, err
}
metrics.ZipCacheRequests.WithLabelValues(c.op, "miss").Inc()
metrics.ZipCachedEntries.WithLabelValues(c.op).Inc()
c.cache.Set(namespace+key, value, c.duration)
return value, nil
}
|