cache

package
v0.0.0-...-7bae66b Latest Latest
Warning

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

Go to latest
Published: May 7, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrCacheDisabled = fmt.Errorf("cache is disabled")
	ErrCacheMiss     = fmt.Errorf("cache miss")
)

Errors

Functions

This section is empty.

Types

type CacheStats

type CacheStats struct {
	Enabled   bool
	Hits      int64
	Misses    int64
	Keys      int64
	Memory    int64
	Evictions int64
}

CacheStats holds cache statistics

type CacheStrategy

type CacheStrategy string

CacheStrategy defines how caching should behave

const (
	// CacheStrategyNone disables caching
	CacheStrategyNone CacheStrategy = "none"

	// CacheStrategyReadThrough reads from cache, falls back to DB, then caches
	CacheStrategyReadThrough CacheStrategy = "read_through"

	// CacheStrategyWriteThrough writes to both cache and DB
	CacheStrategyWriteThrough CacheStrategy = "write_through"

	// CacheStrategyWriteBehind writes to cache immediately, DB asynchronously
	CacheStrategyWriteBehind CacheStrategy = "write_behind"
)

type Config

type Config struct {
	// Enabled determines if caching is active
	Enabled bool

	// Strategy defines caching behavior
	Strategy CacheStrategy

	// Redis connection settings
	RedisAddr     string
	RedisPassword string
	RedisDB       int

	// Connection pool settings
	PoolSize     int
	MinIdleConns int
	MaxRetries   int

	// Default TTL for cache entries
	DefaultTTL time.Duration

	// Eviction policy
	EvictionPolicy EvictionPolicy

	// Key prefix for all cache keys
	KeyPrefix string

	// Serialization format (json, msgpack, protobuf)
	SerializationFormat string

	// Compression enabled
	CompressionEnabled bool

	// Compression threshold (bytes)
	CompressionThreshold int
}

Config holds cache configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a configuration with sensible defaults

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the cache configuration

type ErrInvalidConfig

type ErrInvalidConfig struct {
	Field   string
	Message string
}

ErrInvalidConfig represents a configuration error

func (ErrInvalidConfig) Error

func (e ErrInvalidConfig) Error() string

type EvictionPolicy

type EvictionPolicy string

EvictionPolicy defines how cache entries are evicted

const (
	// EvictionPolicyLRU - Least Recently Used
	EvictionPolicyLRU EvictionPolicy = "lru"

	// EvictionPolicyLFU - Least Frequently Used
	EvictionPolicyLFU EvictionPolicy = "lfu"

	// EvictionPolicyTTL - Time To Live based
	EvictionPolicyTTL EvictionPolicy = "ttl"
)

type RedisCache

type RedisCache struct {
	// contains filtered or unexported fields
}

RedisCache implements caching using Redis

func NewRedisCache

func NewRedisCache(config *Config) (*RedisCache, error)

NewRedisCache creates a new Redis cache instance

func (*RedisCache) Clear

func (c *RedisCache) Clear(ctx context.Context) error

Clear removes all cache entries

func (*RedisCache) Close

func (c *RedisCache) Close() error

Close closes the Redis connection

func (*RedisCache) Delete

func (c *RedisCache) Delete(ctx context.Context, keys ...string) error

Delete removes a value from cache

func (*RedisCache) DeleteByTags

func (c *RedisCache) DeleteByTags(ctx context.Context, tags ...string) error

DeleteByTags deletes all cache entries with specific tags

func (*RedisCache) DeletePattern

func (c *RedisCache) DeletePattern(ctx context.Context, pattern string) error

DeletePattern deletes all keys matching a pattern

func (*RedisCache) Exists

func (c *RedisCache) Exists(ctx context.Context, key string) (bool, error)

Exists checks if a key exists in cache

func (*RedisCache) Expire

func (c *RedisCache) Expire(ctx context.Context, key string, ttl time.Duration) error

Expire sets a new TTL for a key

func (*RedisCache) Get

func (c *RedisCache) Get(ctx context.Context, key string, dest interface{}) error

Get retrieves a value from cache

func (*RedisCache) Set

func (c *RedisCache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

Set stores a value in cache

func (*RedisCache) Stats

func (c *RedisCache) Stats(ctx context.Context) (*CacheStats, error)

Stats returns cache statistics

func (*RedisCache) TTL

func (c *RedisCache) TTL(ctx context.Context, key string) (time.Duration, error)

TTL returns the remaining TTL for a key

type RelationCache

type RelationCache struct {
	// contains filtered or unexported fields
}

RelationCache manages caching for model relationships

func NewRelationCache

func NewRelationCache(cache *RedisCache) *RelationCache

NewRelationCache creates a new relation cache manager

func (*RelationCache) GetConfig

func (rc *RelationCache) GetConfig(relationName string) (*RelationCacheConfig, bool)

GetConfig returns the cache configuration for a relation

func (*RelationCache) GetOrLoad

func (rc *RelationCache) GetOrLoad(
	ctx context.Context,
	parentID interface{},
	relationName string,
	dest interface{},
	loader func(ctx context.Context) (interface{}, error),
) error

GetOrLoad retrieves from cache or loads from database

func (*RelationCache) GetRelation

func (rc *RelationCache) GetRelation(ctx context.Context, parentID interface{}, relationName string, dest interface{}) error

GetRelation retrieves a cached relation

func (*RelationCache) InvalidateAllRelations

func (rc *RelationCache) InvalidateAllRelations(ctx context.Context, parentID interface{}) error

InvalidateAllRelations removes all cached relations for a parent

func (*RelationCache) InvalidateByEvent

func (rc *RelationCache) InvalidateByEvent(ctx context.Context, event string, parentID interface{}) error

InvalidateByEvent removes cached relations based on an event

func (*RelationCache) InvalidateByTag

func (rc *RelationCache) InvalidateByTag(ctx context.Context, tag string) error

InvalidateByTag removes all cached relations with a specific tag

func (*RelationCache) InvalidateRelation

func (rc *RelationCache) InvalidateRelation(ctx context.Context, parentID interface{}, relationName string) error

InvalidateRelation removes a cached relation

func (*RelationCache) RegisterRelation

func (rc *RelationCache) RegisterRelation(relationName string, config *RelationCacheConfig)

RegisterRelation registers a relation with its cache configuration

func (*RelationCache) SetRelation

func (rc *RelationCache) SetRelation(ctx context.Context, parentID interface{}, relationName string, value interface{}) error

SetRelation stores a relation in cache

func (*RelationCache) Stats

func (rc *RelationCache) Stats(ctx context.Context) (map[string]*RelationStats, error)

Stats returns cache statistics for all relations

func (*RelationCache) UpdateConfig

func (rc *RelationCache) UpdateConfig(relationName string, config *RelationCacheConfig)

UpdateConfig updates the cache configuration for a relation

func (*RelationCache) WarmupRelation

func (rc *RelationCache) WarmupRelation(ctx context.Context, relationName string, loader func(ctx context.Context) (map[interface{}]interface{}, error)) error

WarmupRelation pre-loads a relation into cache

type RelationCacheConfig

type RelationCacheConfig struct {
	// Enabled determines if this relation should be cached
	Enabled bool

	// TTL for this specific relation (overrides default)
	TTL time.Duration

	// CacheKey custom key generator function
	CacheKeyFunc func(parentID interface{}, relationName string) string

	// ShouldCache determines if a specific result should be cached
	ShouldCacheFunc func(result interface{}) bool

	// OnCacheHit callback when cache hit occurs
	OnCacheHit func(key string)

	// OnCacheMiss callback when cache miss occurs
	OnCacheMiss func(key string)

	// MaxSize maximum number of items to cache for this relation
	MaxSize int

	// WarmupEnabled determines if cache should be warmed up on startup
	WarmupEnabled bool

	// WarmupQuery query to use for cache warmup
	WarmupQuery string

	// InvalidateOn list of events that should invalidate this cache
	InvalidateOn []string

	// Tags for cache organization and bulk invalidation
	Tags []string
}

RelationCacheConfig holds configuration for relation caching

func DefaultRelationCacheConfig

func DefaultRelationCacheConfig() *RelationCacheConfig

DefaultRelationCacheConfig returns default relation cache config

type RelationStats

type RelationStats struct {
	RelationName string
	Hits         int64
	Misses       int64
	Keys         int64
	AvgTTL       time.Duration
}

RelationStats holds statistics for a cached relation

Jump to

Keyboard shortcuts

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