Documentation
¶
Overview ¶
Package cache provides a two-level cache (local L1 + remote L2) with circuit breaker, Prometheus/OpenTelemetry metrics, and structured value support.
Index ¶
- Constants
- Variables
- type Cache
- func (c *Cache) Del(ctx context.Context, key []byte) error
- func (c *Cache) DeleteFromLocalCache(key []byte)
- func (c *Cache) DeleteFromRemoteCache(ctx context.Context, key []byte) error
- func (c *Cache) Get(ctx context.Context, key []byte) ([]byte, error)
- func (c *Cache) GetStruct(ctx context.Context, key string, dest any) error
- func (c *Cache) Ready(ctx context.Context) error
- func (c *Cache) Set(ctx context.Context, key, value []byte) error
- func (c *Cache) SetExStruct(ctx context.Context, key string, value any, ttl time.Duration) error
- func (c *Cache) SetExp(ctx context.Context, key, value []byte, ttl time.Duration) error
- func (c *Cache) SetStruct(ctx context.Context, key string, value any) error
- type Cacher
- type Coder
- type CustomOption
- func WithCBConsecutiveFailures(v uint32) CustomOption
- func WithCBEnabled(v bool) CustomOption
- func WithCBMaxRequests(v uint32) CustomOption
- func WithCBTimeout(v time.Duration) CustomOption
- func WithCoder(v Coder) CustomOption
- func WithGracefulDegradation(staleTTL time.Duration, staleCacheSize ...int) CustomOption
- func WithLocalCacheFreeCache(cacheSize int, localCacheTTL time.Duration) CustomOption
- func WithLocalCacheTinyLFU(cacheSize int, localCacheTTL time.Duration) CustomOption
- func WithPrefixKey(v []byte) CustomOption
- func WithPreload(data map[string][]byte) CustomOption
- func WithRedisConn(conn redis.UniversalClient, remoteCacheTTL time.Duration) CustomOption
- func WithRemoteCache(rc RemoteCache, remoteCacheTTL time.Duration) CustomOption
- func WithStatsOTEL(stats *StatsOTEL) CustomOption
- func WithStatsProm(stats *StatsProm) CustomOption
- type FreeCache
- type JSONCoder
- type LocalCache
- type Mocked
- func (m *Mocked) Del(ctx context.Context, key []byte) error
- func (m *Mocked) DeleteFromLocalCache(key []byte)
- func (m *Mocked) DeleteFromRemoteCache(ctx context.Context, key []byte) error
- func (m *Mocked) Get(ctx context.Context, key []byte) ([]byte, error)
- func (m *Mocked) GetStruct(ctx context.Context, key string, dest any) error
- func (m *Mocked) Ready(ctx context.Context) error
- func (m *Mocked) Set(ctx context.Context, key, value []byte) error
- func (m *Mocked) SetExStruct(ctx context.Context, key string, value any, ttl time.Duration) error
- func (m *Mocked) SetExp(ctx context.Context, key, value []byte, ttl time.Duration) error
- func (m *Mocked) SetStruct(ctx context.Context, key string, value any) error
- type MsgPackCoder
- type RedisRemoteCache
- func (r *RedisRemoteCache) Del(ctx context.Context, key string) error
- func (r *RedisRemoteCache) Get(ctx context.Context, key string) ([]byte, error)
- func (r *RedisRemoteCache) Ping(ctx context.Context) error
- func (r *RedisRemoteCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
- type RemoteCache
- type StatsOTEL
- type StatsProm
- type TinyLFU
Constants ¶
const (
// LabelName is the Prometheus/OTEL label key used to identify the cache instance.
LabelName = "cache_name"
)
Variables ¶
var ( // ErrCacheMiss is returned when the requested key is not found in the cache. ErrCacheMiss = errors.New("cache key is missing") // ErrKeyEmpty is returned when an empty key is provided to a cache operation. ErrKeyEmpty = errors.New("key is empty") // ErrInitCache is returned when cache initialization fails due to missing RemoteCache and LocalCache. ErrInitCache = errors.New("can not init cache : RemoteCache or LocalCache must not be nil") // ErrConvertingToBytes is returned when a cache value cannot be converted to []byte. ErrConvertingToBytes = errors.New("type error when converting to []byte") )
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache implements Cacher with optional local (L1) and remote (L2) layers.
func New ¶
func New(name string, options ...CustomOption) (*Cache, error)
New creates a new Cache. At least one of RemoteCache or LocalCache must be set.
func (*Cache) DeleteFromLocalCache ¶
DeleteFromLocalCache removes a key from the local cache and the stale cache.
func (*Cache) DeleteFromRemoteCache ¶
DeleteFromRemoteCache removes a key from the remote cache only.
func (*Cache) Get ¶
Get retrieves a value by key, checking the local cache first, then falling back to the remote cache.
func (*Cache) Set ¶
Set stores a key-value pair in both local and remote caches using the configured TTL.
func (*Cache) SetExStruct ¶
SetExStruct encodes value and stores it in the cache with a custom TTL.
type Cacher ¶
type Cacher interface {
Del(ctx context.Context, key []byte) error
Set(ctx context.Context, key, value []byte) error
SetExp(ctx context.Context, key, value []byte, ttl time.Duration) error
Get(ctx context.Context, key []byte) ([]byte, error)
DeleteFromLocalCache(key []byte)
DeleteFromRemoteCache(ctx context.Context, key []byte) error
Ready(ctx context.Context) error
GetStruct(context.Context, string, any) error
SetStruct(context.Context, string, any) error
SetExStruct(context.Context, string, any, time.Duration) error
}
Cacher defines the interface for a two-level cache (local + remote).
type CustomOption ¶
type CustomOption func(*customConfig)
CustomOption is a functional option for configuring a simple Cache.
func WithCBConsecutiveFailures ¶
func WithCBConsecutiveFailures(v uint32) CustomOption
WithCBConsecutiveFailures sets the number of consecutive failures before the circuit breaker trips.
func WithCBEnabled ¶
func WithCBEnabled(v bool) CustomOption
WithCBEnabled enables or disables the circuit breaker for remote cache operations.
func WithCBMaxRequests ¶
func WithCBMaxRequests(v uint32) CustomOption
WithCBMaxRequests sets the maximum number of requests allowed in the half-open state.
func WithCBTimeout ¶
func WithCBTimeout(v time.Duration) CustomOption
WithCBTimeout sets the circuit breaker timeout duration.
func WithCoder ¶
func WithCoder(v Coder) CustomOption
WithCoder sets the encoder/decoder used for cache value serialization.
func WithGracefulDegradation ¶
func WithGracefulDegradation(staleTTL time.Duration, staleCacheSize ...int) CustomOption
WithGracefulDegradation enables a stale cache that is consulted when the circuit breaker is open and the primary L1 misses. staleTTL controls how long entries survive in the stale cache (should be significantly longer than the primary L1 TTL). A zero staleTTL means entries never expire (eviction still applies when the cache is full). staleCacheSize sets the maximum number of items in the stale TinyLFU cache; 0 defaults to 10 000.
func WithLocalCacheFreeCache ¶
func WithLocalCacheFreeCache(cacheSize int, localCacheTTL time.Duration) CustomOption
WithLocalCacheFreeCache configures a FreeCache-based local cache with the given size and TTL.
func WithLocalCacheTinyLFU ¶
func WithLocalCacheTinyLFU(cacheSize int, localCacheTTL time.Duration) CustomOption
WithLocalCacheTinyLFU configures a TinyLFU-based local cache with the given size and TTL.
func WithPrefixKey ¶
func WithPrefixKey(v []byte) CustomOption
WithPrefixKey overrides the key namespace prefix. Pass nil to disable prefixing.
func WithPreload ¶
func WithPreload(data map[string][]byte) CustomOption
WithPreload warms up the local cache (and stale cache if configured) on startup with the provided key-value pairs. Data is written to L1 only; the remote cache is not touched. Keys are subject to the configured prefix.
func WithRedisConn ¶
func WithRedisConn(conn redis.UniversalClient, remoteCacheTTL time.Duration) CustomOption
WithRedisConn sets the remote cache to a Redis connection.
func WithRemoteCache ¶ added in v1.0.1
func WithRemoteCache(rc RemoteCache, remoteCacheTTL time.Duration) CustomOption
WithRemoteCache sets the remote cache (L2) implementation and its default TTL.
func WithStatsOTEL ¶
func WithStatsOTEL(stats *StatsOTEL) CustomOption
WithStatsOTEL sets the OpenTelemetry stats collector.
func WithStatsProm ¶
func WithStatsProm(stats *StatsProm) CustomOption
WithStatsProm sets the Prometheus stats collector.
type FreeCache ¶
type FreeCache struct {
// contains filtered or unexported fields
}
FreeCache is a LocalCache implementation backed by freecache.
func NewFreeCache ¶
NewFreeCache size is in bytes
type JSONCoder ¶
type JSONCoder struct{}
JSONCoder encodes and decodes cache values using JSON serialization.
type LocalCache ¶
type LocalCache interface {
Set(key []byte, data []byte) error
SetExp(key []byte, data []byte, ttl time.Duration) error
Get(key []byte) ([]byte, error)
Del(key []byte)
}
LocalCache defines the interface for a local in-process cache (L1 layer).
type Mocked ¶
Mocked is a testify mock implementing Cacher for unit tests.
func (*Mocked) DeleteFromLocalCache ¶
DeleteFromLocalCache implements Cacher.
func (*Mocked) DeleteFromRemoteCache ¶
DeleteFromRemoteCache implements Cacher.
func (*Mocked) SetExStruct ¶
SetExStruct implements Cacher.
type MsgPackCoder ¶
type MsgPackCoder struct{}
MsgPackCoder encodes and decodes cache values using MessagePack serialization.
type RedisRemoteCache ¶ added in v1.0.1
type RedisRemoteCache struct {
// contains filtered or unexported fields
}
RedisRemoteCache adapts redis.UniversalClient to the RemoteCache interface.
func NewRedisRemoteCache ¶ added in v1.0.1
func NewRedisRemoteCache(client redis.UniversalClient) *RedisRemoteCache
NewRedisRemoteCache creates a RemoteCache backed by Redis.
func (*RedisRemoteCache) Del ¶ added in v1.0.1
func (r *RedisRemoteCache) Del(ctx context.Context, key string) error
Del removes a key.
func (*RedisRemoteCache) Get ¶ added in v1.0.1
Get retrieves a value by key. Returns ErrCacheMiss when the key does not exist.
type RemoteCache ¶ added in v1.0.1
type RemoteCache interface {
Get(ctx context.Context, key string) ([]byte, error)
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
Del(ctx context.Context, key string) error
Ping(ctx context.Context) error
}
RemoteCache defines the interface for a remote cache (L2 layer). Get must return ErrCacheMiss when the requested key does not exist.
type StatsOTEL ¶
type StatsOTEL struct {
HitsLocal metric.Float64Counter
MissesLocal metric.Float64Counter
HitsRemote metric.Float64Counter
MissesRemote metric.Float64Counter
HitsStale metric.Float64Counter
SetLocal metric.Float64Counter
SetRemote metric.Float64Counter
SetTotal metric.Float64Counter
CBOpen metric.Float64Counter
CBTooManyRequests metric.Float64Counter
CBState metric.Float64Gauge
Duration metric.Float64Histogram
}
StatsOTEL holds OpenTelemetry counters for cache hit, miss, and set operations.
func GetStatsOTEL ¶
GetStatsOTEL creates a new StatsOTEL instance with OpenTelemetry counters for the given meter name.
type StatsProm ¶
type StatsProm struct {
HitsLocal *prometheus.CounterVec
MissesLocal *prometheus.CounterVec
HitsRemote *prometheus.CounterVec
MissesRemote *prometheus.CounterVec
HitsStale *prometheus.CounterVec
SetLocal *prometheus.CounterVec
SetRemote *prometheus.CounterVec
SetTotal *prometheus.CounterVec
CBOpen *prometheus.CounterVec
CBTooManyRequests *prometheus.CounterVec
CBState *prometheus.GaugeVec
Duration *prometheus.HistogramVec
}
StatsProm contains accumulated stats.
func GetStatsProm ¶
GetStatsProm creates a new StatsProm instance with Prometheus counter vectors for the given namespace and subsystem.
type TinyLFU ¶
type TinyLFU struct {
// contains filtered or unexported fields
}
TinyLFU is a concurrency-safe local cache using the TinyLFU admission policy.
func NewTinyLFU ¶
NewTinyLFU creates a TinyLFU cache. size is the maximum number of items.