Documentation
¶
Index ¶
- Constants
- func OverlayURL(cfg *ValkeyConfig, raw string) error
- type CFValkey
- func (c *CFValkey) Client() valkey.Client
- func (c *CFValkey) GetDependencies() []string
- func (c *CFValkey) GetInitOrderStage() cf.Stage
- func (c *CFValkey) Health(ctx context.Context) error
- func (c *CFValkey) Init(ctx context.Context, fw *cf.CaerusFramework) error
- func (c *CFValkey) Key(parts ...string) string
- func (c *CFValkey) KeyPrefix() string
- func (c *CFValkey) LockMeter() *LockMeter
- func (c *CFValkey) Metrics() []cf_observability.Metric
- func (c *CFValkey) Name() string
- func (c *CFValkey) OnConfigReload(source string, cfg any)
- func (c *CFValkey) RegisterConfigSources(conf any) error
- func (c *CFValkey) Shutdown(ctx context.Context) error
- type CommandHook
- type LockMeter
- type Option
- func WithAddress(addr string) Option
- func WithAddresses(addrs ...string) Option
- func WithClientName(name string) Option
- func WithClientOption(opt valkey.ClientOption) Option
- func WithCommandHook(hooks ...CommandHook) Option
- func WithConfig(cfg ValkeyConfig) Option
- func WithConfigSource(name, path string, opts ...SourceOption) Option
- func WithConnLifetime(d time.Duration) Option
- func WithConnWriteTimeout(d time.Duration) Option
- func WithDB(db int) Option
- func WithDegradedMode(enabled bool) Option
- func WithDialTimeout(d time.Duration) Option
- func WithHealthWhenDegraded(policy string) Option
- func WithKeyPrefix(prefix string) Option
- func WithLogger(logger *slog.Logger) Option
- func WithName(name string) Option
- func WithPassword(password string) Option
- func WithPingTimeout(d time.Duration) Option
- func WithTLS(tlsCAFile, tlsCertFile, tlsKeyFile string) Option
- func WithTLSInsecureSkipVerify(skip bool) Option
- func WithUsername(username string) Option
- type SourceOption
- type ValkeyConfig
Constants ¶
const ( // ComponentName is the framework component name for the valkey component. // It is the identifier other components use in GetDependencies to require // valkey. ComponentName = "valkey" // ComponentStage is the stage data-layer components initialize in. It is // not a built-in bootstrap stage; AddComponent registers it automatically // the first time a component declares it. ComponentStage = cf.Stage("data") )
Variables ¶
This section is empty.
Functions ¶
func OverlayURL ¶
func OverlayURL(cfg *ValkeyConfig, raw string) error
OverlayURL merges connection fields from a redis/valkey URL into cfg. URL-derived fields win over existing values (file/env).
Types ¶
type CFValkey ¶
type CFValkey struct {
// contains filtered or unexported fields
}
CFValkey is the caerus-framework-valkey component. It wraps a valkey-go client, verifies connectivity at Init, and closes it at Shutdown.
func (*CFValkey) Client ¶
Client returns the valkey-go client. It is non-nil after a successful Init and nil before Init or after Shutdown. When command hooks are configured (WithCommandHook), the returned client routes Do and DoMulti through the hook chain; all other methods are delegated to the underlying client.
func (*CFValkey) GetDependencies ¶
GetDependencies implements cf.Dependencies. The component logs through the framework logs component, and depends on configuration when WithConfigSource is set.
func (*CFValkey) GetInitOrderStage ¶
GetInitOrderStage implements cf.CaerusComponent.
func (*CFValkey) Health ¶
Health implements cf.HealthProvider. It pings the valkey server, so the observability component's readiness endpoint reflects real connectivity. A nil client (before Init or after Shutdown) is unhealthy. After DegradedMode with a failed ping, behaviour follows health_when_degraded (default not_ready → still unhealthy for /readyz).
func (*CFValkey) Init ¶
Init implements cf.CaerusComponent. It creates the valkey-go client and verifies connectivity with a ping. By default a broken connection fails startup (fail-fast). With DegradedMode, a failed ping keeps the client and lets Initialize continue (metrics/logs scream; Health stays honest unless health_when_degraded=ready).
func (*CFValkey) Key ¶
Key builds a namespaced key by joining the configured prefix and parts with ":". The prefix's trailing ":" is normalized, so WithKeyPrefix("prod:") and WithKeyPrefix("prod") both produce the same keys:
v := cf_valkey.New(cf_valkey.WithKeyPrefix("prod:"))
v.Key("session", "abc") // "prod:session:abc"
v.Key("ratelimit", c.RealIP()) // "prod:ratelimit:192.0.2.1"
With an empty prefix, Key is a plain ":"-join of the parts.
func (*CFValkey) LockMeter ¶
LockMeter returns the component's shared lock-traffic meter. Distributed lock helpers in the patterns subpackage feed it via this accessor; the totals ride the component's Metrics() output (aggregated per component instance, disambiguated by the component label).
func (*CFValkey) Metrics ¶
func (c *CFValkey) Metrics() []cf_observability.Metric
Metrics implements cf_observability.MetricsProvider. Before Init or after Shutdown it returns nil. After Init (including DegradedMode without a live ping) it always returns samples so degrade/unreachable state is visible.
func (*CFValkey) Name ¶
Name implements cf.CaerusComponent. Returns the custom name set via WithName, or the default ComponentName ("valkey") if no custom name was set.
func (*CFValkey) OnConfigReload ¶
OnConfigReload implements cf.ConfigReloader. It rebuilds the client from the bound configuration source. The fresh value is delivered as cfg but the client is rebuilt from the source so the translation stays in one place. On failure the previous client is kept.
func (*CFValkey) RegisterConfigSources ¶
RegisterConfigSources implements cf.ConfigSourceRegistrar. The framework calls it during argv absorption; it registers this component's configuration source (name, path, env prefix, format, Owner and the VALKEY_URL AfterLoad overlay) with the configuration component. No-op when no source is bound.
type CommandHook ¶
type CommandHook interface {
// Do wraps a single command execution.
Do(ctx context.Context, cmd valkey.Completed,
next func(context.Context, valkey.Completed) valkey.ValkeyResult) valkey.ValkeyResult
// DoMulti wraps a pipelined batch of commands.
DoMulti(ctx context.Context, cmds []valkey.Completed,
next func(context.Context, []valkey.Completed) []valkey.ValkeyResult) []valkey.ValkeyResult
}
CommandHook intercepts commands sent through the component's client before they reach Valkey. Hooks are configured at construction with WithCommandHook and run in registration order around the real command: each hook calls next to continue the chain (and finally the network round-trip), or short-circuits by returning without calling next. Use it to attach spans, log slow commands, or count traffic without importing an instrumentation library into this module.
type LockMeter ¶
type LockMeter struct {
// contains filtered or unexported fields
}
LockMeter aggregates distributed-lock traffic counters for one valkey component. Mutexes created against the component increment it through LockMeter(); CFValkey.Metrics() then exposes the totals on /metrics as Prometheus counters. Counters are cumulative and only increase for the process lifetime and are emitted (zero until first increment) while the component is connected.
func (*LockMeter) IncAcquireBusy ¶
func (m *LockMeter) IncAcquireBusy()
IncAcquireBusy records an acquisition rejected because the lock was held.
func (*LockMeter) IncAcquireOK ¶
func (m *LockMeter) IncAcquireOK()
IncAcquireOK records a successful lock acquisition.
func (*LockMeter) IncUnlockMismatch ¶
func (m *LockMeter) IncUnlockMismatch()
IncUnlockMismatch records a release where the caller no longer owned the lock (expired or stolen).
func (*LockMeter) IncUnlockOK ¶
func (m *LockMeter) IncUnlockOK()
IncUnlockOK records a release that actually deleted the lock key.
func (*LockMeter) Metrics ¶
func (m *LockMeter) Metrics(labels map[string]string) []cf_observability.Metric
Metrics renders the meter's four counters, each carrying a copy of the caller's labels so the lock series share the component's identity. Counters are emitted while the component is connected (zero until first fired), so the series are always present on /metrics.
type Option ¶
type Option func(*options)
Option configures the valkey component at construction time.
func WithAddress ¶
WithAddress sets the single server address (default "127.0.0.1:6379").
func WithAddresses ¶
WithAddresses sets multiple server addresses (for cluster/sentinel setups).
func WithClientName ¶
WithClientName sets CLIENT SETNAME on connections.
func WithClientOption ¶
func WithClientOption(opt valkey.ClientOption) Option
WithClientOption sets the full valkey-go client option. Convenience setters (WithAddress/WithAddresses, WithUsername, WithPassword, WithDB, WithClientName) override the matching fields, so call them after WithClientOption if you combine them.
func WithCommandHook ¶
func WithCommandHook(hooks ...CommandHook) Option
WithCommandHook registers command hooks on the component. Multiple calls append; hooks run in registration order, the first hook wrapping the outermost. Use it to attach tracing spans, slow-command logging, or command counters to every Client().Do / DoMulti call. The hook interface lives here so the valkey module needs no instrumentation dependency (e.g. OpenTelemetry); apps implement CommandHook against the instrumenter of their choice.
func WithConfig ¶
func WithConfig(cfg ValkeyConfig) Option
WithConfig sets a static connection configuration snapshot. Non-zero fields of cfg override the values set by the convenience options. Prefer WithConfigSource when using caerus-framework-configuration with hot-reload.
func WithConfigSource ¶
func WithConfigSource(name, path string, opts ...SourceOption) Option
WithConfigSource binds this component to a named configuration source and registers that source with the configuration component (via the framework's ConfigSourceRegistrar pass during argv absorption). The module owns the Source: the config type, default EnvPrefix, the VALKEY_URL AfterLoad overlay and its Owner (Name(), so named instances reload correctly). main only points the instance at where the config lives.
cf_valkey.New(cf_valkey.WithConfigSource("valkey", "config/valkey.json"))
cf_valkey.New(cf_valkey.WithConfigSource("valkey-cache", "/etc/app/valkey-cache.yaml",
cf_valkey.WithSourceFormat(cf_configuration.FormatYAML)))
A path of "" registers an env-only (fileless) source when the EnvPrefix is non-empty. The path CLI override stays --<source-name> (ParseFlags). Declares a dependency on "configuration".
func WithConnLifetime ¶
WithConnLifetime sets a maximum connection lifetime. Connections older than this are closed and replaced. Zero means no limit (valkey-go default).
func WithConnWriteTimeout ¶
WithConnWriteTimeout sets the per-connection read/write timeout. It bounds pipeline response waits and triggers periodic PINGs for liveness.
func WithDegradedMode ¶ added in v0.0.3
WithDegradedMode allows Init to succeed when the connectivity ping fails. Default is hard-fail. Degraded mode screams in logs/metrics; Health still fails ping unless HealthWhenDegraded is "ready".
func WithDialTimeout ¶
WithDialTimeout sets the TCP dial timeout (default: valkey-go's default, typically 5s). Applied to the underlying net.Dialer.
func WithHealthWhenDegraded ¶ added in v0.0.3
WithHealthWhenDegraded sets Health() behaviour while unreachable after DegradedMode: "not_ready" (default) or "ready" (break-glass LB traffic).
func WithKeyPrefix ¶
WithKeyPrefix sets a namespace prefix applied by Key to every key this component's users build. Useful when several services or environments share one instance. The prefix is trimmed of a trailing ":"; an empty prefix keeps Key a plain ":"-join.
func WithLogger ¶
WithLogger overrides the logger used for component diagnostics. By default the component logs through the framework logs component (declared in GetDependencies); WithLogger is an explicit override for tests and embedded use and wins over the framework logger. slog.Default() remains the fallback only when neither is available.
func WithName ¶
WithName sets a custom component name, allowing multiple valkey instances in the same process. The default name is "valkey" (ComponentName). Use this when you need multiple valkey clients (e.g., cache and sessions) in one binary. Retrieve named instances with GetByName[*CFValkey](fw, "cache").
func WithPingTimeout ¶
WithPingTimeout sets how long Init waits for the connectivity ping before failing (default 5s).
func WithTLS ¶
WithTLS configures TLS from PEM file paths. Suitable for Kubernetes-mounted secrets (External Secrets). CA is optional (server verify / private CA). Client cert and key are a pair: both set for mTLS, or both empty. A half pair is rejected at apply / reload (last-good), same as postgresql.
func WithTLSInsecureSkipVerify ¶ added in v0.0.7
WithTLSInsecureSkipVerify skips server certificate verification. Use only for broken lab certs; rediss:// does not turn this on by itself.
type SourceOption ¶
type SourceOption func(*sourceOptions)
SourceOption configures the self-registered configuration source created by WithConfigSource.
func WithSourceEnvPrefix ¶
func WithSourceEnvPrefix(prefix string) SourceOption
WithSourceEnvPrefix sets the environment overlay prefix for the source (default: the uppercase source name with "-" replaced by "_", plus "_"). An empty prefix disables env overlay.
func WithSourceFormat ¶
func WithSourceFormat(f cf_configuration.Format) SourceOption
WithSourceFormat forces the file format instead of inferring it from the path extension (".yaml"/".yml" → YAML; anything else JSON).
type ValkeyConfig ¶
type ValkeyConfig struct {
Addresses []string `json:"addresses" yaml:"addresses" env:"ADDRESSES"`
Username string `json:"username,omitempty" yaml:"username,omitempty" env:"USERNAME"`
Password string `json:"password,omitempty" yaml:"password,omitempty" env:"PASSWORD" secret:"redact"`
DB int `json:"db" yaml:"db" env:"DB"`
ClientName string `json:"client_name,omitempty" yaml:"client_name,omitempty" env:"CLIENT_NAME"`
KeyPrefix string `json:"key_prefix,omitempty" yaml:"key_prefix,omitempty" env:"KEY_PREFIX"`
TLSCAFile string `json:"tls_ca_file,omitempty" yaml:"tls_ca_file,omitempty" env:"TLS_CA_FILE"`
TLSCertFile string `json:"tls_cert_file,omitempty" yaml:"tls_cert_file,omitempty" env:"TLS_CERT_FILE"`
TLSKeyFile string `json:"tls_key_file,omitempty" yaml:"tls_key_file,omitempty" env:"TLS_KEY_FILE"`
// TLS enables TLS with system roots (MinVersion 1.2) when no PEM files
// are set. ParseURL/OverlayURL set this for rediss:// and valkeys://.
// PEM files still win for custom CA / mTLS.
TLS *bool `json:"tls,omitempty" yaml:"tls,omitempty" env:"TLS"`
// TLSInsecureSkipVerify skips certificate verify. Lab/broken certs only;
// never the default. Explicit setting, not implied by rediss://.
TLSInsecureSkipVerify *bool `json:"tls_insecure_skip_verify,omitempty" yaml:"tls_insecure_skip_verify,omitempty" env:"TLS_INSECURE_SKIP_VERIFY"`
DialTimeoutSec float64 `json:"dial_timeout_sec,omitempty" yaml:"dial_timeout_sec,omitempty" env:"DIAL_TIMEOUT_SEC"`
ConnWriteTimeoutSec float64 `json:"conn_write_timeout_sec,omitempty" yaml:"conn_write_timeout_sec,omitempty" env:"CONN_WRITE_TIMEOUT_SEC"`
ConnLifetimeSec float64 `json:"conn_lifetime_sec,omitempty" yaml:"conn_lifetime_sec,omitempty" env:"CONN_LIFETIME_SEC"`
// DegradedMode — when true, a failed Init ping does not abort the process.
// The client is kept for later reconnect; metrics/logs scream. Default off
// (pointer so omitted ≠ explicit false). Off by default (hard Init).
DegradedMode *bool `json:"degraded_mode,omitempty" yaml:"degraded_mode,omitempty" env:"DEGRADED_MODE"`
// HealthWhenDegraded: "not_ready" (default) or "ready". Controls Health()
// (and thus /readyz) while the client cannot ping after a degraded Init
// or while disconnected. "ready" is break-glass: send LB traffic anyway.
HealthWhenDegraded string `json:"health_when_degraded,omitempty" yaml:"health_when_degraded,omitempty" env:"HEALTH_WHEN_DEGRADED"`
}
ValkeyConfig is the file/env-drivable connection configuration. Load it through the configuration component (caerus-framework-configuration) and pass it via WithConfig; both JSON and YAML tags are provided.
func ParseURL ¶
func ParseURL(raw string) (ValkeyConfig, error)
ParseURL parses a redis:// or valkey:// URL (or host:port) into ValkeyConfig. Examples:
redis://user:pass@127.0.0.1:6379/0 valkey://127.0.0.1:6379 127.0.0.1:6379