go.bigb.es/auxilia

v0.2.0
Doc Versions Source

Documentation

Package cache provides a generic, TTL-based, in-memory key-value cache with background expiry sweeping and configurable expiration strategies.

Index

Constants

const (
	// NoExpiration indicates that an item should never expire.
	NoExpiration time.Duration = -2
	// DefaultExpiration indicates that an item should use the cache's default expiration.
	DefaultExpiration time.Duration = -1
)

Variables

var (
	// ErrNotExists is returned when an operation requires a key that is not present.
	ErrNotExists = errors.New("cache: record does not exist")
	// ErrAlreadyExists is returned when an insert finds the key already present.
	ErrAlreadyExists = errors.New("cache: record already exists")
)

Types

T type Cache

src
type Cache[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Cache is the exported handle embedding *cache plus janitor.

f func New

src
func New[K comparable, V any](defaultExpiration, cleanupInterval time.Duration) *Cache[K, V]

New creates a new Cache with the given default expiration and cleanup interval. The background janitor is started immediately with context.Background.

f func NewFromItems

src
func NewFromItems[K comparable, V any](defaultExpiration, cleanupInterval time.Duration, items map[K]Item[V]) *Cache[K, V]

NewFromItems creates a new Cache pre-seeded with items. The background janitor is started immediately with context.Background.

f func NewFromItemsWithPolicy

src
func NewFromItemsWithPolicy[K comparable, V any](defaultExpiration, cleanupInterval time.Duration, items map[K]Item[V], policy ExpirationPolicy) *Cache[K, V]

NewFromItemsWithPolicy creates a new Cache pre-seeded with items and using the given expiration policy. The background janitor is started immediately with context.Background.

f func NewInitialized

src
func NewInitialized[K comparable, V any](defaultExpiration, cleanupInterval time.Duration) *Cache[K, V]

NewInitialized creates a new Cache with the given default expiration and cleanup interval but does NOT start the background janitor. The caller must call Start to begin periodic expiry sweeping.

f func NewInitializedWithPolicy

src
func NewInitializedWithPolicy[K comparable, V any](defaultExpiration, cleanupInterval time.Duration, policy ExpirationPolicy) *Cache[K, V]

NewInitializedWithPolicy creates a new Cache with the given default expiration, cleanup interval, and expiration policy but does NOT start the background janitor. The caller must call Start to begin periodic expiry sweeping.

f func NewWithPolicy

src
func NewWithPolicy[K comparable, V any](defaultExpiration, cleanupInterval time.Duration, policy ExpirationPolicy) *Cache[K, V]

NewWithPolicy creates a new Cache with the given default expiration, cleanup interval, and expiration policy. The background janitor is started immediately with context.Background.

m func (Cache) Add

src
func (c Cache) Add(k K, x V, d time.Duration) error

Add inserts x for k only if k is absent or expired. It returns ErrAlreadyExists if a live entry already exists.

m func (Cache) Delete

src
func (c Cache) Delete(k K)

Delete removes the key k from the cache. If an onDeletion callback is registered, it is called after the lock is released.

m func (Cache) DeleteExpired

src
func (c Cache) DeleteExpired()

DeleteExpired removes all expired items from the cache. If an onDeletion callback is registered, it is called for each evicted item after the lock is released.

m func (Cache) Flush

src
func (c Cache) Flush()

Flush removes all items from the cache.

m func (Cache) Get

src
func (c Cache) Get(k K) (V, bool)

Get returns the value for k if it exists and is not expired. The second return value indicates whether the key was found. Expired items are not deleted by Get.

m func (Cache) GetOrInsert

src
func (c Cache) GetOrInsert(k K, insertV V, insertD time.Duration) (V, bool)

GetOrInsert atomically retrieves the value for k or inserts insertV if k is missing or expired. It returns the value and true if the key was already present and valid, or (insertV, false) if the value was inserted. Eviction callbacks fire after the lock is released.

m func (Cache) GetWithExpiration

src
func (c Cache) GetWithExpiration(k K) (V, time.Time, bool)

GetWithExpiration returns the value and expiration time for k. The third return value indicates whether the key was found and unexpired. A zero expiration time means the item does not expire.

m func (Cache) GetWithTouch

src
func (c Cache) GetWithTouch(k K, d time.Duration) (V, bool)

GetWithTouch atomically retrieves the value for k and refreshes its expiration. Returns (zero, false) if the key is missing or expired.

m func (Cache) ItemCount

src
func (c Cache) ItemCount() int

ItemCount returns the number of items in the cache, including expired items that have not yet been swept.

m func (Cache) ItemIterator

src
func (c Cache) ItemIterator() collect.ListIterator[collect.Tuple2[K, Item[V]]]

ItemIterator returns a lazy iterator over all non-expired items in the cache. The iterator yields collect.Tuple2 pairs of (key, Item).

m func (Cache) ItemList

src
func (c Cache) ItemList() map[K]Item[V]

ItemList returns a snapshot of all non-expired items in the cache.

m func (Cache) OnDeletion

src
func (c Cache) OnDeletion(f func(K, V, DeletionCause))

OnDeletion sets the deletion callback. Deprecated: use OnDeletionAppend.

m func (Cache) OnDeletionAppend

src
func (c Cache) OnDeletionAppend(f func(K, V, DeletionCause))

OnDeletionAppend prepends f in front of the existing callback chain. If f is nil the callback is disabled entirely.

m func (Cache) Replace

src
func (c Cache) Replace(k K, x V, d time.Duration) error

Replace updates the value for k only if k is present and unexpired. It returns ErrNotExists if the key is missing or expired.

m func (Cache) Set

src
func (c Cache) Set(k K, x V, d time.Duration)

Set stores the value x for the key k with the given expiration duration.

m func (Cache) SetDefault

src
func (c Cache) SetDefault(k K, x V)

SetDefault stores the value x for the key k using the cache's default expiration.

m func (*Cache[K, V]) Start

src
func (c *Cache[K, V]) Start(ctx context.Context)

Start starts the background janitor goroutine for periodic expiry sweeping.

m func (*Cache[K, V]) Stop

src
func (c *Cache[K, V]) Stop()

Stop stops the background janitor goroutine.

m func (Cache) Touch

src
func (c Cache) Touch(k K, d time.Duration) bool

Touch refreshes the expiration on an existing non-expired item. It returns true if the key was found and refreshed.

T type DeletionCause

src
type DeletionCause int

DeletionCause indicates why an item was removed from the cache.

const (

	// Evicted means the item was removed because it expired.
	Evicted DeletionCause
	// Deleted means the item was removed by an explicit Delete call.
	Deleted
)

T type ExpirationPolicy

src
type ExpirationPolicy struct {
	// contains filtered or unexported fields
}

ExpirationPolicy controls how the cache determines whether an item has expired. Use WriteTTL, SlidingTTL, or NewExpirationPolicy to create a policy.

f func NewExpirationPolicy

src
func NewExpirationPolicy(fn func(expiration time.Time, lastAccess time.Time, ttl time.Duration) bool, touchOnRead bool) ExpirationPolicy

NewExpirationPolicy creates a custom ExpirationPolicy.

f func SlidingTTL

src

SlidingTTL returns an ExpirationPolicy that resets the expiration window on every read (Get, GetWithExpiration, GetOrInsert).

f func WriteTTL

src

WriteTTL returns an ExpirationPolicy that expires items based on their write-time deadline (the default behaviour).

T type Item

src
type Item[V any] struct {
	Object     V
	Expiration time.Time     // absolute write-time deadline; zero means no expiration
	LastAccess time.Time     // last access time; used by SlidingTTL
	TTL        time.Duration // resolved TTL used to compute Expiration
}

Item wraps a cached value with an absolute expiration timestamp.

Source Files