cache

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 25, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package cache is the kit's transport-agnostic key/value cache abstraction.

Implementations:

  • NewMemory[V]() — in-process LRU-ish cache with TTL eviction
  • (future) NewRedis[V](client, prefix) — Redis-backed adapter

Consumers code against Cache[V], pick an implementation at wiring time, and can swap memory ↔ Redis without touching call sites.

Index

Constants

This section is empty.

Variables

View Source
var ErrMiss = errors.New("cache: miss")

ErrMiss is returned by Get when the key is absent or has expired.

Functions

This section is empty.

Types

type Cache

type Cache[V any] interface {
	Get(ctx context.Context, key string) (V, error)
	Set(ctx context.Context, key string, value V, ttl time.Duration) error
	Delete(ctx context.Context, key string) error

	// GetOrLoad fetches the cached value or calls loader on miss, storing the
	// result with ttl before returning. Concurrent loaders for the same key
	// are coalesced: only one loader runs, the rest wait for the result.
	GetOrLoad(ctx context.Context, key string, ttl time.Duration, loader func(ctx context.Context) (V, error)) (V, error)

	// Clear flushes the entire namespace.
	Clear(ctx context.Context) error
}

Cache is the common interface backed by every implementation.

type Memory

type Memory[V any] struct {
	// contains filtered or unexported fields
}

Memory is an in-process Cache[V] with TTL eviction and single-flight loading. Suitable for low-cardinality / latency-sensitive caches that don't need cross-instance sharing. Thread-safe.

func NewMemory

func NewMemory[V any]() *Memory[V]

func (*Memory[V]) Clear

func (m *Memory[V]) Clear(_ context.Context) error

func (*Memory[V]) Delete

func (m *Memory[V]) Delete(_ context.Context, key string) error

func (*Memory[V]) Get

func (m *Memory[V]) Get(ctx context.Context, key string) (V, error)

func (*Memory[V]) GetOrLoad

func (m *Memory[V]) GetOrLoad(
	ctx context.Context,
	key string,
	ttl time.Duration,
	loader func(ctx context.Context) (V, error),
) (V, error)

func (*Memory[V]) Len

func (m *Memory[V]) Len() int

Len returns the current entry count (live + expired). Useful for tests.

func (*Memory[V]) Set

func (m *Memory[V]) Set(ctx context.Context, key string, value V, ttl time.Duration) error

func (*Memory[V]) SetClock

func (m *Memory[V]) SetClock(now func() time.Time)

SetClock replaces the time source. Use in tests to drive expiry without real sleeps.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL