cache

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: May 29, 2025 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package cache provides in-memory caching implementations.

Package cache provides Redis-based caching implementations.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound indicates a key was not found in the cache.
	// DEPRECATED: Implementations of userprefs.Cache should return userprefs.ErrNotFound (from the parent package) instead
	// to ensure consistency with the userprefs.Cache interface contract.
	ErrNotFound = errors.New("cache: key not found")

	// ErrKeyExpired indicates a key was found in the cache but has passed its expiration time.
	// Implementations might choose to return this, or treat expired keys as not found (thus returning userprefs.ErrNotFound).
	ErrKeyExpired = errors.New("cache: key expired")

	// ErrCacheFailure indicates a generic operational failure within the cache backend
	// (e.g., connection error for Redis, unexpected error for in-memory cache).
	ErrCacheFailure = errors.New("cache: operation failure")
)

Define cache-specific errors. Note that for broader compatibility within the userprefs library, implementations are encouraged to use errors defined in the parent `userprefs` package where appropriate (e.g., userprefs.ErrNotFound).

Functions

This section is empty.

Types

type Cache

type Cache interface {
	// Get retrieves an item from the cache by its key.
	// It returns the cached item as a byte slice ([]byte) and nil on success.
	// If the key is not found or has expired, implementations should return userprefs.ErrNotFound (from the parent package)
	// to comply with the userprefs.Cache interface contract.
	// Other errors, like cache.ErrCacheFailure, may be returned for operational issues.
	Get(ctx context.Context, key string) ([]byte, error)

	// Set adds an item to the cache with a specific key and time-to-live (TTL).
	// The 'value' parameter is the byte slice item to cache.
	// The 'ttl' parameter specifies the duration for which the item should be cached.
	// A TTL of 0 might be interpreted by implementations as "cache forever" or "use default TTL",
	// refer to specific implementation documentation for details.
	// Returns an error (e.g., cache.ErrCacheFailure) if the operation fails.
	Set(ctx context.Context, key string, value []byte, ttl time.Duration) error

	// Delete removes an item from the cache by its key.
	// It should be idempotent, returning nil error even if the key does not exist in the cache.
	// Returns an error (e.g., cache.ErrCacheFailure) if the deletion attempt fails due to an operational issue.
	Delete(ctx context.Context, key string) error

	// Close releases any resources (like network connections or background goroutines)
	// held by the cache implementation. It should be called when the cache is no longer needed.
	Close() error
}

Cache defines the essential methods for a caching backend. Implementations of this interface, such as MemoryCache or RedisCache found within this package, are designed to fulfill the contract of the userprefs.Cache interface (defined in the parent package) for use by the userprefs.Manager. Implementations must be thread-safe for concurrent access.

type MemoryCache

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

MemoryCache implements the userprefs.Cache interface using an in-memory map. It provides a thread-safe caching mechanism with support for item expiration and automatic garbage collection of expired items. All operations are protected by an internal sync.RWMutex.

func NewMemoryCache

func NewMemoryCache() *MemoryCache

NewMemoryCache initializes and returns a new MemoryCache instance. It also starts a background goroutine that periodically scans for and removes expired items from the cache. This goroutine is stopped when the Close method is called.

func (*MemoryCache) Close

func (c *MemoryCache) Close() error

Close stops the background garbage collection goroutine and clears all items from the memory cache. This method should be called when the MemoryCache is no longer needed to free resources. It effectively resets the cache to an empty state. This method currently always returns nil error.

func (*MemoryCache) Delete

func (c *MemoryCache) Delete(_ context.Context, key string) error

Delete removes an item from the memory cache by its key. The 'ctx' parameter is present for interface compliance but is not used in this implementation. This operation is idempotent: if the key does not exist, it does nothing and returns nil error. This method currently always returns nil error.

func (*MemoryCache) Get

func (c *MemoryCache) Get(_ context.Context, key string) ([]byte, error)

Get retrieves an item from the memory cache by its key. The 'ctx' parameter is present for interface compliance but is not used in this implementation. It returns the cached item as a byte slice ([]byte) and nil error if the key is found and not expired. If the key does not exist or if the item has expired, it returns nil for the byte slice and userprefs.ErrNotFound from the parent package.

func (*MemoryCache) Set

func (c *MemoryCache) Set(_ context.Context, key string, value []byte, ttl time.Duration) error

Set adds an item (as a byte slice) to the memory cache with the given key, applying an optional TTL. The 'ctx' parameter is present for interface compliance but is not used in this implementation. The 'value' parameter must be a byte slice. If 'ttl' (time-to-live) is greater than zero, the item will be marked for expiration after that duration. If 'ttl' is zero or negative, the item will not expire (it will persist until explicitly deleted or the cache is closed). This method currently always returns nil error.

type RedisCache

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

RedisCache implements the userprefs.Cache interface using a Redis backend. It leverages the github.com/redis/go-redis/v9 library for Redis communication.

func NewRedisCache

func NewRedisCache(opts ...RedisOption) (*RedisCache, error)

NewRedisCache creates a new RedisCache instance. It takes a list of RedisOption functions to configure the Redis client. Required options: WithRedisAddress. Optional options: WithRedisPassword, WithRedisDB, WithRedisPoolSize, etc.

The function initializes a Redis client and pings it to ensure connectivity. The DialTimeout setting in RedisConfig (or its default) governs the timeout for the initial connection attempt during client creation. A separate context with a timeout (derived from DialTimeout or a default of 5s) is used for the initial Ping. Returns an error if client creation or the initial Ping fails.

func (*RedisCache) Close

func (c *RedisCache) Close() error

Close closes the underlying Redis client connection pool. It should be called when the RedisCache is no longer needed to release resources.

func (*RedisCache) Delete

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

Delete removes an item from Redis by its key. The underlying Redis DEL command is idempotent. This method returns an error only if the DEL command itself fails. If the key does not exist, Redis DEL command still returns success (0 keys deleted), so no error is returned by this method in that case.

func (*RedisCache) Get

func (c *RedisCache) Get(ctx context.Context, key string) ([]byte, error)

Get retrieves an item from Redis by its key. If the key is not found in Redis (redis.Nil error), it returns (nil, userprefs.ErrNotFound). For other Redis errors, it returns (nil, error_details). On success, it returns the item as a byte slice ([]byte) and nil error. The caller is responsible for unmarshalling this data.

func (*RedisCache) Set

func (c *RedisCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error

Set stores an item (as a byte slice) in Redis. The 'value' parameter must be a byte slice, typically pre-marshalled by the caller (e.g., the Manager). If 'ttl' (time-to-live) is greater than zero, the item will expire in Redis after that duration. If 'ttl' is zero or negative, the item will be stored without an expiration. Returns an error if the Redis SET operation fails.

type RedisClient

type RedisClient interface {
	Get(ctx context.Context, key string) *redis.StringCmd
	Set(ctx context.Context, key string, value []byte, expiration time.Duration) *redis.StatusCmd
	Del(ctx context.Context, keys ...string) *redis.IntCmd
	Close() error
	Ping(ctx context.Context) *redis.StatusCmd // Add Ping for connection check
}

RedisClient defines an interface abstracting the methods used from `redis.Client`. This abstraction allows for easier mocking and testing of RedisCache.

type RedisConfig added in v1.0.0

type RedisConfig struct {
	Addr     string
	Password string
	DB       int

	// Connection Pool Options
	PoolSize     int
	MinIdleConns int
	PoolTimeout  time.Duration
	DialTimeout  time.Duration
	ReadTimeout  time.Duration
	WriteTimeout time.Duration

	// Retry Options
	MaxRetries      int
	MinRetryBackoff time.Duration
	MaxRetryBackoff time.Duration
}

RedisConfig holds configuration options for the Redis cache backend. Fields correspond to options available in github.com/redis/go-redis/v9. If a field is not set via a WithRedis... option, the go-redis library's default will be used.

type RedisOption added in v1.0.0

type RedisOption func(*RedisConfig)

RedisOption defines a function signature for configuring RedisCache settings. These options are applied to a RedisConfig struct during the initialization of a RedisCache instance.

func WithRedisAddress added in v1.0.0

func WithRedisAddress(addr string) RedisOption

WithRedisAddress sets the Redis server address (e.g., "localhost:6379"). If not specified, NewRedisCache defaults to "localhost:6379".

func WithRedisDB added in v1.0.0

func WithRedisDB(db int) RedisOption

WithRedisDB sets the Redis database number to select after connecting. Default is DB 0.

func WithRedisDialTimeout added in v1.0.0

func WithRedisDialTimeout(timeout time.Duration) RedisOption

WithRedisDialTimeout sets the timeout for establishing new connections to the Redis server. Default is 5 seconds.

func WithRedisMaxRetries added in v1.0.0

func WithRedisMaxRetries(retries int) RedisOption

WithRedisMaxRetries sets the maximum number of retries for a command before giving up. Default is 0 (no retries). Set to -1 for infinite retries.

func WithRedisMaxRetryBackoff added in v1.0.0

func WithRedisMaxRetryBackoff(backoff time.Duration) RedisOption

WithRedisMaxRetryBackoff sets the maximum backoff duration between command retries. Default is 512 milliseconds. Use -1 to disable backoff.

func WithRedisMinIdleConns added in v1.0.0

func WithRedisMinIdleConns(conns int) RedisOption

WithRedisMinIdleConns sets the minimum number of idle connections maintained in the pool. Default is 0 (no minimum).

func WithRedisMinRetryBackoff added in v1.0.0

func WithRedisMinRetryBackoff(backoff time.Duration) RedisOption

WithRedisMinRetryBackoff sets the minimum backoff duration between command retries. Default is 8 milliseconds. Use -1 to disable backoff.

func WithRedisPassword added in v1.0.0

func WithRedisPassword(password string) RedisOption

WithRedisPassword sets the password for Redis server authentication. Default is no password.

func WithRedisPoolSize added in v1.0.0

func WithRedisPoolSize(size int) RedisOption

WithRedisPoolSize sets the maximum number of socket connections in the connection pool. Default is typically 10 connections per CPU core.

func WithRedisPoolTimeout added in v1.0.0

func WithRedisPoolTimeout(timeout time.Duration) RedisOption

WithRedisPoolTimeout sets the amount of time the client waits for a connection if all connections in the pool are busy before returning an error. Default is ReadTimeout + 1 second.

func WithRedisReadTimeout added in v1.0.0

func WithRedisReadTimeout(timeout time.Duration) RedisOption

WithRedisReadTimeout sets the timeout for read operations on a Redis connection. Default is 3 seconds. Set to -1 for no timeout.

func WithRedisWriteTimeout added in v1.0.0

func WithRedisWriteTimeout(timeout time.Duration) RedisOption

WithRedisWriteTimeout sets the timeout for write operations on a Redis connection. Default is ReadTimeout. Set to -1 for no timeout.

Jump to

Keyboard shortcuts

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