gas/cache
cache/valkey
import "github.com/gasmod/gas/cache/valkey"Package valkey is a cache on a Valkey server, as a gas.CacheProvider. It speaks the Valkey protocol through valkey-go, so it reaches Redis and other servers that speak it too, and the cache is shared by every instance of an app that uses the server.
Service implements gas.Service, gas.CacheProvider, gas.HealthReporter and gas.ReadyReporter, and keeps the contract of the cache package.
In an app, the container builds the store from New and calls its Init. By hand, with a configuration given in code:
cfg := valkey.DefaultConfig()cfg.Cache.Addr = "localhost:6379"cfg.Cache.KeyPrefix = "app:"
c, err := valkey.New(valkey.WithConfig(cfg))(nil, logger)if err != nil { return err}if err := c.Init(ctx); err != nil { return err}defer c.Close(ctx)
err = c.Set(ctx, "greeting", []byte("hello"), time.Minute)After this the server holds app:greeting, which expires in a minute,
and c.Get(ctx, “greeting”) returns hello until then.
Configuration
Section titled “Configuration”The settings live in the cache section, in Settings:
cache.addr: the server’s address, as host:port, or for a cluster the address of one of its nodes, as under Connecting. It has no default, and is required.cache.username: the ACL user to authenticate as. Default: none, the server’s default user.cache.password: the password to authenticate with, a Secret, which fmt, encoding/json, YAML encoders and log/slog write as[redacted]. Default: none; no password is sent.cache.db: the database number to select, 0 or more; the server decides how many there are, and a valkey-server 8 cluster has only
- Default: DefaultDB, 0.
cache.keyprefix: prepended to every key the store’s methods send, as under Keys. Default: none.cache.defaultttl: the TTL of a Set with a zero TTL, 0 or more; 0 is no expiry. Default: DefaultTTL, no expiry.cache.dialtimeout: the bound of each connect attempt and of each dial, above 0, as under Connecting. Default: DefaultDialTimeout (5s).cache.optimeout: the bound of each command, the connect handshake and PING included, above 0, as under Timeouts and Connecting. Default: DefaultOpTimeout (3s).cache.tls: turns on TLS, as under TLS. Default: false.cache.tlsservername: the name the server’s certificate is checked against; it requirestls. Default: the host ofaddr.cache.connretries: how many times a failed connect is retried, 0 to 10. Default: DefaultConnRetries, 0.cache.connretryinterval: the wait before the first retry, 100ms to MaxConnRetryInterval (30s), checked only whenconnretriesis positive. Default: DefaultConnRetryInterval (2s).
Service.Init resolves the configuration each time it runs, in one of two ways:
- Without WithConfig, it binds DefaultConfig from the
gas.ConfigProvider, which checks the
validatetags. A nil ConfigProvider is the error cache.ErrNoConfigProvider. - With WithConfig, it takes a copy of the given Config, never changing the caller’s struct, and checks the same tags. A nil Config is the error cache.ErrNilConfig.
Either way, these rules then run, in this order, and the first that fails is the error:
- When
connretriesis positive,connretryintervalis in bounds. - Without WithTLSConfig,
tlsservernameis empty unlesstlsis on.
A failure wraps cache.ErrInvalidConfig and names the setting, never its value.
Service.Config returns a copy of the configuration the last successful
Init resolved, defaults included, or the zero Config before one. A
failed Init and Close leave it as it was. Its password stays a
Secret, which prints as [redacted].
The store sends each key as keyprefix followed by the key, so stores
or apps that share a server and a database keep apart by prefix, such
as app: or sessions:. The prefix is a plain string: nothing is
added between it and the key.
Stores share their keys when:
- They have the same prefix, or none.
- Their prefixes overlap. The key
sessions:xof a store with prefixapp:is the keyxof a store with prefixapp:sessions:, bothapp:sessions:xon the server.
Stores that share a server and a database keep apart only when no prefix is a prefix of another.
On a cluster, the slot of a key is that of the whole sent key, prefix
included. A prefix that holds a hash tag, such as {app}:, puts every
key of the store in one slot, on one node.
Connecting
Section titled “Connecting”The store connects to a standalone server or to a Valkey or Redis
Cluster, at addr. Sentinel deployments are not supported.
Init makes connect attempts. Each attempt builds a valkey-go client,
which dials addr, authenticates with HELLO, selects db, asks the
server for the cluster’s slots with CLUSTER SHARDS (CLUSTER SLOTS from
a server before version 8), and is then checked with PING, all within
Init’s context and dialtimeout.
A server that is not a cluster replies to CLUSTER with an error, and
valkey-go then uses its single-server client. So does a user that may
not run CLUSTER, whose reply is NOPERM: on a cluster, the store then
talks to the node at addr alone, and a key in a slot that node does
not serve fails with a MOVED reply, as under Server replies.
On a cluster, valkey-go sends each command to the node that serves the
key’s slot, follows MOVED and ASK redirects, and reads the slots again
after a redirect or a failed command. It connects to each node at the
address the cluster announces for it, which must be reachable from the
app, with the same username, password, db and TLS settings.
addr is only where it starts, a single seed. A db other than 0
fails Init on a valkey-server 8 cluster, which refuses SELECT, with the
reason failed.
valkey-go also bounds the handshake, HELLO and SELECT, CLUSTER SHARDS
and the PING, each by optimeout, as it does every command. So with an optimeout
shorter than dialtimeout, a server that accepts and never answers
fails the attempt after optimeout.
valkey-go dials without a context while it builds a client. So the store gives it a dial function that cancels the dial, and closes a connection it made, when the attempt’s context ends before the attempt does. An attempt never outlives Init’s context.
The connections valkey-go dials after Init, when it reconnects, are
bounded by dialtimeout, their handshake by optimeout too, and both
by the context of the command that needed them.
Retries
Section titled “Retries”A failed attempt is retried up to connretries times. Before each
retry, Init logs valkey connection failed, retrying at warn level,
with attempt (from 1), retries, wait and reason, and waits:
connretryintervalbefore the first retry.- Then twice the previous wait, up to MaxConnRetryInterval.
The wait ends early when Init’s context ends, and Init then fails at once. Service.Close ends an attempt or a wait in progress the same way, as under Lifecycle.
Connect errors
Section titled “Connect errors”When the attempts run out, Init fails with an error wrapping
ErrConnect, connect: and a reason. When Init’s context ended, the
error holds the context’s error too, after the reason. The reason is
the first of these that holds:
authentication failed: the server replied WRONGPASS or NOAUTH.timed out: a deadline passed, in a context or on the network. The error then wraps context.DeadlineExceeded too.connection refused: the server refused the TCP connection.unreachable: any other network error, such as a failed name lookup.failed: anything else, such as a TLS handshake that failed or a database number the server does not have.
valkey-go’s error itself is not kept: its network errors hold the address. The reason and the server’s own logs are what an operator diagnoses with.
Timeouts
Section titled “Timeouts”Every command runs within its context and optimeout, whichever ends
first. So a server that stops answering cannot hold a call longer than
optimeout, even with a context that never ends. optimeout is also
valkey-go’s ConnWriteTimeout: a connection whose reply is that late is
closed.
valkey-go retries GET and EXISTS, which are read-only, after a network
error, with its own backoff of up to a second, until the command’s
deadline. SET, DEL and PING are never retried. The store leaves that
retry on, since the deadline bounds it. A GET or EXISTS whose attempts
keep failing ends with the last attempt’s reason, which is timed out
when the deadline cuts that attempt short.
Command errors
Section titled “Command errors”A command fails in one of these ways:
- At the connection, including after a reconnect that fails: an error
wrapping ErrCommand,
<op>:and a reason as for connecting, never valkey-go’s error. - Ended by
optimeout:<op>: timed out, wrapping ErrCommand and context.DeadlineExceeded too. - Ended by its own context: the context’s error after
<op>:, wrapped, without ErrCommand.
Which of the last two it is depends on which deadline was in force, not
on which timer fired first. A timeout of a command whose context’s
deadline is no later than optimeout’s is the context’s error, <op>: context deadline exceeded, even when the connection’s deadline passed a
moment before the context’s.
Server replies
Section titled “Server replies”A server’s error reply also wraps ErrCommand. Its text is kept only for
the codes whose text, in every form the server sends it, holds nothing
of the command, such as a key: WRONGTYPE, OOM, READONLY,
LOADING, MASTERDOWN, MISCONF and NOREPLICAS. An example is
WRONGTYPE Operation against a key holding the wrong kind of value.
For these, valkey-go’s *valkey.ValkeyError is in the chain for
errors.As.
Every other reply is cut to its code, without the ValkeyError. Their text can hold more, for example:
- A server with a command renamed or disabled replies
ERR unknown command 'GET', with args beginning with:and the key. - NOPERM names the user.
- MOVED, ASK and REDIRECT hold an address.
- BUSY can carry a module’s text.
A cluster’s CLUSTERDOWN and TRYAGAIN replies are cut to their code too,
such as get: CLUSTERDOWN. valkey-go retries GET and EXISTS after
either, as after a network error, until the command’s deadline.
valkey-go drops ERR from a reply’s text, so a reply whose first word
is not one of the codes valkey-server 8 sends is cut to ERR. A
WRONGPASS or NOAUTH reply, which a reconnect with rotated credentials
gets, is the reason authentication failed.
With tls on, the store connects with TLS 1.2 or later. It checks the
server’s certificate against the system’s root certificates, and checks
it names tlsservername, or, when that is empty, the host of addr.
On a cluster, the store connects to each node with TLS, at the TLS port
the cluster announces, and checks the node’s certificate names
tlsservername, or, when that is empty, the host it connects to.
WithTLSConfig takes a *tls.Config for anything else, such as a private
certificate authority or a client certificate. It turns TLS on and
replaces tls and tlsservername, and each Init uses a clone of it.
The clone is shallow, as tls.Config.Clone makes it: RootCAs,
Certificates and the callbacks are shared with the given config, so it
must not change once it is passed.
Security
Section titled “Security”No error the store makes and no log it writes holds a key, a value, the address, the user name or the password:
- The logs carry the database number, whether TLS is on, the retry
attempt,retriesandwait, and fixed reasons. - Server replies kept in errors hold no key, as under Server replies.
- fmt, encoding/json, YAML encoders and log/slog write the password of
a Settings or a Config as
[redacted], and encoding/gob fails on it rather than encode it.
Without TLS, the password and every value cross the network in plain text. Turn TLS on for a server outside the host or its private network.
Hostile servers
Section titled “Hostile servers”The store trusts the server’s replies. A hostile server, or a man-in-the-middle on a plain-text connection, can crash the process.
valkey-go allocates the length a bulk reply announces before it reads the reply, without a bound (readB in its resp.go). So a reply that announces a huge length either panics, on valkey-go’s own goroutine when the connection is pipelining, or takes as much memory as it announces, until the runtime runs out.
The fault is valkey-go’s, and the store cannot catch it. Use TLS to reach a server over a network that is not trusted.
Lifecycle
Section titled “Lifecycle”A successful Init publishes the client, logs service initialized at
info level with db and tls, and only then do the methods use it.
Init on an initialized store returns cache.ErrAlreadyInitialized and
changes nothing. A failed Init closes what it built and leaves the
store as it was.
Service.Close runs these steps, in order:
- It makes the store closed.
- It closes the client, which waits for the commands in progress, each
bounded by
optimeout, and stops valkey-go’s goroutines. - It logs
service closedat info level.
Close on a store that is not initialized returns nil and logs nothing. Close ignores its context. Init after Close connects again, with a configuration resolved afresh; the server keeps its keys.
Close on a store whose Init is in progress cancels that Init’s connect
attempt or retry wait, and waits for Init to return. Init then fails
with an error wrapping cache.ErrClosed, init: service closed, closes
what it built, and leaves the store as it was.
Outside a successful Init, every method but Init, Close, Name, Client and Config returns an error wrapping:
- cache.ErrNotInitialized, before the first successful Init.
- cache.ErrClosed, after Close, until Init succeeds.
A command that Close interrupts returns cache.ErrClosed too. New’s constructor fails with cache.ErrNilLogger for a nil logger. A nil ConfigProvider is accepted, and Init then requires WithConfig.
Health
Section titled “Health”Service.CheckHealth does no I/O: it fails only when the store is not initialized or its context has ended, since valkey-go reconnects by itself after a network failure.
Service.CheckReady sends PING within its context and optimeout, with
errors as a command’s, after ping: . On a cluster, PING goes to one
node, which valkey-go picks.
Client
Section titled “Client”Service.Client returns the valkey-go client, for the commands the store has no method for, or nil when the store is not initialized. The commands sent on it:
- are not prefixed with
keyprefix; - on a cluster, go through valkey-go’s cluster client, so a command on keys in different slots fails with CROSSSLOT;
- are bounded only by their own context;
- return valkey-go’s errors as they are, which can hold the address;
- are never answered from a client-side cache. The client is built with valkey-go’s DisableCache, so its connections send no CLIENT TRACKING, which an ACL user may not be allowed, and DoCache and DoMultiCache send each command to the server, as Do and DoMulti do.
The store closes the client on Close.
Concurrency
Section titled “Concurrency”A Service is safe for concurrent use. Init and Close run one at a time, under a lock that Close holds while it closes the client too. So a Close that runs at the same time as another returns only once the client is closed and its goroutines have stopped.
Init swaps in what it connected at once, so the other methods, which take no lock, use one Init’s client throughout a call. valkey-go pipelines concurrent commands on its connections.
Errors
Section titled “Errors”The sentinel errors of this package, to be tested with errors.Is:
- ErrConnect: Init could not connect, as under Connect errors.
- ErrCommand: a command failed at the connection or with a server reply, as under Command errors and Server replies.
The other errors wrap a sentinel of the cache package, as the cache package describes. Every error starts with ServiceName and the operation.
A configuration that fails its tags gets the validator’s error after
gas/cache/valkey: init: invalid config: validate config: , such as:
Key: 'Config.Cache.Addr' Error:Field validation for 'Addr' failed on the 'required' tagThe other errors, as returned, with get standing for each operation
that can fail the same way:
gas/cache/valkey: logger is nilgas/cache/valkey: init: config is nilgas/cache/valkey: init: no config providergas/cache/valkey: init: invalid config: Cache.ConnRetryInterval must be 100ms to 30s if Cache.ConnRetries > 0gas/cache/valkey: init: invalid config: Cache.TLSServerName requires Cache.TLSgas/cache/valkey: init: service already initializedgas/cache/valkey: init: service closedgas/cache/valkey: init: context canceledgas/cache/valkey: connect: authentication failedgas/cache/valkey: connect: timed outgas/cache/valkey: connect: timed out: context deadline exceededgas/cache/valkey: connect: connection refusedgas/cache/valkey: connect: connection refused: context deadline exceededgas/cache/valkey: connect: unreachablegas/cache/valkey: connect: failedgas/cache/valkey: get: invalid key: emptygas/cache/valkey: get: key not foundgas/cache/valkey: get: service not initializedgas/cache/valkey: get: service closedgas/cache/valkey: get: context canceledgas/cache/valkey: get: context deadline exceededgas/cache/valkey: get: timed outgas/cache/valkey: delete: connection refusedgas/cache/valkey: get: WRONGTYPE Operation against a key holding the wrong kind of valuegas/cache/valkey: get: NOPERMgas/cache/valkey: get: ERRgas/cache/valkey: set: invalid TTL: negativegas/cache/valkey: health: service not initializedgas/cache/valkey: ping: timed outAPI reference
Section titled “API reference”Constants
Section titled “Constants”const ( // DefaultDB is the database number of DefaultConfig. DefaultDB = 0 // DefaultTTL is the TTL of DefaultConfig for a Set with a zero TTL: // no expiry. DefaultTTL time.Duration = 0 // DefaultDialTimeout is the bound of each connect attempt of // DefaultConfig. DefaultDialTimeout = 5 * time.Second // DefaultOpTimeout is the bound of each command of DefaultConfig. DefaultOpTimeout = 3 * time.Second // DefaultConnRetries is the number of connect retries of // DefaultConfig. DefaultConnRetries = 0 // DefaultConnRetryInterval is the wait before the first connect retry // of DefaultConfig. DefaultConnRetryInterval = 2 * time.Second // MaxConnRetryInterval is the longest ConnRetryInterval, and caps the // doubling of the wait between connect retries. MaxConnRetryInterval = 30 * time.Second)const ServiceName = "gas/cache/valkey"ServiceName is the name of the Valkey store, returned by Service.Name and prefixed to every error the store returns.
Variables
Section titled “Variables”var ( // ErrConnect indicates that Init could not connect to the server, as // described in the package documentation. ErrConnect = errors.New("connect failed") // ErrCommand indicates that a command failed, at the connection or // with a server reply, as described in the package documentation. ErrCommand = errors.New("command failed"))func New
Section titled “func New”func New(opts ...Option) func(gas.ConfigProvider, gas.Logger) (*Service, error)New returns the constructor of a Service with opts applied, in the shape the gas container expects. The constructor returns an error wrapping cache.ErrNilLogger for a nil logger; a nil ConfigProvider is accepted, and Init then requires WithConfig.
type Config
Section titled “type Config”type Config struct { // Cache holds the settings. Cache Settings}Config holds the Valkey store’s configuration, read from the cache
section.
func DefaultConfig
Section titled “func DefaultConfig”func DefaultConfig() *ConfigDefaultConfig returns the configuration a store starts from before binding: no address, DefaultDB, DefaultTTL, DefaultDialTimeout, DefaultOpTimeout, DefaultConnRetries, DefaultConnRetryInterval, no credentials, no key prefix and no TLS.
type Option
Section titled “type Option”type Option func(*Service)Option configures a Service. Options only record what they are given; Init checks it.
func WithConfig
Section titled “func WithConfig”func WithConfig(cfg *Config) OptionWithConfig makes Init use a copy of cfg instead of binding the configuration from the ConfigProvider. Init copies *cfg each time it runs and never changes it; the copy is checked against its validate tags as a bound configuration is. A nil cfg makes Init fail with cache.ErrNilConfig.
Default: bind the cache section from the ConfigProvider over
DefaultConfig.
func WithTLSConfig
Section titled “func WithTLSConfig”func WithTLSConfig(cfg *tls.Config) OptionWithTLSConfig makes the store connect with TLS configured by cfg, for what the TLS settings cannot express, such as a private certificate authority or a client certificate. It turns TLS on and replaces the TLS and TLSServerName settings, which are then ignored. Each Init uses cfg.Clone(), made when Init runs; the store never changes cfg. The clone is shallow: it shares RootCAs, Certificates, the callbacks and the other pointers with cfg, so do not change cfg, or what it points to, once it is passed. A nil cfg leaves the TLS settings in charge.
Default: TLS as the TLS and TLSServerName settings say.
type Secret
Section titled “type Secret”type Secret = gas.SecretSecret is gas.Secret: a string that is never printed, marshaled or logged, such as Settings.Password. Configuration binds into it as into a string, and string(s) is the value.
type Service
Section titled “type Service”type Service struct { // contains filtered or unexported fields}Service is a cache on a Valkey server, as described in the package documentation. It is safe for concurrent use.
func (*Service) CheckHealth
Section titled “func (*Service) CheckHealth”func (s *Service) CheckHealth(ctx context.Context) errorCheckHealth reports liveness without I/O: an error wrapping cache.ErrNotInitialized or cache.ErrClosed when the store is not initialized, the context’s error when ctx has ended, and else nil.
func (*Service) CheckReady
Section titled “func (*Service) CheckReady”func (s *Service) CheckReady(ctx context.Context) errorCheckReady reports readiness by sending PING, within ctx and
OpTimeout. Its errors are as a command’s, after ping: .
func (*Service) Client
Section titled “func (*Service) Client”func (s *Service) Client() valkey.ClientClient returns the connected valkey.Client, or nil when the store is not initialized, as described in the package documentation. Commands sent on it are not prefixed with KeyPrefix and not bounded by OpTimeout, and their errors are valkey-go’s own.
func (*Service) Close
Section titled “func (*Service) Close”func (s *Service) Close(context.Context) errorClose cancels an Init in progress and waits for it to return, makes every later call but Init return an error wrapping cache.ErrClosed, then closes the client, which waits for the commands in progress to finish; each is bounded by OpTimeout. A Close that runs at the same time waits for it too. Close on a store that is not initialized returns nil and logs nothing. It ignores its context.
func (*Service) Config
Section titled “func (*Service) Config”func (s *Service) Config() ConfigConfig returns a copy of the configuration the last successful Init resolved, defaults included, or the zero Config before one. A failed Init and Close leave it as it was. Config holds no slice, map or pointer, so the copy shares nothing with the store, and Password stays a Secret.
func (*Service) Delete
Section titled “func (*Service) Delete”func (s *Service) Delete(ctx context.Context, key string) errorDelete removes the value of KeyPrefix and key, with DEL. Deleting a key the server does not hold is not an error.
func (*Service) Exists
Section titled “func (*Service) Exists”func (s *Service) Exists(ctx context.Context, key string) (bool, error)Exists reports whether the server holds a value under KeyPrefix and key, with EXISTS.
func (*Service) Get
Section titled “func (*Service) Get”func (s *Service) Get(ctx context.Context, key string) ([]byte, error)Get returns the value of KeyPrefix and key, or an error wrapping cache.ErrKeyNotFound when the server holds none. An empty value comes back as an empty, non-nil slice.
func (*Service) Init
Section titled “func (*Service) Init”func (s *Service) Init(ctx context.Context) errorInit resolves and checks the configuration, connects, and publishes the client, as described in the package documentation. On an initialized store it returns cache.ErrAlreadyInitialized and changes nothing. A failed Init closes what it opened and leaves the store as it was.
func (*Service) Name
Section titled “func (*Service) Name”func (*Service) Name() stringName returns ServiceName.
func (*Service) Set
Section titled “func (*Service) Set”func (s *Service) Set(ctx context.Context, key string, value []byte, ttl time.Duration) errorSet stores value under KeyPrefix and key, with SET and, when the value expires, PX, as described in the package documentation. A nil value is stored as empty. A Set without expiry clears the TTL a key had.
type Settings
Section titled “type Settings”type Settings struct { // Addr is the server's address, as host:port. It is required. Addr string `validate:"required"` // Username is the ACL user to authenticate as; empty is the default // user. Username string // Password is the password to authenticate with; empty sends none. // fmt prints it as `[redacted]`. Password Secret // KeyPrefix is prepended to every key the store's methods send. KeyPrefix string // TLSServerName is the name the server's certificate is checked // against when TLS is on; empty is the host of Addr. TLSServerName string // DefaultTTL is the TTL of a Set with a zero TTL; 0 is no expiry. DefaultTTL time.Duration `validate:"min=0"` // DialTimeout bounds each connect attempt: dial, handshake and ping. // OpTimeout bounds the handshake and the ping too. DialTimeout time.Duration `validate:"gt=0"` // OpTimeout bounds each command. OpTimeout time.Duration `validate:"gt=0"` // ConnRetryInterval is the wait before the first connect retry. It is // checked only when ConnRetries is positive. ConnRetryInterval time.Duration // DB is the database number to select. DB int `validate:"min=0"` // ConnRetries is how many times a failed connect is retried. ConnRetries int `validate:"min=0,max=10"` // TLS turns on TLS with the system's root certificates. TLS bool}Settings are the Valkey store’s settings, as described in the package documentation.