Documentation
¶
Index ¶
- Variables
- func Key(keyParts ...string) string
- type Cache
- type EvictionHandler
- type EvictionHandlerFactory
- type EvictionPolicy
- type FIFOHandler
- type GetFunc
- type KeyBuilder
- type LFUHandler
- type LRUHandler
- type LoaderFunc
- type MemoryOption
- type NoOpEvictionHandler
- type PrefixKeyBuilder
- type RedisOption
- type Serializer
- type SetFunc
- type SingleflightMixin
- type Store
Constants ¶
This section is empty.
Variables ¶
var ( // ErrStoreRequiresName indicates the cache store requires a name. ErrStoreRequiresName = errors.New("cache store requires a name") // ErrMemoryLimitExceeded is returned when the cache cannot accept additional entries due to size limits or unavailable eviction candidates. ErrMemoryLimitExceeded = errors.New("memory cache size limit exceeded") // ErrCacheClosed is returned when cache operations are attempted after Close has been called. ErrCacheClosed = errors.New("cache closed") // ErrLoaderRequired is returned when GetOrLoad is called without providing a loader. ErrLoaderRequired = errors.New("cache loader is required") )
Functions ¶
Types ¶
type Cache ¶
type Cache[T any] interface { io.Closer // Get retrieves a value by key. Returns the value and true if found, zero value and false if not found. Get(ctx context.Context, key string) (T, bool) // GetOrLoad retrieves a value by key or computes it using the provided loader when missing. // Implementations must ensure concurrent calls for the same key only trigger a single loader execution. GetOrLoad(ctx context.Context, key string, loader LoaderFunc[T], ttl ...time.Duration) (T, error) // Set stores a value with the given key. If ttl is provided and > 0, the entry will expire after the duration. Set(ctx context.Context, key string, value T, ttl ...time.Duration) error // Contains checks if a key exists in the cache. Contains(ctx context.Context, key string) bool // Delete removes a key from the cache. Delete(ctx context.Context, key string) error // Clear removes all entries from the cache. Clear(ctx context.Context) error // Keys returns all keys in the cache, optionally filtered by prefix. Keys(ctx context.Context, prefix ...string) ([]string, error) // ForEach iterates over all key-value pairs in the cache, optionally filtered by prefix. // The iteration stops if the callback returns false. ForEach(ctx context.Context, callback func(key string, value T) bool, prefix ...string) error // Size returns the number of entries in the cache. Size(ctx context.Context) (int64, error) }
Cache defines the interface for a generic key-value cache.
func NewMemory ¶
func NewMemory[T any](opts ...MemoryOption) Cache[T]
NewMemory constructs an in-memory cache using functional options.
type EvictionHandler ¶
type EvictionHandler interface {
// OnAccess is called when an entry is accessed.
OnAccess(key string)
// OnInsert is called when a new entry is inserted.
OnInsert(key string)
// OnEvict is called when an entry is evicted.
OnEvict(key string)
// SelectEvictionCandidate selects a key to evict, returns empty string if no candidate.
SelectEvictionCandidate() string
// Reset clears all eviction tracking data.
Reset()
}
EvictionHandler defines the interface for handling cache eviction.
type EvictionHandlerFactory ¶
type EvictionHandlerFactory struct{}
EvictionHandlerFactory creates eviction handlers based on policy.
func (*EvictionHandlerFactory) CreateHandler ¶
func (f *EvictionHandlerFactory) CreateHandler(policy EvictionPolicy) EvictionHandler
type EvictionPolicy ¶
type EvictionPolicy int
EvictionPolicy defines the eviction strategy for cache when it reaches max size.
const ( // EvictionPolicyNone disables eviction tracking (used for unlimited caches). EvictionPolicyNone EvictionPolicy = iota // EvictionPolicyLRU evicts least recently used entries when cache is full. EvictionPolicyLRU // EvictionPolicyLFU evicts least frequently used entries when cache is full. EvictionPolicyLFU // EvictionPolicyFIFO evicts oldest entries when cache is full. EvictionPolicyFIFO )
type FIFOHandler ¶
type FIFOHandler struct {
// contains filtered or unexported fields
}
FIFOHandler implements First In First Out eviction policy.
func NewFIFOHandler ¶
func NewFIFOHandler() *FIFOHandler
NewFIFOHandler creates a new FIFO eviction handler.
func (*FIFOHandler) OnAccess ¶
func (h *FIFOHandler) OnAccess(key string)
func (*FIFOHandler) OnEvict ¶
func (h *FIFOHandler) OnEvict(key string)
func (*FIFOHandler) OnInsert ¶
func (h *FIFOHandler) OnInsert(key string)
func (*FIFOHandler) Reset ¶
func (h *FIFOHandler) Reset()
func (*FIFOHandler) SelectEvictionCandidate ¶
func (h *FIFOHandler) SelectEvictionCandidate() string
type KeyBuilder ¶
type KeyBuilder interface {
// Build constructs a cache key from the given base key
Build(keyParts ...string) string
}
KeyBuilder defines the interface for building cache keys with different naming strategies.
type LFUHandler ¶
type LFUHandler struct {
// contains filtered or unexported fields
}
LFUHandler implements Least Frequently Used eviction policy using frequency buckets. This implementation achieves O(1) time complexity for all operations.
func NewLFUHandler ¶
func NewLFUHandler() *LFUHandler
NewLFUHandler creates a new LFU eviction handler.
func (*LFUHandler) OnAccess ¶
func (h *LFUHandler) OnAccess(key string)
func (*LFUHandler) OnEvict ¶
func (h *LFUHandler) OnEvict(key string)
func (*LFUHandler) OnInsert ¶
func (h *LFUHandler) OnInsert(key string)
func (*LFUHandler) Reset ¶
func (h *LFUHandler) Reset()
func (*LFUHandler) SelectEvictionCandidate ¶
func (h *LFUHandler) SelectEvictionCandidate() string
type LRUHandler ¶
type LRUHandler struct {
// contains filtered or unexported fields
}
LRUHandler implements Least Recently Used eviction policy.
func NewLRUHandler ¶
func NewLRUHandler() *LRUHandler
NewLRUHandler creates a new LRU eviction handler.
func (*LRUHandler) OnAccess ¶
func (h *LRUHandler) OnAccess(key string)
func (*LRUHandler) OnEvict ¶
func (h *LRUHandler) OnEvict(key string)
func (*LRUHandler) OnInsert ¶
func (h *LRUHandler) OnInsert(key string)
func (*LRUHandler) Reset ¶
func (h *LRUHandler) Reset()
func (*LRUHandler) SelectEvictionCandidate ¶
func (h *LRUHandler) SelectEvictionCandidate() string
type LoaderFunc ¶
LoaderFunc defines a function that loads a value for a given key when cache miss happens.
type MemoryOption ¶
type MemoryOption func(*memoryConfig)
MemoryOption configures the behavior of NewMemory caches.
func WithMemDefaultTTL ¶
func WithMemDefaultTTL(ttl time.Duration) MemoryOption
WithMemDefaultTTL sets a global TTL applied when Set is called without explicit ttl.
func WithMemEvictionPolicy ¶
func WithMemEvictionPolicy(policy EvictionPolicy) MemoryOption
WithMemEvictionPolicy selects the eviction strategy used when max size is enforced.
func WithMemGCInterval ¶
func WithMemGCInterval(interval time.Duration) MemoryOption
WithMemGCInterval sets the interval used by the background garbage collector.
func WithMemMaxSize ¶
func WithMemMaxSize(size int64) MemoryOption
WithMemMaxSize sets the maximum number of entries the cache may hold. A value <= 0 disables size limits.
type NoOpEvictionHandler ¶
type NoOpEvictionHandler struct{}
NoOpEvictionHandler is used when eviction policy is EvictionPolicyNone.
func NewNoOpEvictionHandler ¶
func NewNoOpEvictionHandler() *NoOpEvictionHandler
func (*NoOpEvictionHandler) OnAccess ¶
func (h *NoOpEvictionHandler) OnAccess(key string)
func (*NoOpEvictionHandler) OnEvict ¶
func (h *NoOpEvictionHandler) OnEvict(key string)
func (*NoOpEvictionHandler) OnInsert ¶
func (h *NoOpEvictionHandler) OnInsert(key string)
func (*NoOpEvictionHandler) Reset ¶
func (h *NoOpEvictionHandler) Reset()
func (*NoOpEvictionHandler) SelectEvictionCandidate ¶
func (h *NoOpEvictionHandler) SelectEvictionCandidate() string
type PrefixKeyBuilder ¶
type PrefixKeyBuilder struct {
// contains filtered or unexported fields
}
PrefixKeyBuilder implements KeyBuilder with prefix-based naming strategy.
func NewPrefixKeyBuilder ¶
func NewPrefixKeyBuilder(prefix string) *PrefixKeyBuilder
NewPrefixKeyBuilder creates a new prefix-based key builder with default ":" separator.
func NewPrefixKeyBuilderWithSeparator ¶
func NewPrefixKeyBuilderWithSeparator(prefix, separator string) *PrefixKeyBuilder
NewPrefixKeyBuilderWithSeparator creates a new prefix-based key builder with custom separator.
func (*PrefixKeyBuilder) Build ¶
func (k *PrefixKeyBuilder) Build(keyParts ...string) string
Build constructs a cache key with prefix.
type RedisOption ¶
type RedisOption func(*redisConfig)
RedisOption configures Redis-backed cache instances.
func WithRedisDefaultTTL ¶
func WithRedisDefaultTTL(ttl time.Duration) RedisOption
WithRedisDefaultTTL sets a fallback TTL applied when Set is invoked without explicit duration.
type Serializer ¶
type Serializer[T any] interface { // Serialize converts a value of type T into a byte array for storage Serialize(value T) ([]byte, error) // Deserialize converts a byte array back into a value of type T Deserialize(data []byte) (T, error) }
Serializer handles serialization/deserialization of cache values.
type SingleflightMixin ¶
type SingleflightMixin[T any] struct { // contains filtered or unexported fields }
SingleflightMixin provides reusable singleflight-backed GetOrLoad logic that cache implementations can embed to prevent cache stampede.
Usage:
type MyCache[T any] struct {
// ... other fields ...
loadMixin SingleflightMixin[T]
}
func (c *MyCache[T]) GetOrLoad(ctx context.Context, key string, loader LoaderFunc[T], ttl ...time.Duration) (T, error) {
return c.loadMixin.GetOrLoad(ctx, key, loader, ttl, c.Get, c.Set)
}
func (*SingleflightMixin[T]) GetOrLoad ¶
func (m *SingleflightMixin[T]) GetOrLoad( ctx context.Context, cacheKey string, loader LoaderFunc[T], ttl []time.Duration, getFn GetFunc[T], setFn SetFunc[T], ) (value T, _ error)
GetOrLoad retrieves a value from cache or loads it using the provided loader, coordinating concurrent requests for the same cacheKey to prevent cache stampede.
type Store ¶
type Store interface {
// Name returns the name of the store.
Name() string
// Get retrieves raw bytes by key. Returns the data and true if found, nil and false if not found.
Get(ctx context.Context, key string) ([]byte, bool)
// Set stores raw bytes with the given key. If ttl is provided and > 0, the entry will expire after the duration.
Set(ctx context.Context, key string, data []byte, ttl ...time.Duration) error
// Contains checks if a key exists in the cache.
Contains(ctx context.Context, key string) bool
// Delete removes a key from the cache.
Delete(ctx context.Context, key string) error
// Clear removes all entries from the cache.
Clear(ctx context.Context, prefix string) error
// Keys returns all keys in the cache, optionally filtered by prefix.
Keys(ctx context.Context, prefix string) ([]string, error)
// ForEachRaw iterates over all key-value pairs in the cache, optionally filtered by prefix.
// The iteration stops if the callback returns false.
ForEach(ctx context.Context, prefix string, callback func(key string, data []byte) bool) error
// Size returns the number of entries in the cache.
Size(ctx context.Context, prefix string) (int64, error)
// Close closes the cache and releases any resources.
Close(ctx context.Context) error
}
Store defines the interface for the underlying cache storage implementation. This interface works with raw bytes and can be implemented by different backends like Badger, Redis, etc. It's designed to be injected as a singleton via fx.