Documentation
¶
Index ¶
- Constants
- Variables
- func NewError(msg string) error
- type Action
- type Cache
- type ConsoleLogger
- type InvalidationEvent
- type JSONMarshaller
- type LFUCache
- type LFUCacheFactory
- type LRUCache
- type LRUCacheFactory
- type LocalCache
- type LocalCacheConfig
- type LocalCacheFactory
- type LocalCacheMetrics
- type Logger
- type Marshaller
- type NoOpLogger
- type Options
- type Stats
- type Store
- type SyncedCache
- func (sc *SyncedCache) Clear(ctx context.Context) error
- func (sc *SyncedCache) Close() error
- func (sc *SyncedCache) Delete(ctx context.Context, key string) error
- func (sc *SyncedCache) Get(ctx context.Context, key string) (any, bool)
- func (sc *SyncedCache) Set(ctx context.Context, key string, value any) error
- func (sc *SyncedCache) SetWithInvalidate(ctx context.Context, key string, value any) error
- func (sc *SyncedCache) Stats() Stats
- type Synchronizer
Constants ¶
const ( ActionSet = types.Set ActionInvalidate = types.Invalidate ActionDelete = types.Delete ActionClear = types.Clear )
Action constants for cache operations
Variables ¶
var ErrCacheClosed = NewError("cache is closed")
ErrCacheClosed is returned when operations are performed on a closed cache.
var ErrInvalidConfig = NewError("invalid cache configuration")
ErrInvalidConfig is returned when options are invalid.
Functions ¶
Types ¶
type Cache ¶
type Cache interface {
// Get retrieves a value from the cache.
// Returns the value and true if found, nil and false otherwise.
Get(ctx context.Context, key string) (any, bool)
// Set stores a value in the cache and propagates it to other pods.
// The value is stored in both local and remote storage, and other pods
// receive the value directly to update their local caches.
Set(ctx context.Context, key string, value any) error
// SetWithInvalidate stores a value in the cache and invalidates it on other pods.
// The value is stored in both local and remote storage, but other pods
// only receive an invalidation event and must fetch from Redis if needed.
SetWithInvalidate(ctx context.Context, key string, value any) error
// Delete removes a value from the cache.
// The value is removed from both local and remote storage.
Delete(ctx context.Context, key string) error
// Clear removes all values from the cache.
Clear(ctx context.Context) error
// Close closes the cache and releases all resources.
Close() error
// Stats returns cache statistics.
Stats() Stats
}
Cache defines the interface for a distributed cache with local and remote storage.
type ConsoleLogger ¶
type ConsoleLogger struct {
// contains filtered or unexported fields
}
func (*ConsoleLogger) Debug ¶
func (cl *ConsoleLogger) Debug(msg string, args ...any)
Debug logs a debug message to console.
func (*ConsoleLogger) Error ¶
func (cl *ConsoleLogger) Error(msg string, args ...any)
Error logs an error message to console.
func (*ConsoleLogger) Info ¶
func (cl *ConsoleLogger) Info(msg string, args ...any)
Info logs an info message to console.
func (*ConsoleLogger) Warn ¶
func (cl *ConsoleLogger) Warn(msg string, args ...any)
Warn logs a warning message to console.
type InvalidationEvent ¶
type InvalidationEvent = types.InvalidationEvent
InvalidationEvent is an alias for types.InvalidationEvent for backward compatibility
type JSONMarshaller ¶
type JSONMarshaller struct{}
JSONMarshaller is a marshaller that uses the standard JSON library.
type LFUCache ¶
type LFUCache struct {
// contains filtered or unexported fields
}
LFUCache is a local LFU cache implementation using lfu.
func NewLFUCache ¶
func NewLFUCache(config LocalCacheConfig) (*LFUCache, error)
NewLFUCache creates a new Ristretto-based local cache.
func (*LFUCache) Metrics ¶
func (rc *LFUCache) Metrics() LocalCacheMetrics
Metrics returns cache metrics.
type LFUCacheFactory ¶
type LFUCacheFactory struct {
// contains filtered or unexported fields
}
LFUCacheFactory creates Ristretto cache instances.
func (*LFUCacheFactory) Create ¶
func (rcf *LFUCacheFactory) Create() (LocalCache, error)
Create creates a new Ristretto cache instance.
type LRUCache ¶
type LRUCache struct {
// contains filtered or unexported fields
}
LRUCache is a local LRU cache implementation using golang-lru.
func NewLRUCache ¶
NewLRUCache creates a new LRU-based local cache.
func (*LRUCache) Metrics ¶
func (lc *LRUCache) Metrics() LocalCacheMetrics
Metrics returns cache metrics.
type LRUCacheFactory ¶
type LRUCacheFactory struct {
// contains filtered or unexported fields
}
LRUCacheFactory creates LRU cache instances.
func (*LRUCacheFactory) Create ¶
func (lcf *LRUCacheFactory) Create() (LocalCache, error)
Create creates a new LRU cache instance.
type LocalCache ¶
type LocalCache interface {
// Get retrieves a value from the local cache.
Get(key string) (any, bool)
// Set stores a value in the local cache.
Set(key string, value any, cost int64) bool
// Delete removes a value from the local cache.
Delete(key string)
// Clear removes all values from the local cache.
Clear()
// Close closes the local cache.
Close()
// Metrics returns cache metrics.
Metrics() LocalCacheMetrics
}
LocalCache defines the interface for local in-process caching.
type LocalCacheConfig ¶
type LocalCacheConfig struct {
// NumCounters is the number of counters for the cache (Ristretto only).
// Recommended: 10 * MaxItems
NumCounters int64
// MaxCost is the maximum cost of items in the cache (Ristretto only).
// Recommended: 1GB = 1 << 30
MaxCost int64
// BufferItems is the number of items to buffer before eviction (Ristretto only).
// Recommended: 64
BufferItems int64
// IgnoreInternalCost ignores the internal cost of items (Ristretto only).
IgnoreInternalCost bool
// MaxSize is the maximum number of items in the cache (LRU only).
MaxSize int
}
LocalCacheConfig configures the local cache.
func DefaultLocalCacheConfig ¶
func DefaultLocalCacheConfig() LocalCacheConfig
DefaultLocalCacheConfig returns default local cache configuration.
type LocalCacheFactory ¶
type LocalCacheFactory interface {
// Create creates a new local cache instance.
Create() (LocalCache, error)
}
LocalCacheFactory defines the interface for creating local cache implementations.
func NewLFUCacheFactory ¶
func NewLFUCacheFactory(config LocalCacheConfig) LocalCacheFactory
NewLFUCacheFactory creates a new Ristretto cache factory.
func NewLRUCacheFactory ¶
func NewLRUCacheFactory(maxSize int) LocalCacheFactory
NewLRUCacheFactory creates a new LRU cache factory.
type LocalCacheMetrics ¶
LocalCacheMetrics represents local cache metrics.
type Logger ¶
type Logger interface {
// Debug logs a debug message.
Debug(msg string, args ...any)
// Info logs an info message.
Info(msg string, args ...any)
// Warn logs a warning message.
Warn(msg string, args ...any)
// Error logs an error message.
Error(msg string, args ...any)
}
Logger defines the interface for logging in the distributed cache.
func NewConsoleLogger ¶
NewConsoleLogger creates a new console logger.
type Marshaller ¶
type Marshaller interface {
// Marshal serializes a value to bytes.
Marshal(v any) ([]byte, error)
// Unmarshal deserializes a value from bytes.
Unmarshal(data []byte, v any) error
}
Marshaller defines the interface for JSON marshalling/unmarshalling.
func NewJSONMarshaller ¶
func NewJSONMarshaller() Marshaller
NewJSONMarshaller creates a new JSON marshaller.
type NoOpLogger ¶
type NoOpLogger struct{}
NoOpLogger is a logger that does nothing.
func (*NoOpLogger) Debug ¶
func (n *NoOpLogger) Debug(msg string, args ...any)
Debug logs a debug message (no-op).
func (*NoOpLogger) Error ¶
func (n *NoOpLogger) Error(msg string, args ...any)
Error logs an error message (no-op).
func (*NoOpLogger) Info ¶
func (n *NoOpLogger) Info(msg string, args ...any)
Info logs an info message (no-op).
func (*NoOpLogger) Warn ¶
func (n *NoOpLogger) Warn(msg string, args ...any)
Warn logs a warning message (no-op).
type Options ¶
type Options struct {
// PodID is the unique identifier for this pod/instance.
// Used to avoid self-invalidation in pub/sub.
PodID string
// LocalCacheConfig configures the local Ristretto cache.
LocalCacheConfig LocalCacheConfig
// LocalCacheFactory is the factory for creating local cache instances.
// If nil, defaults to Ristretto factory.
LocalCacheFactory LocalCacheFactory
// RedisAddr is the Redis server address (e.g., "localhost:6379").
RedisAddr string
// RedisPassword is the optional Redis password.
RedisPassword string
// RedisDB is the Redis database number.
RedisDB int
// InvalidationChannel is the Redis pub/sub channel for cache invalidation.
InvalidationChannel string
// SerializationFormat specifies how values are serialized ("json" or "msgpack").
SerializationFormat string
// Marshaller is the marshaller for serialization.
// If nil, defaults to JSON marshaller.
Marshaller Marshaller
// Logger is the logger for debug logging.
// If nil, defaults to no-op logger.
Logger Logger
// DebugMode enables debug logging.
DebugMode bool
// ContextTimeout is the default timeout for cache operations.
ContextTimeout time.Duration
// EnableMetrics enables metrics collection.
EnableMetrics bool
// OnError is called when an error occurs in background operations.
OnError func(error)
// ReaderCanSetToRedis controls whether reader nodes are allowed to write data to Redis.
// When false (default), reader nodes will only update local cache but NOT write to Redis.
// When true, reader nodes can write data to Redis.
// This prevents stale data from readers overwriting fresh data in Redis.
ReaderCanSetToRedis bool
// OnSetLocalCache is a callback for custom processing of data before storing in local cache.
// This callback is invoked when an invalidation event with action "set" is received.
// The callback receives the invalidation event and returns the value to store in local cache.
// When nil (default), the default behavior is used: unmarshal the value and store in local cache.
//
// Use cases:
// - Return raw bytes directly without unmarshaling for reader nodes that serve cached bytes
// - Parse and transform event data into a pre-processed wrapper struct for zero-cost reads
// - Extract structured metadata (hash, timestamp, data) from events for custom handling
OnSetLocalCache func(event InvalidationEvent) any
}
Options configures a SyncedCache instance.
type Stats ¶
type Stats struct {
LocalHits int64
LocalMisses int64
RemoteHits int64
RemoteMisses int64
LocalSize int64
RemoteSize int64
Invalidations int64
}
Stats represents cache statistics.
type Store ¶
type Store interface {
// Get retrieves a value from the store.
Get(ctx context.Context, key string) ([]byte, error)
// Set stores a value in the store.
Set(ctx context.Context, key string, value []byte) error
// Delete removes a value from the store.
Delete(ctx context.Context, key string) error
// Clear removes all values from the store.
Clear(ctx context.Context) error
// Close closes the store connection.
Close() error
}
Store defines the interface for remote storage backends (e.g., Redis).
type SyncedCache ¶
type SyncedCache struct {
// contains filtered or unexported fields
}
SyncedCache is a two-level cache with local and remote storage.
func (*SyncedCache) Clear ¶
func (sc *SyncedCache) Clear(ctx context.Context) error
Clear removes all values from the cache.
func (*SyncedCache) Close ¶
func (sc *SyncedCache) Close() error
Close closes the cache and releases all resources.
func (*SyncedCache) Delete ¶
func (sc *SyncedCache) Delete(ctx context.Context, key string) error
Delete removes a value from the cache.
func (*SyncedCache) Set ¶
Set stores a value in the cache and propagates it to other pods. This is the default behavior - the value is sent to other pods so they can update their local caches without fetching from Redis.
func (*SyncedCache) SetWithInvalidate ¶
SetWithInvalidate stores a value in the cache and invalidates it on other pods. Use this when you want other pods to fetch the value from Redis instead of receiving it directly (useful for large values or when you want lazy loading).
type Synchronizer ¶
type Synchronizer interface {
// Subscribe starts listening for invalidation events.
Subscribe(ctx context.Context) error
// Publish publishes an invalidation event.
Publish(ctx context.Context, event types.InvalidationEvent) error
// OnInvalidate registers a callback for invalidation events.
OnInvalidate(callback func(event types.InvalidationEvent))
// Close closes the synchronizer.
Close() error
}
Synchronizer defines the interface for cache synchronization across nodes.