Documentation
¶
Index ¶
- Constants
- type CFState
- func (c *CFState) CacheGet(ctx context.Context, dst any, parts ...string) error
- func (c *CFState) CacheGetOrLoad(ctx context.Context, ttl time.Duration, load LoadFunc, parts ...string) (val []byte, shared bool, err error)
- func (c *CFState) CacheSet(ctx context.Context, v any, ttl time.Duration, parts ...string) error
- func (c *CFState) Client() valkey.Client
- func (c *CFState) CreateSession(ctx context.Context, id string, v any, ttl time.Duration) error
- func (c *CFState) GetDependencies() []string
- func (c *CFState) GetInitOrderStage() cf.Stage
- func (c *CFState) GetSession(ctx context.Context, id string, dst any) (found bool, err error)
- func (c *CFState) Health(ctx context.Context) error
- func (c *CFState) Init(ctx context.Context, fw *cf.CaerusFramework) error
- func (c *CFState) Key(parts ...string) string
- func (c *CFState) Metrics() []cf_observability.Metric
- func (c *CFState) Name() string
- func (c *CFState) OnConfigReload(source string, cfg any)
- func (c *CFState) RateLimit(ctx context.Context, key string, limit int64, window time.Duration) (RateLimitResult, error)
- func (c *CFState) RegisterConfigSources(conf any) error
- func (c *CFState) RevokeSession(ctx context.Context, id string) error
- func (c *CFState) SessionExists(ctx context.Context, id string) (bool, error)
- func (c *CFState) Shutdown(ctx context.Context) error
- func (c *CFState) TouchSession(ctx context.Context, id string, ttl time.Duration) error
- type LoadFunc
- type Option
- func WithCacheTTL(d time.Duration) Option
- func WithConfig(cfg StateConfig) Option
- func WithConfigSource(name, path string, opts ...SourceOption) Option
- func WithLogger(logger *slog.Logger) Option
- func WithName(name string) Option
- func WithSessionTTL(d time.Duration) Option
- func WithValkeyName(name string) Option
- type RateLimitResult
- type SourceOption
- type StateConfig
Constants ¶
const ( // ComponentName is the framework component name for the valkey-state // component. It is the identifier other components use in GetDependencies // to require it. ComponentName = "valkey-state" // 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 ¶
This section is empty.
Types ¶
type CFState ¶
type CFState struct {
// contains filtered or unexported fields
}
CFState is the caerus-framework-valkey-state component. It is a stateless consumer of a cf_valkey.CFValkey peer: it holds the peer component (never a client snapshot) and builds every command through the peer's live Client() and prefix-aware Key(), so reconnects and key prefixes stay consistent. It provides three keyed state services over that client:
- Sessions: opaque JSON values with a TTL and sliding-window touch.
- Cache: JSON cache-aside plus a singleflight get-or-load.
- Rate limit: atomic fixed-window counters.
func (*CFState) CacheGet ¶
CacheGet reads a JSON value at cache:<parts...> into dst. A miss returns nil and leaves dst untouched. Cache hit/miss counters are updated.
func (*CFState) CacheGetOrLoad ¶
func (c *CFState) CacheGetOrLoad(ctx context.Context, ttl time.Duration, load LoadFunc, parts ...string) (val []byte, shared bool, err error)
CacheGetOrLoad returns the bytes cached at cache:<parts...>, or runs load once for concurrent callers in this process (singleflight), then stores the result with ttl. A ttl <= 0 uses the configured default.
WARNING: singleflight is process-local only; other pods still stampede on a cold key. shared=true when this caller waited on another goroutine's load. Failure modes: a load error is returned to waiters and nothing is cached; a SET failure after a successful load returns the loaded bytes along with the error so callers can log without losing the value.
func (*CFState) CacheSet ¶
CacheSet marshals v as JSON and stores it at cache:<parts...> with the given TTL. A ttl <= 0 uses the configured default.
func (*CFState) Client ¶
Client returns the peer's live valkey client (nil before Init or after Shutdown). It follows the peer-pointer convention: the peer is re-read per use, so a client swap on the valkey side is picked up immediately.
func (*CFState) CreateSession ¶
CreateSession stores a JSON session value at session:<id> with the given TTL. A ttl <= 0 uses the configured default. The session id is chosen by the caller (typically an opaque token); it is never derived from the value.
func (*CFState) GetDependencies ¶
GetDependencies implements cf.Dependencies. The component depends on the valkey component it consumes (the actual peer name when WithValkeyName is set, the default ComponentName otherwise), logs through the framework logs component, and depends on configuration when WithConfigSource is set. Peer names are fixed at construction, so the graph is stable before Init.
func (*CFState) GetInitOrderStage ¶
GetInitOrderStage implements cf.CaerusComponent.
func (*CFState) GetSession ¶
GetSession reads the session at session:<id> and unmarshals it into dst. found is false when the session does not exist or has expired. The session TTL is not extended here; call TouchSession for a sliding window.
func (*CFState) Health ¶
Health implements cf.HealthProvider. It reports healthy while the peer's valkey client is initialized; real connectivity is owned by the valkey component's own Health (aggregated by observability's /readyz).
func (*CFState) Init ¶
Init implements cf.CaerusComponent. It resolves the valkey peer component (by name or the default "valkey"), failing fast when it is missing or not yet initialized. No connection is opened here; the peer owns its client.
func (*CFState) Key ¶
Key builds a prefix-aware key through the valkey peer. Useful for composing with caerus-framework-valkey/patterns helpers (e.g. patterns.NewMutex) against the same key space.
func (*CFState) Metrics ¶
func (c *CFState) Metrics() []cf_observability.Metric
Metrics implements cf_observability.MetricsProvider. It reports operation counters while the peer's client is initialized; before Init or after Shutdown it returns nil, so the observability component skips it (lazy pickup). Counters are cumulative for the process lifetime and are emitted (zero until first fired) so the series are always present.
func (*CFState) Name ¶
Name implements cf.CaerusComponent. Returns the custom name set via WithName, or the default ComponentName ("valkey-state") if no custom name was set.
func (*CFState) OnConfigReload ¶
OnConfigReload implements cf.ConfigReloader. It re-reads the behavior tunables (session/cache TTLs) from the bound configuration source. No connection is rebuilt: the valkey peer owns client rotation, and this component is stateless over it.
func (*CFState) RateLimit ¶
func (c *CFState) RateLimit(ctx context.Context, key string, limit int64, window time.Duration) (RateLimitResult, error)
RateLimit is an atomic fixed-window rate limiter. Each call increments the counter at rl:<key> and reports whether the resulting count is within limit for the window. The counter and its expiry are set atomically (Lua), so a key never leaks without a TTL and concurrent first calls cannot race the expiry.
The key is caller-chosen (e.g. "login:user@example.com" or "ip:1.2.3.4"). A transport error is returned to the caller: fail-open/fail-closed policy belongs to the app (auth-api keeps its "valkey down → allow request" choice).
func (*CFState) 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) with the configuration component. No-op when no source is bound.
func (*CFState) RevokeSession ¶
RevokeSession deletes session:<id>. Deleting a missing session is a no-op success.
func (*CFState) SessionExists ¶
SessionExists reports whether session:<id> exists and is unexpired.
type LoadFunc ¶
LoadFunc fetches the canonical value on a cache miss. Called at most once per key per in-flight wave inside this process.
type Option ¶
type Option func(*options)
Option configures the state component at construction time.
func WithCacheTTL ¶
WithCacheTTL sets the default cache TTL used when a cache call leaves ttl at zero (default 5m).
func WithConfig ¶
func WithConfig(cfg StateConfig) Option
WithConfig sets a static 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, the default EnvPrefix and its Owner (Name(), so named instances reload correctly). main only points the instance at where the config lives.
cf_valkey_state.New(cf_valkey_state.WithConfigSource("state", "config/state.json"))
cf_valkey_state.New(cf_valkey_state.WithConfigSource("sess", "/etc/app/sess.yaml",
cf_valkey_state.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 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 state instances in the same process. The default name is "valkey-state" (ComponentName). Retrieve named instances with GetByName[*CFState](fw, "sessions").
func WithSessionTTL ¶
WithSessionTTL sets the default session TTL used when a session call leaves ttl at zero (default 24h).
func WithValkeyName ¶
WithValkeyName binds the state component to a valkey component with the given name (WithName on the valkey side). The default is the valkey ComponentName ("valkey").
type RateLimitResult ¶
type RateLimitResult struct {
// Allowed is true when Count does not exceed the limit for the window.
Allowed bool
// Count is the incremented request count within the current window.
Count int64
// ResetIn is the time remaining until the window resets (for Retry-After).
ResetIn time.Duration
}
RateLimitResult reports the outcome of a RateLimit check.
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 StateConfig ¶
type StateConfig struct {
// SessionTTLSec is the default session TTL in seconds when a call leaves
// ttl at zero (default 24h).
SessionTTLSec int64 `json:"session_ttl_sec,omitempty" yaml:"session_ttl_sec,omitempty" env:"SESSION_TTL_SEC"`
// CacheTTLSec is the default cache TTL in seconds when a call leaves ttl
// at zero (default 5m).
CacheTTLSec int64 `json:"cache_ttl_sec,omitempty" yaml:"cache_ttl_sec,omitempty" env:"CACHE_TTL_SEC"`
}
StateConfig is the file/env-drivable behavior configuration. Load it through the configuration component (caerus-framework-configuration) and pass it via WithConfigSource; both JSON and YAML tags are provided.