2024-06-21 17:17:20 -04:00
|
|
|
package cache
|
|
|
|
|
|
|
|
|
|
import (
|
2025-06-10 17:22:13 -04:00
|
|
|
"context"
|
2024-06-21 17:57:43 -04:00
|
|
|
"errors"
|
2025-03-27 18:57:06 -04:00
|
|
|
"fmt"
|
2025-06-10 17:22:13 -04:00
|
|
|
"runtime"
|
2026-07-16 20:10:35 -04:00
|
|
|
"sync"
|
2024-06-24 17:30:13 -04:00
|
|
|
"sync/atomic"
|
2024-06-21 17:17:20 -04:00
|
|
|
"time"
|
|
|
|
|
|
2024-06-21 17:57:43 -04:00
|
|
|
"github.com/jellydator/ttlcache/v3"
|
2024-06-21 17:17:20 -04:00
|
|
|
)
|
|
|
|
|
|
2024-06-21 17:57:43 -04:00
|
|
|
type SimpleCache[K comparable, V any] interface {
|
|
|
|
|
Add(key K, value V) error
|
|
|
|
|
AddWithTTL(key K, value V, ttl time.Duration) error
|
|
|
|
|
Get(key K) (V, error)
|
|
|
|
|
GetWithLoader(key K, loader func(key K) (V, time.Duration, error)) (V, error)
|
2026-04-30 23:04:05 -04:00
|
|
|
Remove(key K)
|
2024-06-21 17:57:43 -04:00
|
|
|
Keys() []K
|
2024-06-24 17:30:13 -04:00
|
|
|
Values() []V
|
2025-06-10 17:22:13 -04:00
|
|
|
Len() int
|
|
|
|
|
OnExpiration(fn func(K, V)) func()
|
2024-06-21 17:17:20 -04:00
|
|
|
}
|
|
|
|
|
|
2024-06-21 17:40:18 -04:00
|
|
|
type Options struct {
|
2024-06-21 17:57:43 -04:00
|
|
|
SizeLimit uint64
|
2024-06-21 17:40:18 -04:00
|
|
|
DefaultTTL time.Duration
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-21 17:57:43 -04:00
|
|
|
func NewSimpleCache[K comparable, V any](options ...Options) SimpleCache[K, V] {
|
|
|
|
|
opts := []ttlcache.Option[K, V]{
|
|
|
|
|
ttlcache.WithDisableTouchOnHit[K, V](),
|
|
|
|
|
}
|
2024-06-21 17:40:18 -04:00
|
|
|
if len(options) > 0 {
|
2024-06-21 17:57:43 -04:00
|
|
|
o := options[0]
|
|
|
|
|
if o.SizeLimit > 0 {
|
|
|
|
|
opts = append(opts, ttlcache.WithCapacity[K, V](o.SizeLimit))
|
|
|
|
|
}
|
|
|
|
|
if o.DefaultTTL > 0 {
|
|
|
|
|
opts = append(opts, ttlcache.WithTTL[K, V](o.DefaultTTL))
|
|
|
|
|
}
|
2024-06-21 17:40:18 -04:00
|
|
|
}
|
|
|
|
|
|
2024-06-21 17:57:43 -04:00
|
|
|
c := ttlcache.New[K, V](opts...)
|
2025-06-10 17:22:13 -04:00
|
|
|
cache := &simpleCache[K, V]{
|
2026-07-16 20:10:35 -04:00
|
|
|
data: c,
|
|
|
|
|
loads: make(map[K]*flight[V]),
|
2024-06-21 17:17:20 -04:00
|
|
|
}
|
2025-06-10 17:22:13 -04:00
|
|
|
go cache.data.Start()
|
|
|
|
|
|
|
|
|
|
// Automatic cleanup to prevent goroutine leak when cache is garbage collected
|
|
|
|
|
runtime.AddCleanup(cache, func(ttlCache *ttlcache.Cache[K, V]) {
|
|
|
|
|
ttlCache.Stop()
|
|
|
|
|
}, cache.data)
|
|
|
|
|
|
|
|
|
|
return cache
|
2024-06-21 17:17:20 -04:00
|
|
|
}
|
|
|
|
|
|
2024-06-24 17:30:13 -04:00
|
|
|
const evictionTimeout = 1 * time.Hour
|
|
|
|
|
|
2024-06-21 17:57:43 -04:00
|
|
|
type simpleCache[K comparable, V any] struct {
|
2024-06-24 17:30:13 -04:00
|
|
|
data *ttlcache.Cache[K, V]
|
|
|
|
|
evictionDeadline atomic.Pointer[time.Time]
|
2026-07-16 20:10:35 -04:00
|
|
|
loadsMu sync.Mutex
|
|
|
|
|
loads map[K]*flight[V]
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// flight tracks an in-progress load so concurrent misses of the same key share it.
|
|
|
|
|
type flight[V any] struct {
|
|
|
|
|
done chan struct{}
|
|
|
|
|
val V
|
|
|
|
|
err error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (f *flight[V]) result() (V, error) {
|
|
|
|
|
if f.err != nil {
|
|
|
|
|
var zero V
|
|
|
|
|
return zero, fmt.Errorf("cache error: loader returned %w", f.err)
|
|
|
|
|
}
|
|
|
|
|
return f.val, nil
|
2024-06-21 17:17:20 -04:00
|
|
|
}
|
|
|
|
|
|
2024-06-21 17:57:43 -04:00
|
|
|
func (c *simpleCache[K, V]) Add(key K, value V) error {
|
2024-06-24 17:30:13 -04:00
|
|
|
c.evictExpired()
|
2024-06-21 17:57:43 -04:00
|
|
|
return c.AddWithTTL(key, value, ttlcache.DefaultTTL)
|
2024-06-21 17:17:20 -04:00
|
|
|
}
|
|
|
|
|
|
2024-06-21 17:57:43 -04:00
|
|
|
func (c *simpleCache[K, V]) AddWithTTL(key K, value V, ttl time.Duration) error {
|
2024-06-24 17:30:13 -04:00
|
|
|
c.evictExpired()
|
2024-06-21 17:57:43 -04:00
|
|
|
item := c.data.Set(key, value, ttl)
|
|
|
|
|
if item == nil {
|
|
|
|
|
return errors.New("failed to add item")
|
2024-06-21 17:17:20 -04:00
|
|
|
}
|
2024-06-21 17:57:43 -04:00
|
|
|
return nil
|
2024-06-21 17:17:20 -04:00
|
|
|
}
|
|
|
|
|
|
2026-04-30 23:04:05 -04:00
|
|
|
func (c *simpleCache[K, V]) Remove(key K) {
|
|
|
|
|
c.data.Delete(key)
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-21 17:57:43 -04:00
|
|
|
func (c *simpleCache[K, V]) Get(key K) (V, error) {
|
|
|
|
|
item := c.data.Get(key)
|
|
|
|
|
if item == nil {
|
2024-06-21 17:17:20 -04:00
|
|
|
var zero V
|
2024-06-21 17:57:43 -04:00
|
|
|
return zero, errors.New("item not found")
|
2024-06-21 17:17:20 -04:00
|
|
|
}
|
2024-06-21 17:57:43 -04:00
|
|
|
return item.Value(), nil
|
2024-06-21 17:17:20 -04:00
|
|
|
}
|
|
|
|
|
|
2026-07-16 20:10:35 -04:00
|
|
|
// GetWithLoader loads misses via the loader, deduplicating concurrent loads of
|
|
|
|
|
// the same key: one loader call runs, and every waiter shares its result (or error).
|
2024-06-21 17:57:43 -04:00
|
|
|
func (c *simpleCache[K, V]) GetWithLoader(key K, loader func(key K) (V, time.Duration, error)) (V, error) {
|
2026-07-16 20:10:35 -04:00
|
|
|
if item := c.data.Get(key); item != nil {
|
|
|
|
|
return item.Value(), nil
|
2024-06-21 17:57:43 -04:00
|
|
|
}
|
2026-07-16 20:10:35 -04:00
|
|
|
|
|
|
|
|
c.loadsMu.Lock()
|
|
|
|
|
if f, ok := c.loads[key]; ok {
|
|
|
|
|
c.loadsMu.Unlock()
|
|
|
|
|
<-f.done
|
|
|
|
|
return f.result()
|
|
|
|
|
}
|
|
|
|
|
f := &flight[V]{done: make(chan struct{}), err: errLoaderPanicked}
|
|
|
|
|
c.loads[key] = f
|
|
|
|
|
c.loadsMu.Unlock()
|
|
|
|
|
|
|
|
|
|
// Deregister even if the loader panics, so waiters get an error instead of
|
|
|
|
|
// blocking forever on a flight that will never complete.
|
|
|
|
|
defer func() {
|
|
|
|
|
close(f.done)
|
|
|
|
|
c.loadsMu.Lock()
|
|
|
|
|
delete(c.loads, key)
|
|
|
|
|
c.loadsMu.Unlock()
|
|
|
|
|
}()
|
|
|
|
|
|
|
|
|
|
if item := c.data.Get(key); item != nil { // a flight may have completed since the miss
|
|
|
|
|
f.val, f.err = item.Value(), nil
|
|
|
|
|
} else {
|
|
|
|
|
c.evictExpired()
|
|
|
|
|
var ttl time.Duration
|
|
|
|
|
f.val, ttl, f.err = loader(key)
|
|
|
|
|
if f.err == nil {
|
|
|
|
|
c.data.Set(key, f.val, ttl)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return f.result()
|
2024-06-21 17:57:43 -04:00
|
|
|
}
|
|
|
|
|
|
2026-07-16 20:10:35 -04:00
|
|
|
var errLoaderPanicked = errors.New("loader panicked")
|
|
|
|
|
|
2024-06-24 17:30:13 -04:00
|
|
|
func (c *simpleCache[K, V]) evictExpired() {
|
|
|
|
|
if c.evictionDeadline.Load() == nil || c.evictionDeadline.Load().Before(time.Now()) {
|
|
|
|
|
c.data.DeleteExpired()
|
2026-05-19 18:02:29 -03:00
|
|
|
c.evictionDeadline.Store(new(time.Now().Add(evictionTimeout)))
|
2024-06-24 17:30:13 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-21 17:57:43 -04:00
|
|
|
func (c *simpleCache[K, V]) Keys() []K {
|
2024-11-19 07:45:24 -05:00
|
|
|
res := make([]K, 0, c.data.Len())
|
2024-06-24 17:30:13 -04:00
|
|
|
c.data.Range(func(item *ttlcache.Item[K, V]) bool {
|
|
|
|
|
if !item.IsExpired() {
|
|
|
|
|
res = append(res, item.Key())
|
|
|
|
|
}
|
|
|
|
|
return true
|
|
|
|
|
})
|
|
|
|
|
return res
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (c *simpleCache[K, V]) Values() []V {
|
2024-11-19 07:45:24 -05:00
|
|
|
res := make([]V, 0, c.data.Len())
|
2024-06-24 17:30:13 -04:00
|
|
|
c.data.Range(func(item *ttlcache.Item[K, V]) bool {
|
|
|
|
|
if !item.IsExpired() {
|
|
|
|
|
res = append(res, item.Value())
|
|
|
|
|
}
|
|
|
|
|
return true
|
|
|
|
|
})
|
|
|
|
|
return res
|
2024-06-21 17:17:20 -04:00
|
|
|
}
|
2025-06-10 17:22:13 -04:00
|
|
|
|
|
|
|
|
func (c *simpleCache[K, V]) Len() int {
|
|
|
|
|
return c.data.Len()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (c *simpleCache[K, V]) OnExpiration(fn func(K, V)) func() {
|
|
|
|
|
return c.data.OnEviction(func(_ context.Context, reason ttlcache.EvictionReason, item *ttlcache.Item[K, V]) {
|
|
|
|
|
if reason == ttlcache.EvictionReasonExpired {
|
|
|
|
|
fn(item.Key(), item.Value())
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
}
|