Documentation
¶
Overview ¶
Package cache provides a generic, concurrency-safe LRU+TTL cache.
The implementation is extracted and generalised from the positive-only LRU inside apikey/cache.go. At least three other packages (policyeval regexp cache, graph event dedup, fleetfetch) reimpose the same pattern; this replaces them all.
Key properties:
- Generics: New[K, V] works with any comparable key and any value.
- LRU eviction: when maxSize is exceeded, the least-recently-used entry is evicted.
- Per-entry TTL: entries older than ttl are treated as misses and evicted lazily on next access.
- Optional stale-while-revalidate window (WithStaleWindow): entries past their TTL but within stale window are returned with a Stale=true flag so callers can serve them while refreshing.
- Clock-injectable: pass a clock.Clock for deterministic tests.
Usage:
c := cache.New[string, *MyVal](1000, 5*time.Minute)
c.Set("key", &MyVal{})
val, ok := c.Get("key")
// with stale window:
c2 := cache.New[string, *MyVal](1000, 5*time.Minute,
cache.WithStaleWindow[string, *MyVal](15*time.Minute))
entry, ok := c2.GetEntry("key")
if ok && entry.Stale { /* serve stale, trigger background refresh */ }
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache[K comparable, V any] struct { // contains filtered or unexported fields }
Cache is a generic LRU+TTL cache.
func New ¶
New creates a new Cache with the given max size and TTL. maxSize must be > 0; ttl must be > 0.
Example ¶
The cache is an LRU with a TTL. Give it a mock clock and expiry becomes deterministic: no sleeps in the test.
package main
import (
"fmt"
"time"
"github.com/baditaflorin/go-common/cache"
"github.com/baditaflorin/go-common/clock"
)
func main() {
clk := clock.NewMock(time.Date(2026, 10, 17, 12, 0, 0, 0, time.UTC))
c := cache.New[string, string](2, time.Minute, cache.WithClock[string, string](clk))
c.Set("a", "1")
c.Set("b", "2")
c.Set("c", "3") // over capacity: the least recently used key, "a", is evicted
_, okA := c.Get("a")
vC, okC := c.Get("c")
fmt.Println(okA, vC, okC, c.Len())
clk.Advance(2 * time.Minute)
_, okC = c.Get("c")
fmt.Println(okC)
}
Output: false 3 true 2 false
func (*Cache[K, V]) Delete ¶
func (c *Cache[K, V]) Delete(key K)
Delete removes key from the cache. No-op if absent.
func (*Cache[K, V]) Get ¶
Get retrieves the value for key. Returns the value and true if the entry exists and is fresh. Returns the zero value and false otherwise. Use GetEntry when you need stale-window semantics.
func (*Cache[K, V]) GetEntry ¶
GetEntry retrieves an entry for key including stale metadata. ok=true means the key was found (possibly stale if Stale=true). ok=false means the key is absent or expired beyond the stale window.
func (*Cache[K, V]) Len ¶
Len returns the number of entries currently in the cache (including potentially expired entries not yet evicted).
func (*Cache[K, V]) Set ¶
func (c *Cache[K, V]) Set(key K, value V)
Set stores value under key with a TTL starting from now. If the key already exists its value and TTL are refreshed and it is moved to the front of the LRU. If the cache is full, the LRU entry is evicted before inserting.
func (*Cache[K, V]) Snapshot ¶ added in v0.133.0
Snapshot returns a shallow copy of live entries, including entries within the configured stale window. It removes expired entries without refreshing their LRU position. Mutating the returned map does not change the cache; pointer-valued V values still refer to the same underlying objects.
type Entry ¶
type Entry[V any] struct { Value V Stale bool // true when TTL expired but within stale window Expires time.Time // absolute expiry of this entry's fresh period }
Entry is the value returned by GetEntry, carrying the value and freshness metadata.
type Option ¶
type Option[K comparable, V any] func(*Cache[K, V])
Option configures a Cache at construction time.
func WithClock ¶
func WithClock[K comparable, V any](c clock.Clock) Option[K, V]
WithClock injects a clock.Clock for deterministic testing.
func WithStaleWindow ¶
func WithStaleWindow[K comparable, V any](d time.Duration) Option[K, V]
WithStaleWindow sets the duration beyond TTL during which a stale entry is returned (with Entry.Stale=true) instead of a miss. A stale window of zero (the default) means entries are hard-evicted at TTL expiry.