bouncer/internal/cache/ttl/cache.go

40 lines
888 B
Go
Raw Normal View History

package ttl
import (
"time"
cache "forge.cadoles.com/cadoles/bouncer/internal/cache"
)
type Cache[K comparable, V any] struct {
timestamps cache.Cache[K, time.Time]
values cache.Cache[K, V]
ttl time.Duration
}
// Get implements cache.Cache.
func (c *Cache[K, V]) Get(key K) (V, bool) {
timestamp, exists := c.timestamps.Get(key)
if !exists || timestamp.Add(c.ttl).Before(time.Now()) {
return *new(V), false
}
return c.values.Get(key)
}
// Set implements cache.Cache.
func (c *Cache[K, V]) Set(key K, value V) {
c.timestamps.Set(key, time.Now())
c.values.Set(key, value)
}
func NewCache[K comparable, V any](values cache.Cache[K, V], timestamps cache.Cache[K, time.Time], ttl time.Duration) *Cache[K, V] {
return &Cache[K, V]{
values: values,
timestamps: timestamps,
ttl: ttl,
}
}
var _ cache.Cache[string, bool] = &Cache[string, bool]{}