cache

package
v0.8.6 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotFound is returned when a key is not found in the cache.
	ErrNotFound = errors.New("cache: key not found")

	// ErrNotConnected is returned when attempting operations on a disconnected cache.
	ErrNotConnected = errors.New("cache: not connected")

	// ErrInvalidTTL is returned when an invalid TTL is provided.
	ErrInvalidTTL = errors.New("cache: invalid TTL")

	// ErrKeyTooLarge is returned when a key exceeds the maximum allowed size.
	ErrKeyTooLarge = errors.New("cache: key too large")

	// ErrValueTooLarge is returned when a value exceeds the maximum allowed size.
	ErrValueTooLarge = errors.New("cache: value too large")

	// ErrUnsupportedOperation is returned when an operation is not supported by the backend.
	ErrUnsupportedOperation = errors.New("cache: operation not supported")
)

Functions

func NewExtension

func NewExtension(opts ...ConfigOption) forge.Extension

NewExtension creates a new cache extension with functional options. Config is loaded from ConfigManager by default, with options providing overrides.

Example:

// Load from ConfigManager (tries "extensions.cache", then "cache")
cache.NewExtension()

// Override specific fields
cache.NewExtension(
    cache.WithDriver("redis"),
    cache.WithURL("redis://localhost:6379"),
)

// Require config from ConfigManager
cache.NewExtension(cache.WithRequireConfig(true))

func NewExtensionWithConfig

func NewExtensionWithConfig(config Config) forge.Extension

NewExtensionWithConfig creates a new cache extension with a complete config. This is for backward compatibility or when config is fully known at initialization.

Types

type Cache

type Cache interface {
	// Connect establishes a connection to the cache backend
	Connect(ctx context.Context) error

	// Disconnect closes the connection to the cache backend
	Disconnect(ctx context.Context) error

	// Ping checks if the cache backend is accessible
	Ping(ctx context.Context) error

	// Get retrieves a value from the cache by key
	// Returns ErrNotFound if the key doesn't exist
	Get(ctx context.Context, key string) ([]byte, error)

	// Set stores a value in the cache with the given key and TTL
	// If ttl is 0, uses the default TTL from config
	Set(ctx context.Context, key string, value []byte, ttl time.Duration) error

	// Delete removes a key from the cache
	Delete(ctx context.Context, key string) error

	// Exists checks if a key exists in the cache
	Exists(ctx context.Context, key string) (bool, error)

	// Clear removes all keys from the cache
	Clear(ctx context.Context) error

	// Keys returns all keys matching the pattern
	// Pattern uses glob-style matching (* for wildcard)
	Keys(ctx context.Context, pattern string) ([]string, error)

	// TTL returns the remaining time-to-live for a key
	// Returns 0 if the key has no expiration
	TTL(ctx context.Context, key string) (time.Duration, error)

	// Expire sets a new TTL for a key
	Expire(ctx context.Context, key string, ttl time.Duration) error
}

Cache is the main interface for cache operations. All cache backends (in-memory, Redis, Memcached) implement this interface.

type Config

type Config struct {
	// Driver specifies the cache backend: "inmemory", "redis", "memcached"
	Driver string

	// URL is the connection string for the cache backend
	// Examples:
	//   - Redis: "redis://localhost:6379/0"
	//   - Memcached: "memcached://localhost:11211"
	//   - In-Memory: "" (not used)
	URL string

	// DefaultTTL is the default time-to-live for cache entries
	// Used when Set() is called with ttl=0
	DefaultTTL time.Duration

	// MaxSize is the maximum number of items in the cache (in-memory only)
	// 0 means unlimited
	MaxSize int

	// CleanupInterval is how often to clean up expired items (in-memory only)
	CleanupInterval time.Duration

	// MaxKeySize is the maximum allowed key size in bytes
	MaxKeySize int

	// MaxValueSize is the maximum allowed value size in bytes
	MaxValueSize int

	// Prefix is prepended to all keys
	// Useful for namespacing in shared cache instances
	Prefix string

	// ConnectionPoolSize is the number of connections to maintain (Redis/Memcached)
	ConnectionPoolSize int

	// ConnectionTimeout is the timeout for establishing a connection
	ConnectionTimeout time.Duration

	// ReadTimeout is the timeout for read operations
	ReadTimeout time.Duration

	// WriteTimeout is the timeout for write operations
	WriteTimeout time.Duration

	// RequireConfig determines if config must exist in ConfigManager
	// If true, extension fails to start without config
	// If false, uses defaults when config is missing
	RequireConfig bool
}

Config configures the cache extension.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a default configuration for in-memory cache.

func (Config) Validate

func (c Config) Validate() error

Validate validates the configuration.

type ConfigOption

type ConfigOption func(*Config)

ConfigOption is a functional option for configuring the cache extension.

func WithConfig

func WithConfig(config Config) ConfigOption

WithConfig applies a complete config.

func WithConnectionPoolSize

func WithConnectionPoolSize(size int) ConfigOption

WithConnectionPoolSize sets the connection pool size.

func WithDefaultTTL

func WithDefaultTTL(ttl time.Duration) ConfigOption

WithDefaultTTL sets the default TTL.

func WithDriver

func WithDriver(driver string) ConfigOption

WithDriver sets the cache driver.

func WithMaxSize

func WithMaxSize(size int) ConfigOption

WithMaxSize sets the maximum cache size (in-memory only).

func WithPrefix

func WithPrefix(prefix string) ConfigOption

WithPrefix sets the key prefix.

func WithRequireConfig

func WithRequireConfig(require bool) ConfigOption

WithRequireConfig sets whether config is required from ConfigManager.

func WithURL

func WithURL(url string) ConfigOption

WithURL sets the cache URL.

type CounterCache

type CounterCache interface {
	Incr(ctx context.Context, key string) (int64, error)
	IncrBy(ctx context.Context, key string, value int64) (int64, error)
	Decr(ctx context.Context, key string) (int64, error)
	DecrBy(ctx context.Context, key string, value int64) (int64, error)
}

Counter operations for atomic increments/decrements.

type Extension

type Extension struct {
	*forge.BaseExtension
	// contains filtered or unexported fields
}

Extension implements forge.Extension for cache functionality.

func (*Extension) Cache

func (e *Extension) Cache() Cache

Cache returns the cache instance (for advanced usage).

func (*Extension) Health

func (e *Extension) Health(ctx context.Context) error

Health checks if the cache is healthy.

func (*Extension) Register

func (e *Extension) Register(app forge.App) error

Register registers the cache extension with the app.

func (*Extension) Start

func (e *Extension) Start(ctx context.Context) error

Start starts the cache extension.

func (*Extension) Stop

func (e *Extension) Stop(ctx context.Context) error

Stop stops the cache extension.

type InMemoryCache

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

InMemoryCache implements Cache interface using an in-memory store.

func NewInMemoryCache

func NewInMemoryCache(config Config, logger forge.Logger, metrics forge.Metrics) *InMemoryCache

NewInMemoryCache creates a new in-memory cache.

func (*InMemoryCache) Clear

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

Clear removes all keys from the cache.

func (*InMemoryCache) Connect

func (c *InMemoryCache) Connect(ctx context.Context) error

Connect initializes the cache and starts the cleanup goroutine.

func (*InMemoryCache) Delete

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

Delete removes a key from the cache.

func (*InMemoryCache) Disconnect

func (c *InMemoryCache) Disconnect(ctx context.Context) error

Disconnect stops the cache and cleans up resources.

func (*InMemoryCache) Exists

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

Exists checks if a key exists in the cache.

func (*InMemoryCache) Expire

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

Expire sets a new TTL for a key.

func (*InMemoryCache) Get

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

Get retrieves a value from the cache.

func (*InMemoryCache) GetJSON

func (c *InMemoryCache) GetJSON(ctx context.Context, key string, target any) error

func (*InMemoryCache) GetString

func (c *InMemoryCache) GetString(ctx context.Context, key string) (string, error)

func (*InMemoryCache) Keys

func (c *InMemoryCache) Keys(ctx context.Context, pattern string) ([]string, error)

Keys returns all keys matching the pattern.

func (*InMemoryCache) Ping

func (c *InMemoryCache) Ping(ctx context.Context) error

Ping checks if the cache is connected.

func (*InMemoryCache) Set

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

Set stores a value in the cache.

func (*InMemoryCache) SetJSON

func (c *InMemoryCache) SetJSON(ctx context.Context, key string, value any, ttl time.Duration) error

func (*InMemoryCache) SetString

func (c *InMemoryCache) SetString(ctx context.Context, key string, value string, ttl time.Duration) error

func (*InMemoryCache) TTL

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

TTL returns the remaining time-to-live for a key.

type JSONCache

type JSONCache interface {
	GetJSON(ctx context.Context, key string, target any) error
	SetJSON(ctx context.Context, key string, value any, ttl time.Duration) error
}

GetJSON retrieves and unmarshals a JSON value from the cache.

type MultiCache

type MultiCache interface {
	MGet(ctx context.Context, keys ...string) ([][]byte, error)
	MSet(ctx context.Context, kvs map[string][]byte, ttl time.Duration) error
	MDelete(ctx context.Context, keys ...string) error
}

Multi-key operations.

type StringCache

type StringCache interface {
	GetString(ctx context.Context, key string) (string, error)
	SetString(ctx context.Context, key string, value string, ttl time.Duration) error
}

GetString retrieves a string value from the cache.

Jump to

Keyboard shortcuts

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