Documentation
¶
Overview ¶
Package cachestore is the caching (key->value) service abstraction layer
Index ¶
- Constants
- Variables
- func GetModelValue[T any](ctx context.Context, c CacheService, key string) (T, bool, error)
- func GetOrLoad[T any](ctx context.Context, c ClientInterface, key string, ttl time.Duration, ...) (T, error)
- func GetOrLoadWithOptions[T any](ctx context.Context, c ClientInterface, key string, ttl time.Duration, ...) (T, error)
- func RandomHex(n int) (string, error)
- func SetModelValue[T any](ctx context.Context, c CacheService, key string, value T, ttl time.Duration, ...) error
- type CacheService
- type Client
- func (c *Client) Close(ctx context.Context)
- func (c *Client) Debug(on bool)
- func (c *Client) Delete(ctx context.Context, key string) error
- func (c *Client) EmptyCache(ctx context.Context) error
- func (c *Client) Engine() Engine
- func (c *Client) FreeCache() *freecache.Cache
- func (c *Client) Get(ctx context.Context, key string) (string, error)
- func (c *Client) GetModel(ctx context.Context, key string, model interface{}) error
- func (c *Client) IsDebug() bool
- func (c *Client) IsNewRelicEnabled() bool
- func (c *Client) Redis() *cache.Client
- func (c *Client) RedisConfig() *RedisConfig
- func (c *Client) ReleaseLock(ctx context.Context, lockKey, secret string) (bool, error)
- func (c *Client) Set(ctx context.Context, key string, value interface{}, dependencies ...string) error
- func (c *Client) SetModel(ctx context.Context, key string, model interface{}, ttl time.Duration, ...) error
- func (c *Client) SetTTL(ctx context.Context, key string, value interface{}, ttl time.Duration, ...) error
- func (c *Client) WaitWriteLock(ctx context.Context, lockKey string, ttl, ttw int64) (string, error)
- func (c *Client) WriteLock(ctx context.Context, lockKey string, ttl int64) (string, error)
- func (c *Client) WriteLockWithSecret(ctx context.Context, lockKey, secret string, ttl int64) (string, error)
- type ClientInterface
- type ClientOps
- func WithDebugging() ClientOps
- func WithFreeCache() ClientOps
- func WithFreeCacheConnection(client *freecache.Cache) ClientOps
- func WithLogger(customLogger zLogger.GormLoggerInterface) ClientOps
- func WithNewRelic() ClientOps
- func WithRedis(redisConfig *RedisConfig) ClientOps
- func WithRedisConnection(redisClient *cache.Client) ClientOps
- type Engine
- type LoadOptions
- type LockService
- type RedisConfig
Examples ¶
Constants ¶
const ( // DefaultRedisMaxIdleTimeout is the default max timeout on an idle connection DefaultRedisMaxIdleTimeout = 240 * time.Second // DefaultRedisPort is the default Redis port DefaultRedisPort = "6379" // RedisPrefix is the prefix for URL based connections RedisPrefix = "redis://" // RedissPrefix is the prefix for TLS URL based connections RedissPrefix = "rediss://" )
const ( // DefaultCacheSize in bytes, where 1024 * 1024 represents a single Megabyte, and 100 * 1024*1024 represents 100 Megabytes. DefaultCacheSize = 100 * 1024 * 1024 // DefaultGCPercent is the percentage when full it will run GC DefaultGCPercent = 20 )
Variables ¶
var ErrAppNameRequired = errors.New("app name is required")
ErrAppNameRequired is when the app name is required
var ErrInvalidRedisCACert = errors.New("invalid redis tls ca certificate")
ErrInvalidRedisCACert is when the redis TLS CA certificate cannot be loaded
var ErrInvalidRedisConfig = errors.New("invalid redis config")
ErrInvalidRedisConfig is when the redis config is missing or invalid
var ErrInvalidTTL = errors.New("invalid ttl")
ErrInvalidTTL is returned for a negative TTL, and for a lock TTL of zero or less
var ErrKeyNotFound = errors.New("key not found")
ErrKeyNotFound is returned when a record is not found for a given key
var ErrKeyRequired = errors.New("key is empty and required")
ErrKeyRequired is returned when the key is empty (key->value)
var ErrLoadInProgress = errors.New("another caller is still loading this key")
ErrLoadInProgress is returned by GetOrLoad and GetOrLoadWithOptions when another process holds the key's fill lock and LockWait passes without a stored value
var ErrLockCreateFailed = errors.New("failed creating cache lock")
ErrLockCreateFailed is the error when creating a lock fails
var ErrLockExists = errors.New("lock already exists with a different secret")
ErrLockExists is wrapped by the error of WriteLock, WriteLockWithSecret, and WaitWriteLock when another secret holds the lock
var ErrSecretGenerationFailed = errors.New("failed generating secret")
ErrSecretGenerationFailed is the error if the secret failed to generate
var ErrSecretRequired = errors.New("secret is empty and required")
ErrSecretRequired is returned when the secret is empty (value)
var ErrTTWCannotBeEmpty = errors.New("the TTW value cannot be empty")
ErrTTWCannotBeEmpty is when the TTW field is empty
Functions ¶
func GetModelValue ¶ added in v1.3.0
GetModelValue retrieves the value stored at key and unmarshals its JSON into a value of type T. It is the generic, value-returning counterpart to Client.GetModel: rather than taking a caller-allocated pointer, it returns the decoded value directly, so the caller writes
user, found, err := GetModelValue[User](ctx, c, key)
instead of allocating a User and passing its address.
found reports whether the key existed. On a miss it returns the zero value of T, false, and a nil error, so a missing key is distinguished from a decode or transport error without inspecting a sentinel. Any other error is returned as-is with found false and the zero value of T.
func GetOrLoad ¶ added in v1.5.0
func GetOrLoad[T any](ctx context.Context, c ClientInterface, key string, ttl time.Duration, load func(context.Context) (T, error), ) (T, error)
GetOrLoad returns the value stored at key, decoded from JSON into a T. On a miss it calls load once, stores its result with ttl, and returns it.
It is GetOrLoadWithOptions with the default LoadOptions:
report, err := cachestore.GetOrLoad(ctx, client, "report:daily", time.Minute, buildReport)
Example ¶
ExampleGetOrLoad reads one key three times: the first read misses and calls load, and the next two find the stored value.
package main
import (
"context"
"fmt"
"time"
cachestore "github.com/mrz1836/go-cachestore"
)
func main() {
ctx := context.Background()
client, err := cachestore.NewClient(ctx, cachestore.WithFreeCache())
if err != nil {
fmt.Println(err)
return
}
defer client.Close(ctx)
// load stands in for an expensive query
loads := 0
load := func(context.Context) (int, error) {
loads++
return 42, nil
}
var answer int
for range 3 {
if answer, err = cachestore.GetOrLoad(ctx, client, "answer", time.Minute, load); err != nil {
fmt.Println(err)
return
}
fmt.Println(answer)
}
fmt.Println("loads:", loads)
}
Output: 42 42 42 loads: 1
func GetOrLoadWithOptions ¶ added in v1.5.0
func GetOrLoadWithOptions[T any](ctx context.Context, c ClientInterface, key string, ttl time.Duration, load func(context.Context) (T, error), opts LoadOptions, ) (T, error)
GetOrLoadWithOptions returns the value stored at key, decoded from JSON into a T. On a miss it calls load once, stores its result as JSON with ttl (whole seconds, rounded up, as SetModel stores it), and returns it.
Callers on the same *Client and key share one call to load; the others wait for its result. On Redis and Valkey, that call runs only while it holds the key's fill lock, "<key>:fill-lock", so processes share it too: a caller that finds the lock held re-reads the key every PollInterval, takes the lock itself once it is free and the key is still empty, and returns ErrLoadInProgress when LockWait passes without a value. FreeCache has no fill lock, so there the shared call is the whole guarantee. Another ClientInterface implementation shares nothing in one process, though the fill lock still applies.
An error from load reaches every caller of that call, as load returned it, and nothing is stored: errors are never cached. A stored value that no longer decodes into a T counts as a miss, and the load replaces it. A cache error is returned as is.
load runs with the first caller's context values but not its cancellation, under a deadline of LockTTL, so one caller leaving fails none of the others and a load never outlives its fill lock. Each caller returns its own context's error as soon as its context is done. A panic in load is raised again in each waiting caller, with the load's stack.
T must round-trip through encoding/json, and each caller decodes its own copy. An empty key (after trimming) returns ErrKeyRequired, a ttl of zero or less ErrInvalidTTL, and a done ctx its own error, before any cache call.
func SetModelValue ¶ added in v1.3.0
func SetModelValue[T any](ctx context.Context, c CacheService, key string, value T, ttl time.Duration, dependencies ...string) error
SetModelValue marshals value to JSON and stores it at key with the given TTL. It is the generic counterpart to Client.SetModel and the write side of GetModelValue.
The TTL follows SetModel's rule: whole seconds, rounded up; 0 is no expiry; a negative TTL returns ErrInvalidTTL and stores nothing.
Redis only supports dependency keys at this time.
Types ¶
type CacheService ¶
type CacheService interface {
Delete(ctx context.Context, key string) error
Get(ctx context.Context, key string) (string, error)
GetModel(ctx context.Context, key string, model interface{}) error
Set(ctx context.Context, key string, value interface{}, dependencies ...string) error
SetTTL(ctx context.Context, key string, value interface{}, ttl time.Duration, dependencies ...string) error
SetModel(ctx context.Context, key string, model interface{}, ttl time.Duration, dependencies ...string) error
}
CacheService are the cache related methods
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the client (configuration)
func (*Client) EmptyCache ¶
EmptyCache will empty the cache entirely
CAUTION: this will dump all the stored cache
func (*Client) Get ¶
Get will return a value from a given key
Redis will be an interface{} but really a string (empty string)
func (*Client) GetModel ¶
GetModel will get a model (parsing JSON (bytes) -> Model)
Model needs to be a pointer to a struct
func (*Client) IsNewRelicEnabled ¶
IsNewRelicEnabled will return if new relic is enabled
func (*Client) RedisConfig ¶
func (c *Client) RedisConfig() *RedisConfig
RedisConfig will return the Redis config client if found
func (*Client) ReleaseLock ¶
ReleaseLock will release a given lock key only if the secret matches
Taking a lock and releasing it are each one atomic step on both engines. On FreeCache, which has no compare-and-delete, a release leaves an empty value that expires within a second; Get reads it as missing, and the next lock takes it
func (*Client) Set ¶
func (c *Client) Set(ctx context.Context, key string, value interface{}, dependencies ...string) error
Set will set a key->value using the current engine
The value has no expiry, on either engine Redis only supports dependency keys at this time Value should be used as a string for best results
func (*Client) SetModel ¶
func (c *Client) SetModel(ctx context.Context, key string, model interface{}, ttl time.Duration, dependencies ...string, ) error
SetModel will set any model or struct (parsing Model->JSON (bytes))
The TTL follows SetTTL's rule: whole seconds, rounded up, on both engines; 0 is no expiry; a negative TTL returns ErrInvalidTTL and stores nothing. FreeCache counts time in whole seconds, so there an entry expires within the last second of its TTL
Model needs to be a pointer to a struct Redis only supports dependency keys at this time
func (*Client) SetTTL ¶ added in v0.4.0
func (c *Client) SetTTL(ctx context.Context, key string, value interface{}, ttl time.Duration, dependencies ...string) error
SetTTL will set a key->value using the current engine with a TTL
The TTL is counted in whole seconds, rounded up, on both engines, so a fraction never shortens it or turns it into no expiry: 500ms lives one second, and 1.5s two. A TTL of 0 stores the value with no expiry, as Set does. A negative TTL returns ErrInvalidTTL and stores nothing. FreeCache counts time in whole seconds, so there an entry expires within the last second of its TTL
Redis only supports dependency keys at this time Value should be used as a string for best results
func (*Client) WaitWriteLock ¶
WaitWriteLock will try to take a lock until it gets one or the TTW (in seconds) runs out
While another secret holds the lock, it tries again every 10 milliseconds. It returns ctx's error as soon as ctx is done, any other failure at once, and, when the TTW runs out, the last attempt's error, which wraps ErrLockExists and ErrLockCreateFailed. A nil ctx waits with no cancellation. The lock TTL (in seconds) must be at least one: zero or less returns ErrInvalidTTL
func (*Client) WriteLock ¶
WriteLock will create a unique lock/secret with a TTL (seconds) to expire The lockKey is unique and should be deterministic The secret will be automatically generated and stored in the locked key (returned)
The TTL must be at least one second: zero or less returns ErrInvalidTTL. Every failure to take the lock wraps ErrLockCreateFailed and its cause, and, when another secret holds the lock, ErrLockExists; compare with errors.Is
func (*Client) WriteLockWithSecret ¶ added in v0.1.2
func (c *Client) WriteLockWithSecret(ctx context.Context, lockKey, secret string, ttl int64) (string, error)
WriteLockWithSecret will create a lock with the given secret with a TTL (seconds) to expire The lockKey is unique and should be deterministic The secret should be unique per instance/process that wants to acquire the lock
Taking the lock again with the same secret succeeds and resets its TTL. The TTL must be at least one second: zero or less returns ErrInvalidTTL. Every failure to take the lock wraps ErrLockCreateFailed and its cause, and, when another secret holds the lock, ErrLockExists; compare with errors.Is
type ClientInterface ¶
type ClientInterface interface {
CacheService
LockService
Close(ctx context.Context)
Debug(on bool)
EmptyCache(ctx context.Context) error
Engine() Engine
FreeCache() *freecache.Cache
IsDebug() bool
IsNewRelicEnabled() bool
Redis() *cache.Client
RedisConfig() *RedisConfig
}
ClientInterface is the cachestore interface
type ClientOps ¶
type ClientOps func(c *clientOptions)
ClientOps allow functional options to be supplied that overwrite default client options.
func WithFreeCache ¶
func WithFreeCache() ClientOps
WithFreeCache will set the cache to local memory using FreeCache
func WithFreeCacheConnection ¶
WithFreeCacheConnection will set the cache to use an existing FreeCache connection
func WithLogger ¶
func WithLogger(customLogger zLogger.GormLoggerInterface) ClientOps
WithLogger will set the custom logger interface
func WithRedis ¶
func WithRedis(redisConfig *RedisConfig) ClientOps
WithRedis will set the redis configuration
func WithRedisConnection ¶
WithRedisConnection will set an existing redis connection (read & write)
type Engine ¶
type Engine string
Engine is the different engines that are supported for the cachestore
const ( Empty Engine = "empty" // No engine set FreeCache Engine = "freecache" // FreeCache (in-memory cache) Redis Engine = "redis" // Redis )
Supported engines
type LoadOptions ¶ added in v1.5.0
type LoadOptions struct {
// LockTTL is the fill lock's TTL, rounded up to whole seconds, and the longest
// one load may run. It defaults to 10 seconds.
LockTTL time.Duration
// LockWait is how long a caller waits for another process's load before it
// returns ErrLoadInProgress. It defaults to 5 seconds.
LockWait time.Duration
// PollInterval is how often a waiting caller re-reads the key. It defaults to
// 50 milliseconds.
PollInterval time.Duration
}
LoadOptions tune GetOrLoadWithOptions. A field that is zero or negative takes its default.
type LockService ¶
type LockService interface {
ReleaseLock(ctx context.Context, lockKey, secret string) (bool, error)
WaitWriteLock(ctx context.Context, lockKey string, ttl, ttw int64) (string, error)
WriteLock(ctx context.Context, lockKey string, ttl int64) (string, error)
WriteLockWithSecret(ctx context.Context, lockKey, secret string, ttl int64) (string, error)
}
LockService are the locking related methods
type RedisConfig ¶
type RedisConfig struct {
DependencyMode bool `json:"dependency_mode" mapstructure:"dependency_mode"` // false for digital ocean (not supported)
MaxActiveConnections int `json:"max_active_connections" mapstructure:"max_active_connections"` // 0
MaxConnectionLifetime time.Duration `json:"max_connection_lifetime" mapstructure:"max_connection_lifetime"` // 0
MaxIdleConnections int `json:"max_idle_connections" mapstructure:"max_idle_connections"` // 10
MaxIdleTimeout time.Duration `json:"max_idle_timeout" mapstructure:"max_idle_timeout"` // 240 * time.Second
URL string `json:"url" mapstructure:"url"` // redis://localhost:6379
// Authentication (ElastiCache RBAC / Redis ACL). When Username is set a
// two-arg AUTH is issued; otherwise a single-arg AUTH is used. Supplying
// credentials here keeps them out of the URL/logs.
Username string `json:"username" mapstructure:"username"`
Password string `json:"password" mapstructure:"password"`
// TLS configuration
UseTLS bool `json:"use_tls" mapstructure:"use_tls"` // true for digital ocean (required); rediss:// also enables TLS
// TLSConfig, when set, is used directly for the TLS handshake and takes
// precedence over the TLS* fields below. Not serializable (json/mapstructure ignored).
TLSConfig *tls.Config `json:"-" mapstructure:"-"`
// TLSServerName overrides the SNI/ServerName used for certificate
// validation. Leave empty to default to the endpoint host (correct for ElastiCache).
TLSServerName string `json:"tls_server_name" mapstructure:"tls_server_name"`
// TLSInsecureSkipVerify disables certificate verification (testing only).
TLSInsecureSkipVerify bool `json:"tls_insecure_skip_verify" mapstructure:"tls_insecure_skip_verify"`
// TLSCACertPath is an optional path to a PEM CA bundle used to verify the server.
TLSCACertPath string `json:"tls_ca_cert_path" mapstructure:"tls_ca_cert_path"`
}
RedisConfig is the configuration for the cache client (redis or valkey)
Redis and Valkey are wire-compatible, so the same configuration connects to either engine — point URL at your instance. For AWS ElastiCache with in-transit encryption use a rediss:// URL (or set UseTLS); for RBAC/ACL set Username and Password.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package cachestoretest provides helpers for running real Redis and Valkey servers in tests using the local Docker CLI.
|
Package cachestoretest provides helpers for running real Redis and Valkey servers in tests using the local Docker CLI. |
|
examples
|
|
|
debugging
command
Package main shows how to use the debugging feature of the caching library
|
Package main shows how to use the debugging feature of the caching library |
|
new_client
command
Package main shows how to create a new client
|
Package main shows how to create a new client |
|
new_relic
command
Package main shows how to use new relic with the caching library
|
Package main shows how to use new relic with the caching library |
|
with_freecache
command
Package main shows how to use freecache with the caching library
|
Package main shows how to use freecache with the caching library |
|
with_redis
command
Package main shows how to use redis with the caching library
|
Package main shows how to use redis with the caching library |
