cache.go 1.06 KB
Newer Older
1 2
package caching

3
import lru "github.com/hashicorp/golang-lru/v2"
4 5 6 7 8 9 10

type Metrics interface {
	CacheAdd(label string, cacheSize int, evicted bool)
	CacheGet(label string, hit bool)
}

// LRUCache wraps hashicorp *lru.Cache and tracks cache metrics
11
type LRUCache[K comparable, V any] struct {
12 13
	m     Metrics
	label string
14
	inner *lru.Cache[K, V]
15 16
}

17
func (c *LRUCache[K, V]) Get(key K) (value V, ok bool) {
18 19 20 21 22 23 24
	value, ok = c.inner.Get(key)
	if c.m != nil {
		c.m.CacheGet(c.label, ok)
	}
	return value, ok
}

25
func (c *LRUCache[K, V]) Add(key K, value V) (evicted bool) {
26 27 28 29 30 31 32 33 34
	evicted = c.inner.Add(key, value)
	if c.m != nil {
		c.m.CacheAdd(c.label, c.inner.Len(), evicted)
	}
	return evicted
}

// NewLRUCache creates a LRU cache with the given metrics, labeling the cache adds/gets.
// Metrics are optional: no metrics will be tracked if m == nil.
35
func NewLRUCache[K comparable, V any](m Metrics, label string, maxSize int) *LRUCache[K, V] {
36
	// no errors if the size is positive
37 38
	cache, _ := lru.New[K, V](maxSize)
	return &LRUCache[K, V]{
39 40 41 42 43
		m:     m,
		label: label,
		inner: cache,
	}
}