cache

package
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ActionSet        = types.Set
	ActionInvalidate = types.Invalidate
	ActionDelete     = types.Delete
	ActionClear      = types.Clear
)

Action constants for cache operations

Variables

View Source
var ErrCacheClosed = NewError("cache is closed")

ErrCacheClosed is returned when operations are performed on a closed cache.

View Source
var ErrInvalidConfig = NewError("invalid cache configuration")

ErrInvalidConfig is returned when options are invalid.

Functions

func NewError

func NewError(msg string) error

NewError creates a new error with the given message.

Types

type Action

type Action = types.Action

Action is an alias for types.Action for backward compatibility

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.

func (*JSONMarshaller) Marshal

func (jm *JSONMarshaller) Marshal(v any) ([]byte, error)

Marshal serializes a value to JSON.

func (*JSONMarshaller) Unmarshal

func (jm *JSONMarshaller) Unmarshal(data []byte, v any) error

Unmarshal deserializes a value from JSON.

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) Clear

func (rc *LFUCache) Clear()

Clear removes all values from the local cache.

func (*LFUCache) Close

func (rc *LFUCache) Close()

Close closes the local cache.

func (*LFUCache) Delete

func (rc *LFUCache) Delete(key string)

Delete removes a value from the local cache.

func (*LFUCache) Get

func (rc *LFUCache) Get(key string) (any, bool)

Get retrieves a value from the local cache.

func (*LFUCache) Metrics

func (rc *LFUCache) Metrics() LocalCacheMetrics

Metrics returns cache metrics.

func (*LFUCache) Set

func (rc *LFUCache) Set(key string, value any, cost int64) bool

Set stores a value in the local cache.

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

func NewLRUCache(maxSize int) (*LRUCache, error)

NewLRUCache creates a new LRU-based local cache.

func (*LRUCache) Clear

func (lc *LRUCache) Clear()

Clear removes all values from the local cache.

func (*LRUCache) Close

func (lc *LRUCache) Close()

Close closes the local cache.

func (*LRUCache) Delete

func (lc *LRUCache) Delete(key string)

Delete removes a value from the local cache.

func (*LRUCache) Get

func (lc *LRUCache) Get(key string) (any, bool)

Get retrieves a value from the local cache.

func (*LRUCache) Metrics

func (lc *LRUCache) Metrics() LocalCacheMetrics

Metrics returns cache metrics.

func (*LRUCache) Set

func (lc *LRUCache) Set(key string, value any, _ int64) bool

Set stores a value in the local cache.

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

type LocalCacheMetrics struct {
	Hits      int64
	Misses    int64
	Evictions int64
	Size      int64
}

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

func NewConsoleLogger(prefix string) Logger

NewConsoleLogger creates a new console logger.

func NewNoOpLogger

func NewNoOpLogger() Logger

NewNoOpLogger creates a new no-op 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.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns default cache options.

func (*Options) Validate

func (o *Options) Validate() error

Validate validates the options.

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 New

func New(opts Options) (*SyncedCache, error)

New creates a new SyncedCache instance.

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) Get

func (sc *SyncedCache) Get(ctx context.Context, key string) (any, bool)

Get retrieves a value from the cache.

func (*SyncedCache) Set

func (sc *SyncedCache) Set(ctx context.Context, key string, value any) error

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

func (sc *SyncedCache) SetWithInvalidate(ctx context.Context, key string, value any) error

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).

func (*SyncedCache) Stats

func (sc *SyncedCache) Stats() Stats

Stats returns cache statistics.

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.

Jump to

Keyboard shortcuts

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