Documentation
¶
Overview ¶
Package cache provides caching abstractions and utilities.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrKeyNotFound is returned in Cache.Get and Cache.Delete when the // provided key could not be found in cache. ErrKeyNotFound error = errors.New("cache: key not found in cache") // ErrInvalidCachedValue is returned when the cached value cannot be decoded // into the expected type. ErrInvalidCachedValue error = errors.New("cache: invalid cached value") // ErrInvalidTargetType is returned when the target type is not compatible with the decoder ErrInvalidTargetType error = errors.New("cache: target must be a byte slice for pure gzip decoding") // ErrInvalidPayloadType is returned when the payload type is not compatible with the encoder ErrInvalidPayloadType error = errors.New("cache: payload must be a byte slice for pure gzip encoding") // ErrClosed is returned when attempting to use a closed cache ErrClosed error = errors.New("cache: closed") )
var ( // DefaultExpiration is the default duration for items stored in // the cache to expire. DefaultExpiration time.Duration = 0 )
Functions ¶
func SetInstance ¶
func SetInstance(cache Cache)
SetInstance sets the global Cache instance to the specified Cache. It is thread-safe and does nothing if the provided cache is nil. This can be called before or after Instance() to override the default.
Parameters:
cache - The new Cache instance to set as global
Types ¶
type Cache ¶
type Cache interface {
// Set adds an item to the cache.
// The item is associated with the given key and can be retrieved using the same key.
Set(ctx context.Context, item Item) error
// GetRaw retrieves the raw bytes of an item from the cache.
GetRaw(ctx context.Context, key string) ([]byte, error)
// Get retrieves an item from the cache, decoding it into the provided target.
Get(ctx context.Context, key string, target any) error
// Delete removes an item from the cache.
// The item is identified by the given key and can be removed using the same key.
Delete(ctx context.Context, key string) error
// Close closes the cache.
Close(ctx context.Context) error
}
Cache represents a cache interface, which is used to store and retrieve items.
type Decoder ¶
Decoder is a function type that decodes a byte payload into a target value. It is used to transform cached data from its stored format back into its original type.
func NewDecoderGzip ¶
func NewDecoderGzip() Decoder
NewDecoderGzip creates a new decoder that decompresses GZIP-compressed data. This decoder is designed to work with raw byte slices and expects the target to be a pointer to a byte slice (*[]byte).
func NewDecoderGzipJSON ¶
func NewDecoderGzipJSON() Decoder
NewDecoderGzipJSON creates a new decoder that combines GZIP decompression with JSON unmarshaling. This decoder is designed to work with data that was encoded using NewEncoderGzipJSON. The process involves: 1. Decompressing the GZIP data 2. Unmarshaling the decompressed JSON into the target value
func NewDecoderJSON ¶
func NewDecoderJSON() Decoder
NewDecoderJSON creates a new JSON decoder that unmarshals JSON data into the target value. This decoder is suitable for data that was stored as JSON in the cache.
func NewSmartDecoder ¶
func NewSmartDecoder() Decoder
NewSmartDecoder creates a decoder that intelligently handles both JSON and GZIP+JSON encoded data. It detects the format based on GZIP magic bytes: - If the data starts with 0x1f 0x8b, it decompresses with GZIP and then decodes the JSON. - Otherwise, it assumes plain JSON and decodes directly.
type Encoder ¶
Encoder is a function type that encodes a value into a byte payload. It is used to transform data into a format suitable for storage in the cache.
func NewEncoderGzip ¶
func NewEncoderGzip() Encoder
NewEncoderGzip creates a new encoder that compresses data using GZIP. This encoder expects the input payload to be a byte slice and compresses it directly. It's useful for compressing raw binary data without JSON transformation.
func NewEncoderGzipJSON ¶
func NewEncoderGzipJSON() Encoder
NewEncoderGzipJSON creates a new encoder that combines JSON marshaling with GZIP compression. This encoder is useful for storing large JSON payloads in a compressed format to save space. The process involves: 1. Converting the payload to JSON 2. Compressing the JSON data using GZIP
func NewEncoderJSON ¶
func NewEncoderJSON() Encoder
NewEncoderJSON creates a new JSON encoder that marshals data into JSON format. This encoder is suitable for storing data as JSON in the cache.
func NewSmartEncoder ¶
NewSmartEncoder creates an encoder that intelligently chooses between JSON and GZIP+JSON encoding based on the size of the payload. This helps optimize storage and performance by: - Using simple JSON encoding for small payloads (below threshold) - Using GZIP+JSON encoding for large payloads (at or above threshold)
type Handler ¶
Handler defines a function type that resolves a value of type T. It takes a context and returns the resolved value and an error.
Parameters:
ctx - Context for controlling cancellation and timeouts
Returns:
T - The resolved value error - Any error that occurred during resolution
type Option ¶
type Option func(*options)
Option is a function type that configures a cache instance's options. It modifies the options struct to customize the cache behavior.
func WithConcurrencySafety ¶
func WithConcurrencySafety() Option
WithConcurrencySafety returns an Option that enables mutex-based concurrency protection. When set, the cache will use a mutex to ensure thread-safe operations.
Returns:
Option - A function that enables the useMutex flag in the options struct
func WithDecoder ¶
WithDecoder returns an Option that sets the decoder for the cache. The decoder is responsible for deserializing values retrieved from the cache.
Parameters:
decoder - The Decoder implementation to use for deserialization
Returns:
Option - A function that sets the decoder in the options struct
func WithEncoder ¶
WithEncoder returns an Option that sets the encoder for the cache. The encoder is responsible for serializing values before storage.
Parameters:
encoder - The Encoder implementation to use for serialization
Returns:
Option - A function that sets the encoder in the options struct
type Provider ¶
type Provider interface {
// Set adds an item to the cache with the given time-to-live (TTL).
// The item is identified by the given key and can be retrieved using the same key.
Set(ctx context.Context, item Item) error
// Get retrieves an item from the cache.
// The item is identified by the given key and can be retrieved using the same key.
// It returns the value of the item as a byte slice.
Get(ctx context.Context, key string) ([]byte, error)
// Delete removes an item from the cache.
// The item is identified by the given key and can be removed using the same key.
Delete(ctx context.Context, key string) error
// Close closes the cache.
Close(ctx context.Context) error
}
Provider represents a cache provider interface, which is used to interact with a cache.
func NewInMemoryCache ¶
func NewInMemoryCache() Provider
NewInMemoryCache creates and returns a new in-memory cache provider. The in-memory cache provider stores items in memory and is useful for local caching. Returns a new in-memory cache provider.
type Resolver ¶
type Resolver[T any] struct { // contains filtered or unexported fields }
Resolver provides a mechanism to resolve and cache values of type T. It handles both retrieval from cache and fresh resolution of values.
Fields:
cache - The underlying cache implementation key - The cache key for storing/retrieving values expiresIn - Duration after which cached values expire returnErrOnSet - Whether to return errors when cache setting fails
func NewResolver ¶
func NewResolver[T any](key string, opts ...ResolverOption[T]) *Resolver[T]
NewResolver creates a new Resolver instance with the specified key and options. Default settings include a 5-minute expiration and the default cache instance.
Parameters:
key - The cache key to use for storing/retrieving values opts - Variable number of configuration options
Returns:
*Resolver[T] - Pointer to the configured Resolver instance
func (*Resolver[T]) Get ¶
Get retrieves a value strictly from cache without fallback resolution. Unlike GetOrFetch, it does not attempt to resolve the value if not found.
Parameters:
ctx - Context for controlling cancellation and timeouts
Returns:
T - The retrieved value error - Any error from cache retrieval
func (*Resolver[T]) GetOrFetch ¶
GetOrFetch retrieves a value from cache or resolves it using the provided fallback. If the value is in cache, it returns immediately. Otherwise, it uses the fallback to fetch the value, caches it for future use, and returns it.
Parameters:
ctx - Context for controlling cancellation and timeouts fallback - Function to resolve the value if not in cache
Returns:
T - The retrieved or resolved value error - Any error that occurred during retrieval/resolution
type ResolverOption ¶
ResolverOption defines a function type for configuring Resolver instances. It takes a pointer to a Resolver and modifies its configuration.
func WithCache ¶
func WithCache[T any](c Cache) ResolverOption[T]
WithCache creates an option to set a custom cache implementation.
Parameters:
c - The custom Cache implementation to use
Returns:
ResolverOption[T] - Configuration function for Resolver
func WithExpiration ¶
func WithExpiration[T any](d time.Duration) ResolverOption[T]
WithExpiration creates an option to set the cache expiration duration.
Parameters:
d - The duration after which cached values expire
Returns:
ResolverOption[T] - Configuration function for Resolver
func WithReturnErrorOnSet ¶
func WithReturnErrorOnSet() ResolverOption[any]
WithReturnErrorOnSet creates an option to configure whether to return errors when setting cache values fails.
Returns:
ResolverOption[any] - Configuration function for Resolver