Documentation
¶
Index ¶
- Constants
- Variables
- func ContextNamespace(ctx context.Context) string
- func ContextWithManager(ctx context.Context, mgr Manager) context.Context
- func ContextWithNamespace(ctx context.Context, namespace string) context.Context
- func EntryID(v Value) string
- func GetExpiresAt(v Value) time.Time
- func IsAliasExists(err error) bool
- func IsBulkWritePartial(err error) bool
- func IsExpired(v Value) bool
- func IsInvalidCursor(err error) bool
- func IsInvalidKey(err error) bool
- func IsKeyExists(err error) bool
- func IsNamespaceFull(err error) bool
- func IsNotFound(err error) bool
- func IsSystemNamespace(namespace string) bool
- func IsTypeMismatch(err error) bool
- func IsUnsupportedCodec(err error) bool
- func IsVersionNotFound(err error) bool
- func IsVersioningNotSupported(err error) bool
- func IsWatchUnhealthy(err error) bool
- func MatchesWatchFilter(event ChangeEvent, filter WatchFilter) bool
- func Set(ctx context.Context, key string, value any, opts ...SetOption) error
- func ValidateKey(key string) error
- func ValidateNamespace(namespace string) error
- func WrapStoreError(op, backend, key string, err error) error
- type AliasExistsError
- type AliasManager
- type AliasStore
- type BulkStore
- type BulkWriteError
- type Cache
- type CacheStats
- type ChangeEvent
- type ChangeType
- type CodecValidator
- type Config
- type Filter
- type FilterBuilder
- type HealthChecker
- type InvalidKeyError
- type KeyExistsError
- type KeyNotFoundError
- type Manager
- type ManagerObserver
- type Metadata
- type NamespaceFullError
- type NamespaceLister
- type Option
- func WithAlias(alias, target string) Option
- func WithAliases(target string, aliases ...string) Option
- func WithCache(c Cache) Option
- func WithCodec(c codec.Codec) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMaxKeysPerNamespace(n int) Option
- func WithMemoryCacheTTL(d time.Duration) Option
- func WithStore(store Store) Option
- func WithWatchBackoffFactor(f float64) Option
- func WithWatchInitialBackoff(d time.Duration) Option
- func WithWatchMaxBackoff(d time.Duration) Option
- type Page
- type Reader
- type Secret
- func (s *Secret) Bytes() []byte
- func (s *Secret) Clone() *Secret
- func (s *Secret) Equal(other *Secret) bool
- func (s *Secret) GoString() string
- func (s *Secret) IsZero() bool
- func (s *Secret) Lock() error
- func (s *Secret) LogValue() slog.Value
- func (s *Secret) MarshalBSONValue() (byte, []byte, error)
- func (s *Secret) MarshalJSON() ([]byte, error)
- func (s *Secret) MarshalText() ([]byte, error)
- func (s *Secret) Scan(value any) error
- func (s *Secret) String() string
- func (s *Secret) Unlock() error
- func (s *Secret) UnmarshalBSONValue(typ byte, data []byte) error
- func (s *Secret) UnmarshalText(b []byte) error
- func (s *Secret) Value() (driver.Value, error)
- func (s *Secret) Wipe()
- type SetOption
- type StatsProvider
- type Store
- type StoreError
- type StoreStats
- type Type
- type TypeMismatchError
- type UnsupportedCodecError
- type Value
- func CloneValue(src Value, newRaw any, opts ...ValueOption) Value
- func Get(ctx context.Context, key string) (Value, error)
- func MarkStale(v Value) Value
- func NewRawValue(data []byte, codecName string, opts ...ValueOption) Value
- func NewSecretValue(s *Secret, opts ...ValueOption) Value
- func NewValue(data any, opts ...ValueOption) Value
- func NewValueFromBytes(ctx context.Context, data []byte, codecName string, opts ...ValueOption) (Value, error)
- type ValueOption
- func WithValueCodec(c codec.Codec) ValueOption
- func WithValueEntryID(id string) ValueOption
- func WithValueExpiresAt(t time.Time) ValueOption
- func WithValueMetadata(version int64, createdAt, updatedAt time.Time) ValueOption
- func WithValueStale(stale bool) ValueOption
- func WithValueType(t Type) ValueOption
- func WithValueWriteMode(mode WriteMode) ValueOption
- type VersionFilter
- type VersionFilterBuilder
- type VersionNotFoundError
- type VersionPage
- type VersionedReader
- type VersionedStore
- type WatchFilter
- type WatchHealthError
- type WatchStatus
- type WriteMode
- type WriteModer
- type Writer
Examples ¶
Constants ¶
const DefaultNamespace = ""
DefaultNamespace is the default namespace (empty string). Use this when you don't need namespace separation.
const SystemNamespacePrefix = "internal:"
SystemNamespacePrefix is the reserved prefix for internal system namespaces. Namespaces starting with this prefix are used by infrastructure components (e.g., key rotation, service discovery) and should not be written by clients.
Variables ¶
var ( // ErrNotFound is returned when a config key does not exist. ErrNotFound = errors.New("config: key not found") // ErrTypeMismatch is returned when attempting to convert a value to an incompatible type. ErrTypeMismatch = errors.New("config: type mismatch") // ErrInvalidKey is returned when a config key is empty or malformed. ErrInvalidKey = errors.New("config: invalid key") // ErrInvalidNamespace is returned when a namespace is malformed. ErrInvalidNamespace = errors.New("config: invalid namespace") // ErrInvalidValue is returned when a value cannot be stored. ErrInvalidValue = errors.New("config: invalid value") // ErrStoreNotConnected is returned when operating on a disconnected store. ErrStoreNotConnected = errors.New("config: store not connected") // ErrStoreClosed is returned when operating on a closed store. ErrStoreClosed = errors.New("config: store closed") // ErrWatchNotSupported is returned when the store does not support watching. ErrWatchNotSupported = errors.New("config: watch not supported") // ErrManagerClosed is returned when operating on a closed manager. ErrManagerClosed = errors.New("config: manager closed") // ErrCodecNotFound is returned when a codec is not registered. ErrCodecNotFound = errors.New("config: codec not found") // ErrReadOnly is returned when attempting to write to a read-only store. ErrReadOnly = errors.New("config: store is read-only") // ErrKeyExists is returned when attempting to create a key that already exists. ErrKeyExists = errors.New("config: key already exists") // ErrUnsupportedCodec is returned when a store does not support the requested codec. ErrUnsupportedCodec = errors.New("config: unsupported codec") // ErrVersionNotFound is returned when a specific version of a key does not exist. ErrVersionNotFound = errors.New("config: version not found") // ErrVersioningNotSupported is returned when the store does not support versioning. ErrVersioningNotSupported = errors.New("config: versioning not supported") // ErrNamespaceFull is returned when a namespace has reached its maximum key count. ErrNamespaceFull = errors.New("config: namespace key limit exceeded") // ErrAliasExists is returned when creating an alias that conflicts with an // existing alias or an existing configuration key. ErrAliasExists = errors.New("config: alias already exists") // ErrAliasSelf is returned when an alias points to itself. ErrAliasSelf = errors.New("config: alias cannot reference itself") // ErrAliasChain is returned when an alias target is itself an alias, // which would create a chain. Aliases are single-hop only. ErrAliasChain = errors.New("config: alias chain not allowed") // ErrInvalidCursor indicates a pagination cursor is malformed, expired, // originated from a different store backend, or uses a protocol version // the current backend does not understand. Returned by paginated APIs // that use opaque cursors, such as [NamespaceLister.ListNamespaces]. // Callers should treat this as an invalid-argument condition and either // retry from the first page (empty cursor) or surface it to the user. // See the cursor envelope in package internal/cursor for the wire-level // failure modes that produce this sentinel. ErrInvalidCursor = errors.New("config: invalid cursor") )
Sentinel errors for config operations. Use errors.Is() to check for these errors as they may be wrapped.
var ErrBulkWritePartial = errors.New("config: bulk write partially failed")
ErrBulkWritePartial is returned when a bulk write operation partially fails.
var ErrWatchUnhealthy = errors.New("config: watch unhealthy")
ErrWatchUnhealthy is returned by Health() when watch has consecutive failures.
Functions ¶
func ContextNamespace ¶
ContextNamespace retrieves the namespace from context. Returns empty string if no namespace is set.
func ContextWithManager ¶
ContextWithManager adds a Manager to the context. This allows handlers to access configuration without explicit dependency injection.
Example ¶
package main
import (
"context"
"fmt"
"github.com/rbaliyan/config"
"github.com/rbaliyan/config/memory"
)
func main() {
ctx := context.Background()
mgr, _ := config.New(config.WithStore(memory.NewStore()))
_ = mgr.Connect(ctx)
defer mgr.Close(ctx)
// Add manager and namespace to context
ctx = config.ContextWithManager(ctx, mgr)
ctx = config.ContextWithNamespace(ctx, "myapp")
// Set and get via context convenience functions
_ = config.Set(ctx, "greeting", "hello")
val, _ := config.Get(ctx, "greeting")
s, _ := val.String()
fmt.Println(s)
}
Output: hello
func ContextWithNamespace ¶
ContextWithNamespace adds a namespace to the context. Operations will use this namespace.
func EntryID ¶ added in v0.6.3
EntryID returns the storage-level identifier associated with v, if any. The identifier is an implementation detail used by Store backends for pagination and update paths; it is empty for values created via NewValue before they have been written.
func GetExpiresAt ¶ added in v0.6.5
GetExpiresAt returns the expiry time stored in v's metadata, or zero if none.
func IsAliasExists ¶ added in v0.5.5
IsAliasExists checks if an error indicates an alias already exists.
func IsBulkWritePartial ¶
IsBulkWritePartial checks if an error indicates a partial bulk write failure. Use errors.As() to get the BulkWriteError for details about which keys failed.
func IsExpired ¶ added in v0.6.5
IsExpired reports whether v has a non-zero expiry time that is in the past.
func IsInvalidCursor ¶ added in v0.7.1
IsInvalidCursor checks if an error indicates a malformed or backend-incompatible pagination cursor. This is the canonical predicate for handling pagination errors from NamespaceLister.ListNamespaces and from cursor decoding in package internal/cursor.
func IsInvalidKey ¶
IsInvalidKey checks if an error indicates an invalid key.
func IsKeyExists ¶
IsKeyExists checks if an error indicates a key already exists.
func IsNamespaceFull ¶ added in v0.5.4
IsNamespaceFull checks if an error indicates a namespace has reached its key limit.
func IsNotFound ¶
IsNotFound checks if an error indicates a missing key.
func IsSystemNamespace ¶ added in v0.5.0
IsSystemNamespace returns true if the namespace is reserved for internal use. A system namespace must start with the "internal:" prefix.
func IsTypeMismatch ¶
IsTypeMismatch checks if an error indicates a type mismatch.
func IsUnsupportedCodec ¶ added in v0.4.2
IsUnsupportedCodec checks if an error indicates an unsupported codec.
func IsVersionNotFound ¶ added in v0.5.3
IsVersionNotFound checks if an error indicates a missing version.
func IsVersioningNotSupported ¶ added in v0.5.3
IsVersioningNotSupported checks if an error indicates versioning is not supported.
func IsWatchUnhealthy ¶
IsWatchUnhealthy checks if an error indicates watch connection issues.
func MatchesWatchFilter ¶ added in v0.5.2
func MatchesWatchFilter(event ChangeEvent, filter WatchFilter) bool
MatchesWatchFilter reports whether event satisfies filter. Store implementations use this to decide which watchers receive an event. Alias change events always match (they are global and affect all namespaces).
func Set ¶
Set is a convenience function that sets a value using the Manager from context. Returns ErrManagerClosed if no manager is in context. Uses the namespace from context, or "" (default) if not set.
func ValidateKey ¶
ValidateKey validates a configuration key. Keys must:
- Not be empty
- Contain only alphanumeric characters, underscores, dashes, dots, and slashes
- Not contain path traversal sequences (..)
- Not start or end with a slash
Returns an InvalidKeyError if the key is invalid.
func ValidateNamespace ¶
ValidateNamespace validates a namespace name. Empty namespaces are allowed (represents the default namespace). Returns ErrInvalidNamespace if the namespace contains invalid characters.
func WrapStoreError ¶
WrapStoreError creates a StoreError from a backend error.
Types ¶
type AliasExistsError ¶ added in v0.5.5
type AliasExistsError struct {
Alias string
Reason string // e.g. "alias already registered" or "key exists in namespace \"prod\""
}
AliasExistsError provides details about an alias that already exists.
func (*AliasExistsError) Error ¶ added in v0.5.5
func (e *AliasExistsError) Error() string
func (*AliasExistsError) Unwrap ¶ added in v0.5.5
func (e *AliasExistsError) Unwrap() error
type AliasManager ¶ added in v0.5.5
type AliasManager interface {
// SetAlias creates a new alias mapping from alias to target.
// When the store implements [AliasStore], the alias is persisted and
// propagated to other instances via Watch.
//
// Returns [ErrAliasExists] if the alias key is already registered as an
// alias or exists as a configuration entry.
// Returns [ErrAliasSelf] if alias equals target.
// Returns [ErrAliasChain] if the mapping would create a chain.
SetAlias(ctx context.Context, alias, target string) error
// RemoveAlias removes an alias.
// Returns [ErrNotFound] if the alias does not exist.
RemoveAlias(ctx context.Context, alias string) error
// ResolveAlias returns the canonical key for the given key.
// If the key is not an alias, it is returned unchanged.
ResolveAlias(key string) string
// Aliases returns a snapshot of all registered aliases (alias → target).
Aliases() map[string]string
}
AliasManager provides runtime management of key aliases.
Aliases allow transparent key migration by mapping old key names to new canonical keys. All operations (Get, Set, Delete) automatically resolve aliases to their target keys.
When the underlying store implements AliasStore, aliases are persisted and propagated to all connected Manager instances via Watch. When the store does not implement AliasStore, aliases are held in memory only (useful for testing).
Aliases are global (not per-namespace) and single-hop: if A is aliased to B, accessing A resolves to B. Chain aliases (A→B→C) are not supported; update A's target directly if the canonical key changes.
Use type assertion on Manager:
if am, ok := mgr.(config.AliasManager); ok {
am.SetAlias(ctx, "old/key", "new/key")
}
type AliasStore ¶ added in v0.5.5
type AliasStore interface {
// SetAlias creates a new alias mapping from alias to target.
// Returns the stored Value (target key name with metadata).
// Returns [ErrAliasExists] if the alias key is already registered as an
// alias or already exists as a configuration entry in any namespace.
SetAlias(ctx context.Context, alias, target string) (Value, error)
// DeleteAlias removes an alias.
// Returns [ErrNotFound] if the alias does not exist.
DeleteAlias(ctx context.Context, alias string) error
// GetAlias retrieves the target for a specific alias.
// Returns [ErrNotFound] if the alias does not exist.
GetAlias(ctx context.Context, alias string) (Value, error)
// ListAliases returns all registered aliases as a map of alias → Value.
// The Value for each entry contains the target key name as a string.
ListAliases(ctx context.Context) (map[string]Value, error)
}
AliasStore is an optional interface for stores that support persistent key aliases.
Aliases provide transparent key migration by mapping old key names to new canonical keys. They occupy the same key space as configuration entries: a key that exists as a config entry cannot be used as an alias, and vice versa.
Alias values reuse the Value interface, where the underlying data is the target key name (a string). The returned Value carries metadata such as version and timestamps.
Stores that implement AliasStore emit ChangeTypeAliasSet and ChangeTypeAliasDelete events through the Watch channel so that all connected Manager instances stay in sync.
Use type assertion to check if a store supports aliases:
if as, ok := store.(config.AliasStore); ok {
val, err := as.SetAlias(ctx, "db.host", "database/host")
}
type BulkStore ¶
type BulkStore interface {
// GetMany retrieves multiple values in a single operation.
// Returns a map of key -> Value. Missing keys are not included in the result.
GetMany(ctx context.Context, namespace string, keys []string) (map[string]Value, error)
// SetMany creates or updates multiple values in a single operation.
// SetMany always uses upsert semantics regardless of any WriteMode set on
// individual values. Use individual Set calls for conditional (create-only
// or update-only) writes.
SetMany(ctx context.Context, namespace string, values map[string]Value) error
// DeleteMany removes multiple values in a single operation.
// Returns the number of entries actually deleted.
DeleteMany(ctx context.Context, namespace string, keys []string) (int64, error)
}
BulkStore is an optional interface for stores that support batch operations. Implementing this interface allows efficient bulk reads and writes.
type BulkWriteError ¶
type BulkWriteError struct {
// Errors maps keys to their specific errors. Only failed keys are included.
Errors map[string]error
// Succeeded contains keys that were written successfully.
Succeeded []string
}
BulkWriteError provides details about partial failures in bulk operations. Use KeyErrors() to see which keys failed and which succeeded.
func (*BulkWriteError) Error ¶
func (e *BulkWriteError) Error() string
func (*BulkWriteError) FailedKeys ¶
func (e *BulkWriteError) FailedKeys() []string
FailedKeys returns the list of keys that failed.
func (*BulkWriteError) KeyErrors ¶
func (e *BulkWriteError) KeyErrors() map[string]error
KeyErrors returns the map of key -> error for failed keys.
func (*BulkWriteError) Unwrap ¶
func (e *BulkWriteError) Unwrap() error
type Cache ¶ added in v0.6.4
type Cache interface {
// Get retrieves a cached value.
// Returns ErrNotFound if not in cache.
Get(ctx context.Context, namespace, key string) (Value, error)
// Set stores a value in the cache.
Set(ctx context.Context, namespace, key string, value Value) error
// Delete removes an entry from the cache.
Delete(ctx context.Context, namespace, key string) error
// Stats returns cache statistics.
Stats() CacheStats
}
Cache defines the interface for configuration value caching.
The cache provides fast local access to configuration values and serves as a resilience layer. If the backend store becomes unavailable, the application can continue serving cached values.
The cache is automatically invalidated via the store's Watch mechanism (e.g., MongoDB Change Streams, PostgreSQL LISTEN/NOTIFY).
The default implementation is an in-process LRU (see newMemoryCache). For shared caching across multiple application instances, supply a distributed implementation (e.g. redis.NewCache) via config.WithCache.
func NewMemoryCache ¶ added in v0.6.6
NewMemoryCache returns a Cache backed by a bounded in-memory LRU. capacity is the maximum number of entries (0 uses the default of 10000). ttl is the per-entry time-to-live (0 means no TTL — entries expire only under LRU pressure).
Suitable as the inner cache for configcrypto.NewEncryptedCache, or for any Store wrapper that needs a local write-back layer without external dependencies.
type CacheStats ¶
type CacheStats struct {
// Hits is the number of successful cache lookups.
Hits int64 `json:"hits"`
// Misses is the number of cache lookups that found no entry.
Misses int64 `json:"misses"`
// Size is the current number of entries in the cache.
Size int64 `json:"size"`
// Capacity is the maximum number of entries (0 = unbounded).
Capacity int64 `json:"capacity"`
// Evictions is the number of entries evicted due to capacity limits.
Evictions int64 `json:"evictions"`
}
CacheStats contains cache statistics.
func (*CacheStats) HitRate ¶
func (s *CacheStats) HitRate() float64
HitRate returns the cache hit rate as a percentage (0.0 to 1.0). Returns 0 if there have been no lookups.
type ChangeEvent ¶
type ChangeEvent struct {
// Type indicates the kind of change.
Type ChangeType
// Namespace is the namespace of the changed key.
Namespace string
// Key is the key that changed.
Key string
// Value is the new value (nil for Delete events).
Value Value
// Timestamp is when the change occurred.
Timestamp time.Time
}
ChangeEvent represents a configuration change notification.
type ChangeType ¶
type ChangeType int
ChangeType represents the type of configuration change.
const ( // ChangeTypeSet indicates a create or update operation. ChangeTypeSet ChangeType = iota // ChangeTypeDelete indicates a delete operation. ChangeTypeDelete // ChangeTypeAliasSet indicates an alias was created. ChangeTypeAliasSet // ChangeTypeAliasDelete indicates an alias was removed. ChangeTypeAliasDelete )
func (ChangeType) IsAliasChange ¶ added in v0.5.5
func (c ChangeType) IsAliasChange() bool
IsAliasChange reports whether the change type is an alias event.
func (ChangeType) String ¶
func (c ChangeType) String() string
String returns the string representation of the change type.
type CodecValidator ¶ added in v0.4.2
CodecValidator is an optional interface for stores that restrict supported codecs. Stores that do not implement this accept all codecs (backward compatible).
type Filter ¶
type Filter interface {
// Keys returns specific keys to retrieve (mutually exclusive with Prefix).
Keys() []string
// Prefix returns the prefix to match (mutually exclusive with Keys).
Prefix() string
// Limit returns the maximum number of results (0 = no limit).
Limit() int
// Cursor returns the pagination cursor (entry ID) for continuing from a previous result.
Cursor() string
}
Filter defines criteria for listing configuration entries. Use NewFilter() to create a FilterBuilder and construct filters.
Filters support two mutually exclusive modes:
- Keys mode: retrieve specific keys by exact match
- Prefix mode: retrieve all keys matching a prefix
Example:
// Get specific keys
filter := config.NewFilter().WithKeys("db/host", "db/port").Build()
// Get all keys with prefix
filter := config.NewFilter().WithPrefix("db/").WithLimit(100).Build()
// Paginate with cursor
page, _ := cfg.Find(ctx, config.NewFilter().WithPrefix("").WithLimit(50).Build())
nextPage, _ := cfg.Find(ctx, config.NewFilter().WithPrefix("").WithLimit(50).WithCursor(page.NextCursor()).Build())
type FilterBuilder ¶
type FilterBuilder struct {
// contains filtered or unexported fields
}
FilterBuilder builds Filter instances using a fluent API.
func (*FilterBuilder) WithCursor ¶
func (b *FilterBuilder) WithCursor(cursor string) *FilterBuilder
WithCursor sets the pagination cursor for continuing from a previous result.
func (*FilterBuilder) WithKeys ¶
func (b *FilterBuilder) WithKeys(keys ...string) *FilterBuilder
WithKeys sets specific keys to retrieve. Cannot be used with WithPrefix - calling this clears any prefix.
func (*FilterBuilder) WithLimit ¶
func (b *FilterBuilder) WithLimit(limit int) *FilterBuilder
WithLimit sets the maximum number of results.
func (*FilterBuilder) WithPrefix ¶
func (b *FilterBuilder) WithPrefix(prefix string) *FilterBuilder
WithPrefix sets a prefix to match keys. Cannot be used with WithKeys - calling this clears any keys.
type HealthChecker ¶
type HealthChecker interface {
// Health performs a health check on the store.
// Returns nil if healthy, or an error describing the issue.
Health(ctx context.Context) error
}
HealthChecker is an optional interface for stores that support health checks.
type InvalidKeyError ¶
InvalidKeyError provides details about an invalid key.
func (*InvalidKeyError) Error ¶
func (e *InvalidKeyError) Error() string
func (*InvalidKeyError) Unwrap ¶
func (e *InvalidKeyError) Unwrap() error
type KeyExistsError ¶
KeyExistsError provides details about a key that already exists.
func (*KeyExistsError) Error ¶
func (e *KeyExistsError) Error() string
func (*KeyExistsError) Unwrap ¶
func (e *KeyExistsError) Unwrap() error
type KeyNotFoundError ¶
KeyNotFoundError provides details about a missing key.
func (*KeyNotFoundError) Error ¶
func (e *KeyNotFoundError) Error() string
func (*KeyNotFoundError) Unwrap ¶
func (e *KeyNotFoundError) Unwrap() error
type Manager ¶
type Manager interface {
// Connect establishes connection to the backend and starts watching.
// Must be called before any other operations.
Connect(ctx context.Context) error
// Close stops watching and releases resources.
Close(ctx context.Context) error
// Namespace returns a Config for the specified namespace.
// Use "" for the default namespace.
Namespace(name string) Config
// Refresh forces a cache refresh for a specific key.
Refresh(ctx context.Context, namespace, key string) error
// Health performs a health check on the manager and underlying store.
// Returns nil if healthy, or an error describing the issue.
// Includes watch status - returns an error if watch has consecutive failures.
Health(ctx context.Context) error
}
Manager manages configuration across namespaces.
The Manager wraps a Store with caching and automatic cache invalidation. It provides access to namespaced configuration via the Namespace method.
Example:
// Create manager
mgr := config.New(
config.WithStore(memory.NewStore()),
)
// Connect to backend
if err := mgr.Connect(ctx); err != nil {
return err
}
defer mgr.Close(ctx)
// Get configuration for a namespace (use "" for default)
prodConfig := mgr.Namespace("production")
// Use Reader interface in application code
val, err := prodConfig.Get(ctx, "app/database/timeout")
if err != nil {
return err
}
var timeout int
if err := val.Unmarshal(&timeout); err != nil {
return err
}
// Use Writer interface for management
if err := prodConfig.Set(ctx, "app/database/timeout", 30); err != nil {
return err
}
func ContextManager ¶
ContextManager retrieves the Manager from context. Returns nil if no manager is set.
func New ¶
New creates a new configuration Manager.
The manager is created but not connected. Call Connect() before use. This follows the New/Connect split pattern for better error handling.
The manager always maintains an internal cache for resilience. If the backend store becomes temporarily unavailable, cached values will continue to be served. This ensures your application keeps working during database outages.
Returns an error if cache initialization fails.
Example ¶
package main
import (
"context"
"fmt"
"github.com/rbaliyan/config"
"github.com/rbaliyan/config/memory"
)
func main() {
ctx := context.Background()
// Create a manager with an in-memory store
mgr, err := config.New(config.WithStore(memory.NewStore()))
if err != nil {
fmt.Println("Error:", err)
return
}
// Connect to the backend
if err := mgr.Connect(ctx); err != nil {
fmt.Println("Error:", err)
return
}
defer mgr.Close(ctx)
// Get a namespaced config and set a value
cfg := mgr.Namespace("production")
if err := cfg.Set(ctx, "app/timeout", 30); err != nil {
fmt.Println("Error:", err)
return
}
// Read the value back
val, err := cfg.Get(ctx, "app/timeout")
if err != nil {
fmt.Println("Error:", err)
return
}
i, _ := val.Int64()
fmt.Println("timeout:", i)
}
Output: timeout: 30
type ManagerObserver ¶
type ManagerObserver interface {
// CacheStats returns statistics about the internal cache.
CacheStats() CacheStats
// WatchStatus returns the current status of the watch connection.
WatchStatus() WatchStatus
}
ManagerObserver provides observability into the Manager's internal state. Use a type assertion to access these methods:
if obs, ok := mgr.(config.ManagerObserver); ok {
stats := obs.CacheStats()
status := obs.WatchStatus()
}
type Metadata ¶
type Metadata interface {
// Version returns the version number of the value.
Version() int64
// CreatedAt returns when the value was first created.
CreatedAt() time.Time
// UpdatedAt returns when the value was last modified.
UpdatedAt() time.Time
// IsStale returns true if this value was served from cache due to a store error.
// When true, the value may be outdated. Applications can use this to:
// - Log warnings about stale data
// - Show degraded UI indicators
// - Trigger background refresh
IsStale() bool
// ExpiresAt returns the absolute time at which this value expires.
// A zero time means no TTL (the value never expires).
ExpiresAt() time.Time
}
Metadata provides version and timestamp information for stored values.
type NamespaceFullError ¶ added in v0.5.4
NamespaceFullError provides details about a namespace that has reached its key limit.
func (*NamespaceFullError) Error ¶ added in v0.5.4
func (e *NamespaceFullError) Error() string
func (*NamespaceFullError) Unwrap ¶ added in v0.5.4
func (e *NamespaceFullError) Unwrap() error
type NamespaceLister ¶ added in v0.7.1
type NamespaceLister interface {
// ListNamespaces returns a page of namespace names. See the
// [NamespaceLister] interface godoc for the full contract on ordering,
// filtering, limits, cursor opacity, concurrency, and which namespaces
// are eligible for inclusion (implementation-defined).
//
// nextCursor is empty iff there are no further pages.
ListNamespaces(ctx context.Context, prefix string, limit int, cursor string) (names []string, nextCursor string, err error)
}
NamespaceLister is an optional interface a Store may implement to expose efficient, server-side paginated enumeration of namespace names.
Stores that don't implement this can still be enumerated via StatsProvider, but every page recomputes the full stats payload — an O(namespaces) cost paid per page request. Paginating N namespaces at P entries per page performs ⌈N/P⌉ full-store scans for one logical enumeration. Do not rely on the StatsProvider fallback for backends expected to exceed a few hundred namespaces; implement NamespaceLister directly using the backend's natural pagination primitive (SQL DISTINCT ... ORDER BY ... LIMIT/OFFSET, MongoDB aggregation, in-memory sorted index, Redis ZRANGEBYLEX, etc.).
Contract ¶
- Sort order: ascending, lexicographic byte-wise on UTF-8; stable across calls.
- Prefix filter: applied before the cursor cut; results are sorted byte-wise. Empty prefix matches all namespaces.
- Limit: honored as a maximum. Implementations MAY cap to a backend-specific ceiling but MUST NOT return more than `limit` entries. Callers SHOULD pass `limit > 0`. Backends MAY treat `limit <= 0` as "apply backend default" rather than erroring, but MUST document the choice in their godoc and MUST NOT panic.
- Cursor opacity: cursors are opaque to callers. They are NOT portable across backends; implementations are free to choose offsets, last-seen names, B-tree positions, etc. Backend authors should use the config/internal/cursor envelope to tag cursors with a backend identifier so a swapped store can detect foreign cursors.
- First page: an empty cursor string signals "start at the beginning." Backends MUST NOT pass the empty string to config/internal/cursor.Unmarshal (which rejects empty input); decode only when the caller supplied a non-empty cursor.
- Stability under concurrent writes: best-effort. A namespace added or removed mid-pagination may be skipped or repeated across pages, but never duplicated within a single page.
- Empty namespaces: namespace inclusion when no entries currently exist under it is implementation-defined; backends document their choice (most reflect current state and omit empties).
- Watch events: namespace appearance and disappearance are implicit side effects of Store.Set and Store.Delete on the contained keys. No dedicated ChangeEvent is emitted for namespace lifecycle.
- Invalid cursor: must return an error that wraps ErrInvalidCursor (use IsInvalidCursor to check). Causes include malformed encoding, expired tokens, foreign-backend cursors, and protocol-version mismatch.
Implementations ¶
Implemented by the memory, sqlite, postgres, and mongodb stores in this module. Redis is intentionally excluded; redis callers fall back to the StatsProvider path in the service layer. Each backend uses a distinct cursor envelope tag so a cursor produced by one store and replayed against another returns ErrInvalidCursor. Wrapper stores (otel, multi, transform, expand) do not currently forward this interface — a type assertion against a wrapped store returns `ok == false`, and callers should unwrap to the underlying store if they need direct NamespaceLister access.
Use type assertion to check if a store supports namespace enumeration:
if nl, ok := store.(config.NamespaceLister); ok {
cursor := ""
for {
names, next, err := nl.ListNamespaces(ctx, "prod-", 50, cursor)
if err != nil {
return err
}
for _, ns := range names {
handle(ns)
}
if next == "" {
break
}
cursor = next
}
}
type Option ¶
type Option func(*managerOptions)
Option configures the Manager.
func WithAlias ¶ added in v0.5.5
WithAlias registers a key alias that maps alias to target. When any operation (Get, Set, Delete) uses the alias key, it is transparently resolved to the target key. This enables key migration without changing application code that references old key names.
Aliases are global (not per-namespace) and single-hop. Returns an error from New() if the alias is invalid.
Example:
mgr, err := config.New(
config.WithStore(store),
config.WithAlias("db.host", "database/host"),
)
func WithAliases ¶ added in v0.5.5
WithAliases maps one or more alias keys to a single canonical target key. This is convenient when migrating multiple old key names to one new key. See WithAlias for details.
Example:
mgr, err := config.New(
config.WithStore(store),
config.WithAliases("database/host", "db.host", "db-host", "legacy/db/host"),
)
func WithCache ¶ added in v0.6.4
WithCache sets a custom cache implementation for the Manager. When set, the provided cache is used instead of the default in-memory LRU. Use this to share cache state across instances with a distributed backend such as Redis:
mgr, err := config.New(
config.WithStore(pgStore),
config.WithCache(redis.NewCache(redisClient,
redis.WithCacheTTL(5*time.Minute),
)),
)
func WithCodec ¶
WithCodec sets the default codec for encoding/decoding values. Default is JSON if not specified.
func WithMaxKeysPerNamespace ¶ added in v0.5.4
WithMaxKeysPerNamespace sets the maximum number of keys allowed per namespace. Set operations that would exceed this limit return ErrNamespaceFull. Only enforced on creates (not updates to existing keys). 0 means unlimited (default).
func WithMemoryCacheTTL ¶ added in v0.6.5
WithMemoryCacheTTL sets the TTL for entries in the default in-memory LRU cache. Entries older than d are automatically evicted. Use 0 (the default) to disable expiry and rely solely on LRU eviction. Has no effect when WithCache is also set.
func WithStore ¶
WithStore sets the configuration store backend. This is required - the manager will fail to connect without a store.
func WithWatchBackoffFactor ¶ added in v0.1.12
WithWatchBackoffFactor sets the multiplier applied to backoff after each watch failure. Default: 2.0.
func WithWatchInitialBackoff ¶ added in v0.1.12
WithWatchInitialBackoff sets the initial wait time between watch reconnection attempts. Default: 100ms.
func WithWatchMaxBackoff ¶ added in v0.1.12
WithWatchMaxBackoff sets the maximum wait time between watch reconnection attempts. Default: 30s.
type Page ¶
type Page interface {
// Results returns the values in this page as a map of key -> Value.
Results() map[string]Value
// NextCursor returns the cursor for fetching the next page.
// This is typically the last key in the results.
NextCursor() string
// Limit returns the actual limit used by the server.
// The server may adjust the requested limit. Clients should check
// len(Results()) < Limit() to determine if there are more results.
Limit() int
}
Page represents a page of results from a Find operation. It provides access to the results and pagination information.
Example usage for pagination:
limit := 100
filter := config.NewFilter().WithPrefix("app/").WithLimit(limit).Build()
for {
page, err := cfg.Find(ctx, filter)
if err != nil {
return err
}
for key, val := range page.Results() {
// Process each entry
}
// No more results if returned count < limit
if len(page.Results()) < page.Limit() {
break
}
filter = config.NewFilter().WithPrefix("app/").WithLimit(limit).WithCursor(page.NextCursor()).Build()
}
type Reader ¶
type Reader interface {
// Get retrieves a configuration value by key.
//
// Get uses an internal cache for resilience. If the store is unavailable,
// it will return a cached value if one exists. This is intentional - for
// use cases like feature flags and rate limits, having slightly stale
// configuration is better than failing completely.
Get(ctx context.Context, key string) (Value, error)
// Find returns a page of keys and values matching the filter.
// Use Page.NextCursor() to paginate through results.
Find(ctx context.Context, filter Filter) (Page, error)
}
Reader provides read-only access to configuration. Use this interface in application code to read config values.
The Reader automatically uses an internal cache for resilience. If the backend store is temporarily unavailable, cached values will be returned. This ensures your application continues working even during database outages.
type Secret ¶ added in v0.6.3
type Secret struct {
// contains filtered or unexported fields
}
Secret holds sensitive bytes that can be explicitly zeroed.
String() and all text/JSON serialization methods return the mask "******" so secrets are never accidentally leaked into logs, error messages, or HTTP responses. Use Bytes() to obtain the actual content.
The internal representation is []byte so the secret can be zeroed in place via Wipe(). A runtime finalizer zeroes the backing bytes when the Secret becomes unreachable, providing a best-effort safety net. Call Wipe() explicitly for deterministic zeroing.
All methods use pointer receivers. Use *Secret in struct fields and function signatures. Equal() performs constant-time comparison.
var cfg struct {
DBPassword *config.Secret `yaml:"db_password"`
}
fmt.Println(cfg.DBPassword) // ******
pwd := cfg.DBPassword.Bytes() // []byte("actual-password"); zero after use
cfg.DBPassword.Wipe() // zeroes backing bytes
func NewSecret ¶ added in v0.6.3
NewSecret wraps s in a Secret and registers a finalizer that zeroes the backing bytes when the Secret becomes unreachable.
func NewSecretBytes ¶ added in v0.6.5
NewSecretBytes creates a Secret from a byte slice. It copies the input; callers may zero their slice after this call. A finalizer is registered to zero the backing bytes on GC.
func SecretFrom ¶ added in v0.6.6
SecretFrom extracts a *Secret from a Value of TypeSecret. The returned Secret holds a copy of the raw bytes; callers should call Wipe() when done to zero them from the heap. Returns ErrTypeMismatch if v is not TypeSecret.
func (*Secret) Bytes ¶ added in v0.6.5
Bytes returns a copy of the secret bytes. Each call allocates a new slice; callers should zero it after use.
func (*Secret) Clone ¶ added in v0.6.5
Clone returns a deep copy of the secret with its own finalizer.
func (*Secret) Equal ¶ added in v0.6.5
Equal reports whether s and other hold the same secret value. It uses constant-time comparison to resist timing attacks.
func (*Secret) GoString ¶ added in v0.6.3
GoString implements fmt.GoStringer so %#v also masks the value.
func (*Secret) Lock ¶ added in v0.6.5
Lock attempts to lock the secret's memory pages so they are not swapped to disk. Requires sufficient OS privileges (typically CAP_IPC_LOCK on Linux). Returns nil if the secret is zero.
func (*Secret) LogValue ¶ added in v0.6.5
LogValue implements slog.LogValuer so structured logging never leaks secrets.
func (*Secret) MarshalBSONValue ¶ added in v0.6.5
MarshalBSONValue implements bson.ValueMarshaler. A zero Secret marshals as BSON Null. A non-zero Secret marshals as BSON Binary (subtype 0x00) containing the raw bytes. Unlike text/JSON marshaling, this returns the actual content — use only in trusted MongoDB contexts.
func (*Secret) MarshalJSON ¶ added in v0.6.5
MarshalJSON implements json.Marshaler. Always marshals as "******".
func (*Secret) MarshalText ¶ added in v0.6.3
MarshalText implements encoding.TextMarshaler. A zero Secret marshals as an empty string so config files are not polluted with mask tokens on round-trip. A non-zero Secret always marshals as "******".
func (*Secret) Scan ¶ added in v0.6.5
Scan implements sql.Scanner so a Secret can be read from a SQL database. A NULL column value results in a zero Secret. Any prior backing bytes are zeroed before being replaced so re-used Secrets do not leave stale plaintext on the heap.
func (*Secret) Unlock ¶ added in v0.6.5
Unlock releases the mlock on the secret's memory pages. Call Unlock before Wipe if Lock was previously called. Returns nil if the secret is zero.
func (*Secret) UnmarshalBSONValue ¶ added in v0.6.5
UnmarshalBSONValue implements bson.ValueUnmarshaler. Accepts BSON Null (zero Secret), BSON Binary (raw bytes), or BSON String (text representation). A string equal to the mask "******" results in a zero Secret to prevent masked tokens from being treated as real credentials. Any prior backing bytes are zeroed before being replaced so re-used Secrets do not leave stale plaintext on the heap.
func (*Secret) UnmarshalText ¶ added in v0.6.3
UnmarshalText implements encoding.TextUnmarshaler, allowing YAML, JSON, TOML, and other text-based formats to populate the Secret. If the input is the mask "******", the secret is set to the empty value to prevent masked tokens from being treated as real credentials on round-trip. Any prior backing bytes are zeroed before being replaced so re-used Secrets do not leave stale plaintext on the heap.
func (*Secret) Value ¶ added in v0.6.3
Value implements driver.Valuer so a Secret can be written to a SQL database. A zero Secret writes NULL. A non-zero Secret writes the raw bytes. Unlike text/JSON marshaling, this returns the actual content — use only with trusted database drivers over encrypted connections.
type SetOption ¶
type SetOption func(*setOptions)
SetOption configures Set operations.
func WithIfExists ¶
func WithIfExists() SetOption
WithIfExists configures Set to only update the key if it already exists. Returns ErrNotFound if the key doesn't exist.
This is useful for implementing "update-only" semantics where you want to ensure the key was previously created.
Example:
err := cfg.Set(ctx, "app/timeout", 60, config.WithIfExists())
if config.IsNotFound(err) {
// Key doesn't exist, need to create it first
}
func WithIfNotExists ¶
func WithIfNotExists() SetOption
WithIfNotExists configures Set to only create the key if it doesn't exist. Returns ErrKeyExists if the key already exists.
This is useful for implementing "create-only" semantics where you want to ensure you don't accidentally overwrite an existing value.
Example:
err := cfg.Set(ctx, "lock/owner", "instance-1", config.WithIfNotExists())
if config.IsKeyExists(err) {
// Key was already taken by another instance
}
func WithSetCodec ¶
WithSetCodec sets the codec for encoding the value.
func WithTTL ¶ added in v0.6.5
WithTTL sets a time-to-live on the stored value. After d has elapsed the value is treated as if it does not exist: Get returns ErrNotFound, Find/ GetMany skip the entry, and the cache layer reports a miss.
Physical removal of the row/document is backend-specific:
- memory — a background sweeper deletes expired entries every WithCleanupInterval (default 1m) and emits a ChangeTypeDelete watch event.
- mongodb — MongoDB's native TTL index reaps expired documents (typically within ~60s of expiry); change-stream events are emitted by the server.
- postgres — read paths filter on expires_at; physical rows are removed when the next write touches them. Run a periodic DELETE job to reclaim storage and trigger NOTIFY events on demand.
- sqlite — same as postgres; no native TTL.
- redis — entries carry an embedded expiry; reads filter past-expiry payloads. The Redis-level TTL on the hash key is not used because hash fields cannot have individual TTLs.
Passing 0 or a negative duration is ignored (no TTL is set). On update, passing 0 preserves any existing TTL on the entry.
Example:
err := cfg.Set(ctx, "session/token", tok, config.WithTTL(24*time.Hour))
type StatsProvider ¶
type StatsProvider interface {
// Stats returns an immutable snapshot of store statistics.
// The returned [StoreStats] is safe to share across goroutines —
// the interface exposes no mutation surface, so callers cannot
// accidentally invalidate a value cached by a shared layer.
Stats(ctx context.Context) (StoreStats, error)
}
StatsProvider is an optional interface for stores that provide statistics.
For paginated namespace enumeration, prefer NamespaceLister: StatsProvider recomputes the full namespace set per call, while NamespaceLister can use the backend's native pagination primitive.
type Store ¶
type Store interface {
// Connect establishes connection to the storage backend.
// Must be called before any other operations.
Connect(ctx context.Context) error
// Close releases resources and closes the connection.
Close(ctx context.Context) error
// Get retrieves a configuration value by namespace and key.
// Returns ErrNotFound if the entry does not exist.
Get(ctx context.Context, namespace, key string) (Value, error)
// Set creates or updates a configuration value.
// The version is auto-incremented on each update.
// Returns the stored Value with updated metadata (version, timestamps).
Set(ctx context.Context, namespace, key string, value Value) (Value, error)
// Delete removes a configuration value by namespace and key.
// Returns ErrNotFound if the entry does not exist.
Delete(ctx context.Context, namespace, key string) error
// Find returns a page of keys and values matching the filter within a namespace.
// Use Page.NextCursor() to paginate through results.
Find(ctx context.Context, namespace string, filter Filter) (Page, error)
// Watch returns a channel that receives change events for cache invalidation.
// The channel is closed when the context is cancelled.
// This is used by the Manager for automatic cache synchronization.
// For stores that don't support real-time watching (e.g., file-based),
// return ErrWatchNotSupported.
Watch(ctx context.Context, filter WatchFilter) (<-chan ChangeEvent, error)
}
Store defines the interface for configuration storage backends.
Implementations must be safe for concurrent use by multiple goroutines. The store is responsible for persistence and versioning.
Design Philosophy ¶
This library is designed for use cases like feature flags, rate limits, and dynamic configuration where eventual consistency is acceptable. The key principle is: having some configuration (even slightly stale) is better than having no configuration at all.
The library maintains an internal in-memory cache that serves as a resilience layer. If the backend store becomes temporarily unavailable, the application can continue operating with cached values. This cache is NOT meant for sharing state across multiple application instances - each instance maintains its own cache that is kept in sync with the backend via the store's Watch mechanism.
For multi-instance deployments, each instance independently watches the backend (e.g., MongoDB Change Streams, PostgreSQL LISTEN/NOTIFY) to invalidate its local cache. This provides eventual consistency without requiring external dependencies like Redis.
Implementations:
- memory.Store: For testing and single-instance deployments
- mongodb.Store: For MongoDB databases (uses Change Streams internally)
- postgres.Store: For PostgreSQL databases (uses LISTEN/NOTIFY internally)
type StoreError ¶
type StoreError struct {
Op string // Operation that failed
Key string // Key involved (if applicable)
Backend string // Backend name (memory, mongodb, postgres)
Err error // Underlying error
}
StoreError wraps backend-specific errors with domain context.
func (*StoreError) Error ¶
func (e *StoreError) Error() string
func (*StoreError) Unwrap ¶
func (e *StoreError) Unwrap() error
type StoreStats ¶
type StoreStats interface {
// TotalEntries returns the total number of entries across all
// namespaces and types.
TotalEntries() int64
// EntriesByType yields (Type, count) pairs. The iterator can be
// ranged over directly:
//
// for t, n := range stats.EntriesByType() { ... }
//
// The underlying snapshot is immutable; the iterator yields fresh
// pairs and does not expose the backing map.
EntriesByType() iter.Seq2[Type, int64]
// EntriesByNamespace yields (namespace, count) pairs. Same
// immutability guarantee as [StoreStats.EntriesByType].
EntriesByNamespace() iter.Seq2[string, int64]
// CountForType returns the entry count for t, or 0 if absent.
// O(1) point lookup that avoids constructing an iterator.
CountForType(t Type) int64
// CountForNamespace returns the entry count for ns, or 0 if absent.
// O(1) point lookup that avoids constructing an iterator.
CountForNamespace(ns string) int64
// MarshalJSON serializes the stats in the canonical wire format —
// keys total_entries, entries_by_type, entries_by_namespace. The
// output round-trips through [UnmarshalStoreStats].
//
// The interface deliberately does NOT embed [json.Unmarshaler]
// because there is no portable way to unmarshal into an interface
// value — the canonical impl is unexported, so callers cannot
// construct a zero-value implementation to fill. Use
// [UnmarshalStoreStats] for the decode side.
json.Marshaler
}
StoreStats is an immutable snapshot of storage statistics returned by StatsProvider.Stats. The interface is deliberately read-only: mutation is unreachable through any exported method, so a snapshot can be held by a cache and observed by many goroutines without defensive copying.
Implementations are produced by NewStoreStats (when building a snapshot from raw counts) or UnmarshalStoreStats (when decoding from JSON). The canonical implementation in this package is unexported; backends should not type-assert against it.
To get a private mutable copy of a map, use maps.Collect on the iterator returned by StoreStats.EntriesByType or StoreStats.EntriesByNamespace.
func NewStoreStats ¶ added in v0.8.0
func NewStoreStats(totalEntries int64, byType map[Type]int64, byNamespace map[string]int64) StoreStats
NewStoreStats builds an immutable StoreStats snapshot (the return type of StatsProvider.Stats) from raw counts. Both maps are cloned on construction so the caller's later mutations do not leak into the snapshot — a snapshot can be safely shared across goroutines and cached behind a single-flight layer.
nil maps are accepted and treated as empty; the resulting snapshot returns 0 from StoreStats.CountForType / StoreStats.CountForNamespace and yields no pairs from the iterators.
func UnmarshalStoreStats ¶ added in v0.8.0
func UnmarshalStoreStats(data []byte) (StoreStats, error)
UnmarshalStoreStats parses the canonical JSON wire format into a fresh, immutable StoreStats (the same shape produced by [StoreStats.MarshalJSON]). Used by the gRPC/HTTP client side to reconstruct a snapshot received over the wire from a remote StatsProvider. Internally delegates to NewStoreStats, so the returned snapshot has the same map-clone immutability guarantee.
Expected JSON shape:
{
"total_entries": <int64>,
"entries_by_type": {"<Type-as-int>": <int64>, ...},
"entries_by_namespace": {"<namespace>": <int64>, ...}
}
Type keys are encoded as the decimal-string form of their numeric value (Go's default for integer map keys). The package does not define MarshalText on Type, so the wire encoding is the int — keep Type a numeric named type to preserve compatibility.
type Type ¶
type Type int
Type represents the type of a configuration value.
const ( // TypeUnknown indicates an unknown or unsupported type. TypeUnknown Type = iota // TypeInt represents an integer value. TypeInt // TypeFloat represents a floating-point value. TypeFloat // TypeString represents a string value. TypeString // TypeBool represents a boolean value. TypeBool // TypeMapStringInt represents a map[string]int value. TypeMapStringInt // TypeMapStringFloat represents a map[string]float64 value. TypeMapStringFloat // TypeMapStringString represents a map[string]string value. TypeMapStringString // TypeListInt represents a []int value. TypeListInt // TypeListFloat represents a []float64 value. TypeListFloat // TypeListString represents a []string value. TypeListString // TypeCustom represents a custom type that requires Unmarshal. TypeCustom // TypeSecret represents a sensitive byte value. // String() and all text/JSON paths return "******"; use SecretFrom to extract the actual bytes. TypeSecret )
func ParseType ¶
ParseType parses a string into a Type. Returns TypeUnknown for unrecognized strings.
func (Type) IsPrimitive ¶
IsPrimitive returns true if the type is a primitive (int, float, string, bool).
type TypeMismatchError ¶
TypeMismatchError provides details about a type conversion failure.
func (*TypeMismatchError) Error ¶
func (e *TypeMismatchError) Error() string
func (*TypeMismatchError) Unwrap ¶
func (e *TypeMismatchError) Unwrap() error
type UnsupportedCodecError ¶ added in v0.4.2
UnsupportedCodecError provides details about a codec that is not supported by the store.
func (*UnsupportedCodecError) Error ¶ added in v0.4.2
func (e *UnsupportedCodecError) Error() string
func (*UnsupportedCodecError) Unwrap ¶ added in v0.4.2
func (e *UnsupportedCodecError) Unwrap() error
type Value ¶
type Value interface {
// Marshal serializes the value to bytes using the configured codec.
Marshal(ctx context.Context) ([]byte, error)
// Unmarshal deserializes the value into the target.
Unmarshal(ctx context.Context, v any) error
// Type returns the detected type of the value.
Type() Type
// Codec returns the codec name used for this value.
Codec() string
// Int64 returns the value as int64.
Int64() (int64, error)
// Float64 returns the value as float64.
Float64() (float64, error)
// String returns the value as string.
String() (string, error)
// Bool returns the value as bool.
Bool() (bool, error)
// Metadata returns associated metadata, if any.
Metadata() Metadata
}
Value provides type-safe access to configuration values. This interface is focused on read operations. Write-related concerns like WriteMode are accessed via the WriteModer interface.
func CloneValue ¶ added in v0.6.6
func CloneValue(src Value, newRaw any, opts ...ValueOption) Value
CloneValue returns a new Value whose raw content is newRaw, with all metadata (version, timestamps, TTL, entryID, write mode) copied from src. The new value uses the default codec; pass WithValueCodec to override. The stale flag is not copied — the clone is a fresh value, not a cache fallback.
Intended for Store wrappers that transform the raw bytes (e.g. encrypt/decrypt, compress, sign) without touching metadata. Instead of manually extracting every metadata field from src and re-applying them with ValueOption calls, write:
decrypted := config.CloneValue(stored, plaintext) encrypted := config.CloneValue(incoming, ciphertext, config.WithValueCodec(encCodec))
func Get ¶
Get is a convenience function that retrieves a value using the Manager from context. Returns ErrManagerClosed if no manager is in context. Uses the namespace from context, or "" (default) if not set.
func MarkStale ¶
MarkStale returns a copy of the value with the stale flag set. This is used when serving cached values due to store errors. The returned value's Metadata().IsStale() will return true.
func NewRawValue ¶ added in v0.5.0
func NewRawValue(data []byte, codecName string, opts ...ValueOption) Value
NewRawValue creates a Value holding pre-marshaled bytes without decoding. The bytes are stored as-is and returned verbatim by Marshal(). This is used when the server does not have the codec registered (e.g., client-side encrypted data) and should pass the bytes through opaquely.
func NewSecretValue ¶ added in v0.6.6
func NewSecretValue(s *Secret, opts ...ValueOption) Value
NewSecretValue creates a Value that holds a secret. The raw bytes are stored as-is under the "secret" codec with TypeSecret, so Marshal returns plaintext bytes suitable for an encrypted store or transport. String() always returns "******" regardless of how the value is accessed. Use SecretFrom to extract the *Secret from a stored Value.
func NewValue ¶
func NewValue(data any, opts ...ValueOption) Value
NewValue creates a Value from any data with optional configuration.
Example ¶
package main
import (
"fmt"
"github.com/rbaliyan/config"
)
func main() {
// Create a value and inspect its type
val := config.NewValue(42)
fmt.Println("type:", val.Type())
i, err := val.Int64()
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("value:", i)
}
Output: type: int value: 42
func NewValueFromBytes ¶
func NewValueFromBytes(ctx context.Context, data []byte, codecName string, opts ...ValueOption) (Value, error)
NewValueFromBytes creates a Value from encoded bytes. If the named codec is not registered and differs from the default codec, the bytes are stored as a raw pass-through value (see NewRawValue).
type ValueOption ¶
type ValueOption func(*val)
ValueOption configures a value during construction.
func WithValueCodec ¶
func WithValueCodec(c codec.Codec) ValueOption
WithValueCodec sets the codec for the value.
func WithValueEntryID ¶
func WithValueEntryID(id string) ValueOption
WithValueEntryID sets the internal entry ID for the value. This is used by store implementations to track the database-level ID. Not intended for end-user code.
func WithValueExpiresAt ¶ added in v0.6.5
func WithValueExpiresAt(t time.Time) ValueOption
WithValueExpiresAt sets the absolute expiry time on the value. A zero time means no TTL. Used by store backends when reading back stored values.
func WithValueMetadata ¶
func WithValueMetadata(version int64, createdAt, updatedAt time.Time) ValueOption
WithValueMetadata sets metadata for the value.
func WithValueStale ¶
func WithValueStale(stale bool) ValueOption
WithValueStale marks the value as stale (served from cache due to store error). This is used internally by the Manager when falling back to cached values.
func WithValueType ¶
func WithValueType(t Type) ValueOption
WithValueType sets the type for the value.
func WithValueWriteMode ¶
func WithValueWriteMode(mode WriteMode) ValueOption
WithValueWriteMode sets the write mode for the value.
type VersionFilter ¶ added in v0.5.3
type VersionFilter interface {
// Version returns the specific version to retrieve (0 = all versions).
Version() int64
// Limit returns the maximum number of versions to return (0 = no limit).
Limit() int
// Cursor returns the pagination cursor for continuing from a previous result.
Cursor() string
}
VersionFilter defines criteria for retrieving version history. Use NewVersionFilter() to create a VersionFilterBuilder.
Two modes of operation:
- Specific version: set Version() > 0 to retrieve a single version
- List all versions: leave Version() as 0 and use Limit()/Cursor() for pagination
type VersionFilterBuilder ¶ added in v0.5.3
type VersionFilterBuilder struct {
// contains filtered or unexported fields
}
VersionFilterBuilder builds VersionFilter instances using a fluent API.
func NewVersionFilter ¶ added in v0.5.3
func NewVersionFilter() *VersionFilterBuilder
NewVersionFilter creates a new VersionFilterBuilder.
func (*VersionFilterBuilder) Build ¶ added in v0.5.3
func (b *VersionFilterBuilder) Build() VersionFilter
Build creates the VersionFilter.
func (*VersionFilterBuilder) WithCursor ¶ added in v0.5.3
func (b *VersionFilterBuilder) WithCursor(cursor string) *VersionFilterBuilder
WithCursor sets the pagination cursor for continuing from a previous result.
func (*VersionFilterBuilder) WithLimit ¶ added in v0.5.3
func (b *VersionFilterBuilder) WithLimit(limit int) *VersionFilterBuilder
WithLimit sets the maximum number of versions to return.
func (*VersionFilterBuilder) WithVersion ¶ added in v0.5.3
func (b *VersionFilterBuilder) WithVersion(version int64) *VersionFilterBuilder
WithVersion sets a specific version to retrieve. When set (> 0), GetVersions returns only that version. When 0 (default), GetVersions returns all versions with pagination.
type VersionNotFoundError ¶ added in v0.5.3
VersionNotFoundError provides details about a missing version.
func (*VersionNotFoundError) Error ¶ added in v0.5.3
func (e *VersionNotFoundError) Error() string
func (*VersionNotFoundError) Unwrap ¶ added in v0.5.3
func (e *VersionNotFoundError) Unwrap() error
type VersionPage ¶ added in v0.5.3
type VersionPage interface {
// Versions returns the values in this page, ordered by version descending.
Versions() []Value
// NextCursor returns the cursor for fetching the next page.
NextCursor() string
// Limit returns the actual limit used.
Limit() int
}
VersionPage represents a page of version history results.
func NewVersionPage ¶ added in v0.5.3
func NewVersionPage(versions []Value, nextCursor string, limit int) VersionPage
NewVersionPage creates a new VersionPage with the given versions and pagination info. This is used by Store implementations to create VersionPage results.
type VersionedReader ¶ added in v0.5.3
type VersionedReader interface {
// GetVersions retrieves version history for a configuration key.
// See VersionedStore.GetVersions for full semantics.
// Returns ErrVersioningNotSupported if the underlying store does not support versioning.
GetVersions(ctx context.Context, key string, filter VersionFilter) (VersionPage, error)
}
VersionedReader provides access to version history for a namespace. Obtained via type assertion on Config:
if vr, ok := cfg.(config.VersionedReader); ok {
// Get specific version
page, _ := vr.GetVersions(ctx, "key", config.NewVersionFilter().WithVersion(3).Build())
// List all versions
page, _ := vr.GetVersions(ctx, "key", config.NewVersionFilter().WithLimit(10).Build())
}
type VersionedStore ¶ added in v0.5.3
type VersionedStore interface {
// GetVersions retrieves version history for a configuration key.
//
// When VersionFilter.Version() is set (> 0), returns a page containing only
// that specific version. Returns ErrVersionNotFound if the version does not exist.
//
// When VersionFilter.Version() is 0, returns a paginated list of all versions
// ordered by version descending (newest first). Use Limit() and Cursor() for pagination.
//
// Returns ErrNotFound if the key has never existed or was deleted.
// Note: deleting a key also removes its version history in every current
// implementation. Only the memory store implements this interface today;
// other backends do not retain prior versions and do not satisfy
// VersionedStore (GetVersions via Manager.GetVersions returns
// ErrVersioningNotSupported).
GetVersions(ctx context.Context, namespace, key string, filter VersionFilter) (VersionPage, error)
}
VersionedStore is an optional interface for stores that support version history. Stores that implement this interface retain all historical versions of config entries. Use type assertion to check if a store supports versioning:
if vs, ok := store.(config.VersionedStore); ok {
// Get a specific version
page, _ := vs.GetVersions(ctx, ns, key, config.NewVersionFilter().WithVersion(3).Build())
// List all versions with pagination
page, _ := vs.GetVersions(ctx, ns, key, config.NewVersionFilter().WithLimit(10).Build())
}
type WatchFilter ¶
type WatchFilter struct {
// Namespaces to watch (empty = all namespaces).
Namespaces []string
// Prefixes to watch within namespaces (empty = all keys).
Prefixes []string
}
WatchFilter specifies criteria for watching changes.
type WatchHealthError ¶
WatchHealthError provides details about watch connection failures. Returned by Manager.Health() when watch has multiple consecutive failures.
func (*WatchHealthError) Error ¶
func (e *WatchHealthError) Error() string
func (*WatchHealthError) Unwrap ¶
func (e *WatchHealthError) Unwrap() error
type WatchStatus ¶
type WatchStatus struct {
// Connected indicates if the manager is connected to the store.
Connected bool `json:"connected"`
// ConsecutiveFailures is the number of consecutive watch failures.
// Resets to 0 when watch successfully connects.
ConsecutiveFailures int32 `json:"consecutive_failures"`
// LastError is the most recent watch error message (empty if no error).
LastError string `json:"last_error,omitempty"`
// LastAttempt is when the last watch connection was attempted.
LastAttempt time.Time `json:"last_attempt,omitempty"`
// Cache contains cache statistics for correlation with watch health.
Cache CacheStats `json:"cache"`
}
WatchStatus provides observability into the watch connection state. Applications can use this to monitor watch health and implement their own alerting or circuit breaking logic if needed.
type WriteMode ¶
type WriteMode int
WriteMode specifies the conditional behavior for Set operations.
const ( // WriteModeUpsert creates or updates the key (default behavior). WriteModeUpsert WriteMode = iota // WriteModeCreate only creates the key if it doesn't exist. // Returns ErrKeyExists if the key already exists. WriteModeCreate // WriteModeUpdate only updates the key if it already exists. // Returns ErrNotFound if the key doesn't exist. WriteModeUpdate )
func GetWriteMode ¶
GetWriteMode extracts the write mode from a Value. Returns WriteModeUpsert (default) if the value does not implement WriteModer. Store implementations should use this instead of calling WriteMode() directly.
type WriteModer ¶
type WriteModer interface {
WriteMode() WriteMode
}
WriteModer is an optional interface for values that carry write mode hints. Store implementations check for this interface in Set operations to determine conditional write behavior (create-only, update-only, or upsert).
type Writer ¶
type Writer interface {
// Set creates or updates a configuration value.
Set(ctx context.Context, key string, value any, opts ...SetOption) error
// Delete removes a configuration value by key.
Delete(ctx context.Context, key string) error
}
Writer provides write access to configuration. Use this interface for gRPC/HTTP servers to manage config.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package bind provides struct binding and validation for the config library.
|
Package bind provides struct binding and validation for the config library. |
|
Package codec defines the encoding/decoding abstraction for configuration values and a global registry of named codecs.
|
Package codec defines the encoding/decoding abstraction for configuration values and a global registry of named codecs. |
|
json
Package json provides a JSON codec for the config library.
|
Package json provides a JSON codec for the config library. |
|
toml
Package toml provides a TOML codec for the config library.
|
Package toml provides a TOML codec for the config library. |
|
yaml
Package yaml provides a YAML codec for the config library.
|
Package yaml provides a YAML codec for the config library. |
|
Package etcd provides an etcd v3-backed config.Store.
|
Package etcd provides an etcd v3-backed config.Store. |
|
Package expand provides variable substitution for configuration values.
|
Package expand provides variable substitution for configuration values. |
|
Package file provides file-based configuration loading and a config.Store backed by YAML, TOML, or JSON files.
|
Package file provides file-based configuration loading and a config.Store backed by YAML, TOML, or JSON files. |
|
internal
|
|
|
cursor
Package cursor provides a standardized envelope for opaque pagination cursors used across config store backends.
|
Package cursor provides a standardized envelope for opaque pagination cursors used across config store backends. |
|
storetest
Package storetest provides shared conformance suites for the optional store interfaces declared in package config (e.g.
|
Package storetest provides shared conformance suites for the optional store interfaces declared in package config (e.g. |
|
testutil
Package testutil collects small helpers shared across the repository's test suites.
|
Package testutil collects small helpers shared across the repository's test suites. |
|
Package k8s provides a config.Store backed by Kubernetes ConfigMaps and Secrets.
|
Package k8s provides a config.Store backed by Kubernetes ConfigMaps and Secrets. |
|
Package live keeps a typed configuration struct automatically synchronized with a config.Config source.
|
Package live keeps a typed configuration struct automatically synchronized with a config.Config source. |
|
Package memory provides an in-memory configuration store for testing and single-instance deployments.
|
Package memory provides an in-memory configuration store for testing and single-instance deployments. |
|
Package mongodb provides a MongoDB-backed configuration store with change stream notifications.
|
Package mongodb provides a MongoDB-backed configuration store with change stream notifications. |
|
Package multi provides a multi-store wrapper that supports fallback patterns.
|
Package multi provides a multi-store wrapper that supports fallback patterns. |
|
Package otel provides OpenTelemetry instrumentation for the config library.
|
Package otel provides OpenTelemetry instrumentation for the config library. |
|
Package postgres provides a PostgreSQL-backed configuration store with LISTEN/NOTIFY change notifications.
|
Package postgres provides a PostgreSQL-backed configuration store with LISTEN/NOTIFY change notifications. |
|
Package redis provides a config.Store implementation backed by Redis.
|
Package redis provides a config.Store implementation backed by Redis. |
|
Package replica provides a store that replicates a primary to one or more secondary stores.
|
Package replica provides a store that replicates a primary to one or more secondary stores. |
|
Package sqlite provides a SQLite-backed configuration store with application-level change notifications.
|
Package sqlite provides a SQLite-backed configuration store with application-level change notifications. |
|
Package transform provides a store decorator that applies a codec.Transformer at the storage boundary.
|
Package transform provides a store decorator that applies a codec.Transformer at the storage boundary. |