config

package module
v0.8.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 1, 2026 License: MIT Imports: 25 Imported by: 3 modules, 8 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Config

CI Go Reference Go Report Card Release OpenSSF Scorecard

A type-safe, namespace-aware configuration library for Go with support for multiple storage backends, built-in resilience, and OpenTelemetry instrumentation.

Features

  • Multiple Storage Backends: Memory, PostgreSQL, MongoDB, SQLite, File, Redis, etcd, Kubernetes (ConfigMaps/Secrets)
  • Version History: Retrieve and paginate historical versions of any config key
  • Multi-Store: Combine stores for caching, fallback, or replication patterns
  • Namespace Isolation: Organize configuration by environment, tenant, or service
  • Built-in Resilience: Internal cache ensures app works during backend outages
  • Type-safe Values: Strongly typed access with automatic conversion
  • Codecs: JSON, YAML, TOML encoding support
  • OpenTelemetry: Tracing and metrics instrumentation
  • Struct Binding: Bind configuration to Go structs with validation
  • Live Binding: Auto-reload structs on config changes via polling

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, cached values continue to be served
  • Each application instance maintains its own local cache
  • Cache is automatically invalidated via the store's native change stream (MongoDB Change Streams, PostgreSQL LISTEN/NOTIFY)
  • No external dependencies like Redis required for caching

Installation

go get github.com/rbaliyan/config

Quick Start

package main

import (
    "context"
    "log"

    "github.com/rbaliyan/config"
    "github.com/rbaliyan/config/memory"
)

func main() {
    ctx := context.Background()

    // Create manager with memory store
    mgr, err := config.New(
        config.WithStore(memory.NewStore()),
    )
    if err != nil {
        log.Fatal(err)
    }

    // Connect to backend
    if err := mgr.Connect(ctx); err != nil {
        log.Fatal(err)
    }
    defer mgr.Close(ctx)

    // Get configuration for a namespace (use "" for default)
    cfg := mgr.Namespace("production")

    // Set a value
    if err := cfg.Set(ctx, "app/timeout", 30); err != nil {
        log.Fatal(err)
    }

    // Get a value
    val, err := cfg.Get(ctx, "app/timeout")
    if err != nil {
        log.Fatal(err)
    }

    // Unmarshal into a typed variable
    var timeout int
    if err := val.Unmarshal(ctx, &timeout); err != nil {
        log.Fatal(err)
    }

    log.Printf("Timeout: %d", timeout)
}

Storage Backends

Memory Store

In-memory storage for testing and single-instance deployments.

import "github.com/rbaliyan/config/memory"

store := memory.NewStore()
PostgreSQL Store

Persistent storage with LISTEN/NOTIFY for real-time updates.

import (
    "database/sql"
    "github.com/lib/pq"
    "github.com/rbaliyan/config/postgres"
)

db, _ := sql.Open("postgres", "postgres://localhost/mydb")
listener := pq.NewListener(dsn, 10*time.Second, time.Minute, nil)

store := postgres.NewStore(db, listener,
    postgres.WithTable("config_entries"),
    postgres.WithNotifyChannel("config_changes"),
)
MongoDB Store

Persistent storage with change streams for real-time updates.

import (
    "go.mongodb.org/mongo-driver/v2/mongo"
    "go.mongodb.org/mongo-driver/v2/mongo/options"
    "github.com/rbaliyan/config/mongodb"
)

client, _ := mongo.Connect(options.Client().ApplyURI("mongodb://localhost:27017"))

store := mongodb.NewStore(client,
    mongodb.WithDatabase("config"),
    mongodb.WithCollection("entries"),
)
SQLite Store

Lightweight persistent storage with no external dependencies.

The store does not manage the database connection lifecycle: open the *sql.DB yourself and pass it in.

import (
    "database/sql"

    "github.com/rbaliyan/config/sqlite"
)

db, err := sql.Open("sqlite3", "config.db")
if err != nil {
    log.Fatal(err)
}

store := sqlite.NewStore(db,
    sqlite.WithTable("config_entries"),
)
File Store

Load configuration from YAML, TOML, or JSON files on disk.

By default the file store is read-only: Set and Delete return config.ErrReadOnly and Watch returns config.ErrWatchNotSupported. Pass file.WithWritable() to enable writes, in which case writes are persisted to a sidecar file (default: {path}.writes.yaml) that overlays the base file, and Watch is served by polling both files at WithWatchInterval (default 2s).

import "github.com/rbaliyan/config/file"

// Read-only (default).
store := file.NewStore("config.yaml")

// Writable: Set/Delete persist to config.yaml.writes.yaml, Watch is polling-based.
writable := file.NewStore("config.yaml",
    file.WithWritable(),
    file.WithWatchInterval(5*time.Second),
)

Top-level keys in the file become namespaces; nested keys are flattened with / (configurable via WithKeySeparator). Top-level scalar values go into the namespace set by WithDefaultNamespace (default: "default").

Pass WithExpansion or WithAngleBracketExpander to substitute ${VAR} or <VAR> placeholders at load time — see Variable Expansion.

Redis Store

Persistent storage backed by Redis. Each namespace is stored as a single Redis hash ({keyPrefix}:{namespace}); change events are published on a single pub/sub channel ({keyPrefix}:changes). Writes and notifications are performed atomically via Lua scripts, so watchers never observe a write they cannot read back.

import "github.com/rbaliyan/config/redis"

store := redis.NewStore(
    redis.WithAddress("redis.internal:6379"),
    redis.WithKeyPrefix("cfg"),     // hash names become "cfg:{namespace}"
    redis.WithPassword("s3cret"),
)

// Or connect to a Redis Cluster.
cluster := redis.NewStore(
    redis.WithCluster("redis-0:6379", "redis-1:6379", "redis-2:6379"),
)
etcd Store

Persistent storage backed by etcd v3. Values are stored as JSON envelopes that preserve the codec name and metadata across round-trips, and the namespace is used as the etcd key prefix (/<namespace>/<key>, or /<key> for the default empty namespace). Real-time Watch is served by etcd's native watch API.

import (
    clientv3 "go.etcd.io/etcd/client/v3"

    "github.com/rbaliyan/config/etcd"
)

client, err := clientv3.New(clientv3.Config{
    Endpoints: []string{"etcd.internal:2379"},
})
if err != nil {
    log.Fatal(err)
}

store, err := etcd.New(client, "prod",     // namespace = etcd key prefix
    etcd.WithWatchBufferSize(128),         // Watch channel buffer (default 64)
)
if err != nil {
    log.Fatal(err)
}
Kubernetes Store

Persistent storage backed by Kubernetes ConfigMaps and Secrets, with real-time Watch. Config namespaces map to Kubernetes namespaces (or a single fixed namespace via WithK8sNamespace). Each config namespace is backed by one ConfigMap named config-{namespace}; keys prefixed with secret/ (configurable via WithSecretKeyPrefix) are routed to a Secret named config-secrets-{namespace} instead.

The k8s store ships in the main module and imports no k8s.io/* packages. Instead of a kubernetes.Clientset, NewStore takes a narrow Client interface (Get/Upsert/Watch/Health) that the caller supplies. A reference adapter built on kubernetes.Interface lives in a separate module at k8s/example (so client-go stays out of the core module); import it directly or copy it into your project.

go get github.com/rbaliyan/config/k8s/example
import (
    "github.com/rbaliyan/config/k8s"
    kubeclient "github.com/rbaliyan/config/k8s/example"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/tools/clientcmd"
)

clientConfig, _ := clientcmd.BuildConfigFromFlags("", "/path/to/kubeconfig")
clientset, _ := kubernetes.NewForConfig(clientConfig)

adapter := kubeclient.New(clientset) // kubernetes.Interface -> k8s.Client
store := k8s.NewStore(adapter,
    k8s.WithK8sNamespace("my-app"),       // restrict to one k8s namespace
    k8s.WithSecretKeyPrefix("secret/"),   // keys with this prefix -> Secrets
)
if err := store.Connect(ctx); err != nil { // establishes the Client and starts the watch (no cache sync)
    return err
}
defer store.Close(ctx)

Config key / characters are replaced with . to form valid Kubernetes data keys (e.g. app/timeout becomes app.timeout).

Working with Values

Reading Values
val, err := cfg.Get(ctx, "database/port")
if err != nil {
    if config.IsNotFound(err) {
        // Key doesn't exist
    }
    return err
}

// Type-safe access via Value interface
port, err := val.Int64()
str, err := val.String()
flag, err := val.Bool()
num, err := val.Float64()

// Unmarshal into any type
var dbConfig DatabaseConfig
if err := val.Unmarshal(ctx, &dbConfig); err != nil {
    return err
}

// Access metadata
meta := val.Metadata()
version := meta.Version()
created := meta.CreatedAt()
updated := meta.UpdatedAt()
Writing Values
// Simple values
cfg.Set(ctx, "app/timeout", 30)
cfg.Set(ctx, "app/name", "myservice")
cfg.Set(ctx, "app/enabled", true)

// Complex values
cfg.Set(ctx, "app/servers", []string{"host1", "host2"})
cfg.Set(ctx, "app/limits", map[string]int{"max": 100, "min": 1})

// With options
cfg.Set(ctx, "app/config", value,
    config.WithType(config.TypeCustom),
    config.WithSetCodec(yamlCodec),
)
Conditional Writes

Control create/update behavior with conditional write options:

// Create only - fails if key already exists
err := cfg.Set(ctx, "feature/flag", true, config.WithIfNotExists())
if config.IsKeyExists(err) {
    // Key already existed, value not changed
}

// Update only - fails if key doesn't exist
err = cfg.Set(ctx, "feature/flag", false, config.WithIfExists())
if config.IsNotFound(err) {
    // Key didn't exist, nothing updated
}

// Default (upsert) - creates or updates
cfg.Set(ctx, "feature/flag", true) // Always succeeds

These options leverage atomic database operations:

  • PostgreSQL: Uses ON CONFLICT DO NOTHING / UPDATE with row count checks
  • MongoDB: Uses InsertOne / FindOneAndUpdate with upsert control
Listing Values
// List all keys with prefix using the Filter builder
limit := 100
page, err := cfg.Find(ctx, config.NewFilter().
    WithPrefix("app/database").
    WithLimit(limit).
    Build())

for key, val := range page.Results() {
    str, _ := val.String()
    fmt.Printf("%s = %s\n", key, str)
}

// Pagination: check if len(results) < limit to determine if more pages exist
if len(page.Results()) == page.Limit() {
    nextPage, _ := cfg.Find(ctx, config.NewFilter().
        WithPrefix("app/database").
        WithLimit(limit).
        WithCursor(page.NextCursor()).
        Build())
    // Process nextPage...
}
Listing Namespaces

Stores that implement NamespaceLister expose efficient, server-side paginated enumeration of namespace names. Memory, SQLite, PostgreSQL, and MongoDB ship with native implementations; Redis is intentionally excluded and falls back to StatsProvider.

// Type-assert against the underlying store (the Manager does not expose
// NamespaceLister directly — type-assert the store you pass into the Manager).
if nl, ok := store.(config.NamespaceLister); ok {
    cursor := ""
    for {
        names, next, err := nl.ListNamespaces(ctx, "prod-", 50, cursor)
        if err != nil {
            if config.IsInvalidCursor(err) {
                // Cursor was malformed, expired, or from a different store.
                // Retry from the first page.
                cursor = ""
                continue
            }
            return err
        }
        for _, ns := range names {
            handle(ns)
        }
        if next == "" {
            break
        }
        cursor = next
    }
}

Contract highlights (see config.NamespaceLister godoc for the full contract): namespaces are returned in ascending byte-wise UTF-8 order; cursors are opaque and not portable across backends (a cursor from the postgres store passed to the mongodb store returns ErrInvalidCursor); limit <= 0 is a caller error on every backend shipped today (no silent default-fallback).

Wrapper note: the otel, multi, transform, and expand wrapper stores do not currently forward NamespaceLister. A type assertion against a wrapped store returns ok == false; callers that need direct enumeration must unwrap to the underlying backend.

Version History

Stores that implement VersionedStore retain historical versions of config entries. Use GetVersions to retrieve them:

// Check if versioning is available
if vr, ok := cfg.(config.VersionedReader); ok {
    // Get a specific version
    page, err := vr.GetVersions(ctx, "app/timeout",
        config.NewVersionFilter().WithVersion(2).Build())

    // List all versions (newest first) with pagination
    page, err := vr.GetVersions(ctx, "app/timeout",
        config.NewVersionFilter().WithLimit(10).Build())

    for _, v := range page.Versions() {
        fmt.Printf("v%d: %v (updated %s)\n",
            v.Metadata().Version(), v, v.Metadata().UpdatedAt())
    }

    // Paginate through all versions
    if len(page.Versions()) == page.Limit() {
        nextPage, _ := vr.GetVersions(ctx, "app/timeout",
            config.NewVersionFilter().
                WithLimit(10).
                WithCursor(page.NextCursor()).
                Build())
        // ...
    }
}

The memory store supports versioning with an optional history cap:

store := memory.NewStore(memory.WithMaxHistory(100)) // Keep up to 100 versions per key

Namespaces

Namespaces provide isolation between different environments or tenants.

// Get configs for different namespaces
prodCfg := mgr.Namespace("production")
devCfg := mgr.Namespace("development")

// Same key, different values per namespace
prodCfg.Set(ctx, "timeout", 60)
devCfg.Set(ctx, "timeout", 5)

// Use "" for the default namespace
defaultCfg := mgr.Namespace("")

Namespace names may contain alphanumeric characters, underscores, dashes, dots, and colons (e.g. org.example:env.prod).

System Namespaces

The internal: prefix is reserved for system namespaces used by infrastructure components such as key rotation and service discovery. Use IsSystemNamespace() to check whether a namespace is reserved:

config.IsSystemNamespace("internal:config:crypto") // true
config.IsSystemNamespace("production")              // false

Server-side authorizers can use this to block client writes to system namespaces while allowing infrastructure components to manage them.

Context Helpers

Access configuration from context without explicit dependency injection.

// Add manager to context
ctx = config.ContextWithManager(ctx, mgr)
ctx = config.ContextWithNamespace(ctx, "production")

// Use anywhere in your application
val, err := config.Get(ctx, "app/setting")
err = config.Set(ctx, "app/setting", "value")

Multi-Store (Fallback Pattern)

Combine multiple stores for caching, fallback, or replication:

import "github.com/rbaliyan/config/multi"

// Cache + Backend pattern
cacheStore := memory.NewStore()
backendStore := postgres.NewStore(db, listener)
store := multi.NewStore(
    []config.Store{cacheStore, backendStore},
    multi.WithStrategy(multi.StrategyReadThrough),
)

// Primary + Backup pattern
primaryStore := postgres.NewStore(primaryDB, primaryListener)
backupStore := postgres.NewStore(backupDB, backupListener)
store := multi.NewStore(
    []config.Store{primaryStore, backupStore},
    multi.WithStrategy(multi.StrategyFallback),
)

mgr, _ := config.New(config.WithStore(store))

Strategies:

  • StrategyFallback: Read from first available store, write to all stores
  • StrategyReadThrough: Read through stores (cache miss populates earlier stores), write to all stores
  • StrategyWriteThrough: Write to all stores, read from first available store

All strategies write to all stores to maintain consistency. The difference is in read behavior:

  • Fallback/WriteThrough: Return first successful read
  • ReadThrough: Try each store in order, populate earlier stores on cache miss
Multi-Store Diagnostics

Multi-Store supports health checks and statistics when the underlying stores implement the optional interfaces:

// Health check (if underlying stores implement HealthChecker)
if err := store.Health(ctx); err != nil {
    log.Printf("Store unhealthy: %v", err)
}

// Statistics (if underlying stores implement StatsProvider)
stats, err := store.Stats(ctx)
if err == nil {
    log.Printf("Total entries: %d", stats.TotalEntries())
}

Because a write only needs one store to succeed, replicas can diverge when some stores are temporarily unavailable. Such partial failures are never silently discarded:

store := multi.NewStore(
    []config.Store{primaryStore, backupStore},
    // Surface partial write failures via a callback (logging/metrics).
    multi.WithOnWriteError(func(e *multi.PartialWriteError) {
        log.Printf("partial write %s %s/%s: %d of %d replicas failed",
            e.Op, e.Namespace, e.Key, e.Failed, e.Stores)
    }),
    // Optionally fail the write outright when any replica fails,
    // trading availability for an all-replicas-or-fail contract.
    multi.WithStrictWrites(),
)

// Count partial writes observed since the store was created.
log.Printf("partial writes: %d", store.PartialWrites())

For primary/secondary replication with synchronous or asynchronous propagation and configurable read preferences, see the dedicated replica package (replica.NewStore(primary, secondaries, ...)).

OpenTelemetry Instrumentation

Wrap stores with tracing and metrics. Both are disabled by default and must be explicitly enabled.

import "github.com/rbaliyan/config/otel"

// Enable tracing and metrics explicitly
instrumentedStore, _ := otel.WrapStore(store,
    otel.WithServiceName("my-service"),
    otel.WithBackendName("postgres"),
    otel.WithTracesEnabled(true),   // Opt-in, disabled by default
    otel.WithMetricsEnabled(true),  // Opt-in, disabled by default
)

mgr, _ := config.New(config.WithStore(instrumentedStore))

Metrics exported:

  • config.operations.total - Counter of all operations
  • config.errors.total - Counter of errors by type
  • config.operation.duration - Histogram of operation latency

Transform Store

transform.WrapStore decorates any config.Store with a codec.Transformer — a reversible byte-level transformation such as encryption or compression. The forward transform is applied on Set (before writing) and the reverse on Get (after reading), so values are stored transformed and returned in their original form. The wrapper transparently forwards the optional HealthChecker, StatsProvider, BulkStore, and VersionedStore interfaces to the inner store, and exposes Unwrap() to retrieve it.

import (
    "github.com/rbaliyan/config/codec"
    "github.com/rbaliyan/config/transform"
)

// transformer implements codec.Transformer (Name/Transform/Reverse).
store, err := transform.WrapStore(backendStore, transformer,
    transform.WithWatchBufferSize(128), // Watch output channel buffer (default 100)
)
if err != nil {
    log.Fatal(err)
}

mgr, _ := config.New(config.WithStore(store))

Struct Binding

Bind configuration to Go structs with validation. Struct fields are automatically mapped to hierarchical keys using the configured struct tag (default: json).

import "github.com/rbaliyan/config/bind"

type DatabaseConfig struct {
    Host string `json:"host" validate:"required"`
    Port int    `json:"port" validate:"required,min=1,max=65535"`
}

binder := bind.New(cfg, bind.WithTagValidation())
bound := binder.Bind()

// Store a struct - creates keys: database/host, database/port
err := bound.SetStruct(ctx, "database", DatabaseConfig{Host: "localhost", Port: 5432})

// Retrieve a struct - reads keys: database/host, database/port
var dbConfig DatabaseConfig
err = bound.GetStruct(ctx, "database", &dbConfig)

Nested structs are also supported:

type AppConfig struct {
    Name  string      `json:"name"`
    Cache CacheConfig `json:"cache"`
}

type CacheConfig struct {
    TTL     int  `json:"ttl"`
    Enabled bool `json:"enabled"`
}

// SetStruct creates: app/name, app/cache/ttl, app/cache/enabled
err := bound.SetStruct(ctx, "app", AppConfig{
    Name: "myapp",
    Cache: CacheConfig{TTL: 300, Enabled: true},
})

Use nonrecursive to store a nested struct as a single JSON value instead of flattening:

type Credentials struct {
    Username string `json:"username"`
    Password string `json:"password"`
}

type AppConfig struct {
    Name  string      `json:"name"`
    Creds Credentials `json:"creds,nonrecursive"` // Store as single JSON value
}

// SetStruct creates: app/name, app/creds (not app/creds/username, app/creds/password)
// Useful when fields are tightly coupled and should be updated atomically

Live Config (Auto-Reload)

Keep a typed struct automatically synchronized with configuration using polling and atomic swap:

import "github.com/rbaliyan/config/live"

type DatabaseConfig struct {
    Host string `json:"host"`
    Port int    `json:"port"`
}

ref, err := live.New[DatabaseConfig](ctx, cfg, "database",
    live.WithRefPollInterval[DatabaseConfig](10*time.Second),
    live.OnChange(func(old, new DatabaseConfig) {
        log.Printf("config changed: %s -> %s", old.Host, new.Host)
    }),
    live.OnError(func(err error) {
        log.Printf("reload error: %v", err)
    }),
)
if err != nil {
    return err
}
defer ref.Close()

// Hot path: single atomic load, zero contention
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    snap := ref.Load()
    fmt.Fprintf(w, "Host: %s, Port: %d", snap.Host, snap.Port)
})

Options:

  • WithRefPollInterval(d) - Set polling interval (default: 30s)
  • OnChange(fn) - Callback with old and new values on change
  • OnError(fn) - Callback on reload error

Methods:

  • Load() - Get current snapshot (atomic, zero-cost)
  • Close() - Stop background polling
  • ReloadNow(ctx) - Force immediate reload
  • LastReload() - Get last reload timestamp
  • LastError() - Get last error (nil if successful)
  • ReloadCount() - Get total successful reload count

Codecs

Multiple encoding formats are supported.

import "github.com/rbaliyan/config/codec"

// Available codecs
jsonCodec := codec.Get("json")
yamlCodec := codec.Get("yaml")
tomlCodec := codec.Get("toml")

// Use with manager
mgr, _ := config.New(
    config.WithStore(store),
    config.WithCodec(yamlCodec),
)

Configuration Types

The library tracks value types for better type safety.

const (
    TypeInt             // int, int64
    TypeFloat           // float64
    TypeString          // string
    TypeBool            // bool
    TypeMapStringInt    // map[string]int
    TypeMapStringFloat  // map[string]float64
    TypeMapStringString // map[string]string
    TypeListInt         // []int
    TypeListFloat       // []float64
    TypeListString      // []string
    TypeCustom          // any other type
)

Error Handling

val, err := cfg.Get(ctx, "key")
if err != nil {
    switch {
    case config.IsNotFound(err):
        // Key doesn't exist
    case config.IsTypeMismatch(err):
        // Type conversion failed
    case config.IsKeyExists(err):
        // Key already exists (from WithIfNotExists)
    default:
        // Other error
    }
}

Variable Expansion

Placeholder tokens in string values can be substituted at parse time (file store only) or at query time (any backend via expand.Store).

Parse-time expansion (file store)

Placeholders are resolved once when the file is loaded. Changes to the underlying source (env vars, etc.) are not reflected until the store reloads.

// ${VAR} and ${VAR:-default} from environment variables.
store := file.NewStore("config.yaml",
    file.WithExpansion(file.EnvExpander()),
)

// <secret-name> from a custom secrets provider.
store := file.NewStore("config.yaml",
    file.WithAngleBracketExpander(func(name string) (string, bool) {
        return vault.Get(name) // your lookup
    }),
)

// Chain multiple sources: custom overrides first, env fallback.
store := file.NewStore("config.yaml",
    file.WithExpansion(overridesFn),
    file.WithExpansion(file.EnvExpander()),
)

Config file syntax:

database:
  host: ${DB_HOST}               # replaced with env var
  port: ${DB_PORT:-5432}         # fallback to 5432 if unset
  password: <db_password>        # replaced via angle-bracket expander
  literal: \${NOT_EXPANDED}      # backslash disables substitution
Query-time expansion (any backend)

expand.NewStore wraps any config.Store and expands placeholders on every Get and Find, so changes to the source are reflected immediately.

import "github.com/rbaliyan/config/expand"

inner := memory.NewStore()
if err := inner.Connect(ctx); err != nil {
    log.Fatal(err)
}

s, err := expand.NewStore(inner,
    expand.WithDollarExpander(expand.EnvExpander()),  // ${VAR}
    expand.WithAngleExpander(secretsFn),              // <VAR>
)

// Reads expand at call time; writes pass through to the inner store unchanged.
val, _ := s.Get(ctx, "app", "host")

Sensitive Values

config.Secret wraps a sensitive string and masks it in all output so secrets are never accidentally leaked into logs, error messages, or HTTP responses.

type AppConfig struct {
    DBPassword config.Secret `yaml:"db_password"`
    APIKey     config.Secret `json:"api_key"`
}

var cfg AppConfig
// Decode from YAML/JSON/TOML: Bytes() holds the real plaintext.
yaml.Unmarshal(data, &cfg)

fmt.Println(cfg.DBPassword)                  // ******
log.Info("config loaded", "cfg", cfg)        // *** no leak ***
realPwd := string(cfg.DBPassword.Bytes())    // "actual-password"

// Marshal to JSON always masks: a Secret marshals as "******" whether zero or not.
out, _ := json.Marshal(cfg)
// Marshal to text (YAML/TOML) is zero-aware: a non-zero Secret writes "******",
// while a zero Secret writes "" so round-tripped files are not polluted.
yamlOut, _ := yaml.Marshal(cfg)

// IsZero reports whether no value has been set.
if cfg.APIKey.IsZero() {
    log.Warn("API key not configured")
}

UnmarshalText("******") produces a zero Secret (empty value), preventing a masked token from being treated as a real credential on round-trip.

Manager Options

mgr, err := config.New(
    config.WithStore(store),           // Required: storage backend
    config.WithCodec(yamlCodec),       // Optional: default codec (default: JSON)
    config.WithLogger(slogLogger),     // Optional: custom logger
)

Benchmarks

Run the benchmark suite (memory store, Value, cache, and json/yaml/toml codecs) with just bench, or compare against the committed baseline.txt. See BENCHMARKS.md for details.

License

MIT License

Documentation

Index

Examples

Constants

View Source
const DefaultNamespace = ""

DefaultNamespace is the default namespace (empty string). Use this when you don't need namespace separation.

View Source
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

View Source
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.

View Source
var ErrBulkWritePartial = errors.New("config: bulk write partially failed")

ErrBulkWritePartial is returned when a bulk write operation partially fails.

View Source
var ErrWatchUnhealthy = errors.New("config: watch unhealthy")

ErrWatchUnhealthy is returned by Health() when watch has consecutive failures.

Functions

func ContextNamespace

func ContextNamespace(ctx context.Context) string

ContextNamespace retrieves the namespace from context. Returns empty string if no namespace is set.

func ContextWithManager

func ContextWithManager(ctx context.Context, mgr Manager) context.Context

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

func ContextWithNamespace(ctx context.Context, namespace string) context.Context

ContextWithNamespace adds a namespace to the context. Operations will use this namespace.

func EntryID added in v0.6.3

func EntryID(v Value) string

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

func GetExpiresAt(v Value) time.Time

GetExpiresAt returns the expiry time stored in v's metadata, or zero if none.

func IsAliasExists added in v0.5.5

func IsAliasExists(err error) bool

IsAliasExists checks if an error indicates an alias already exists.

func IsBulkWritePartial

func IsBulkWritePartial(err error) bool

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

func IsExpired(v Value) bool

IsExpired reports whether v has a non-zero expiry time that is in the past.

func IsInvalidCursor added in v0.7.1

func IsInvalidCursor(err error) bool

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

func IsInvalidKey(err error) bool

IsInvalidKey checks if an error indicates an invalid key.

func IsKeyExists

func IsKeyExists(err error) bool

IsKeyExists checks if an error indicates a key already exists.

func IsNamespaceFull added in v0.5.4

func IsNamespaceFull(err error) bool

IsNamespaceFull checks if an error indicates a namespace has reached its key limit.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound checks if an error indicates a missing key.

func IsSystemNamespace added in v0.5.0

func IsSystemNamespace(namespace string) bool

IsSystemNamespace returns true if the namespace is reserved for internal use. A system namespace must start with the "internal:" prefix.

func IsTypeMismatch

func IsTypeMismatch(err error) bool

IsTypeMismatch checks if an error indicates a type mismatch.

func IsUnsupportedCodec added in v0.4.2

func IsUnsupportedCodec(err error) bool

IsUnsupportedCodec checks if an error indicates an unsupported codec.

func IsVersionNotFound added in v0.5.3

func IsVersionNotFound(err error) bool

IsVersionNotFound checks if an error indicates a missing version.

func IsVersioningNotSupported added in v0.5.3

func IsVersioningNotSupported(err error) bool

IsVersioningNotSupported checks if an error indicates versioning is not supported.

func IsWatchUnhealthy

func IsWatchUnhealthy(err error) bool

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

func Set(ctx context.Context, key string, value any, opts ...SetOption) error

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

func ValidateKey(key string) error

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

func ValidateNamespace(namespace string) error

ValidateNamespace validates a namespace name. Empty namespaces are allowed (represents the default namespace). Returns ErrInvalidNamespace if the namespace contains invalid characters.

func WrapStoreError

func WrapStoreError(op, backend, key string, err error) error

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

func NewMemoryCache(capacity int, ttl time.Duration) (Cache, error)

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

type CodecValidator interface {
	SupportsCodec(codecName string) bool
}

CodecValidator is an optional interface for stores that restrict supported codecs. Stores that do not implement this accept all codecs (backward compatible).

type Config

type Config interface {
	Reader
	Writer

	// Namespace returns the namespace name.
	Namespace() string
}

Config combines Reader and Writer for a specific namespace.

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 NewFilter

func NewFilter() *FilterBuilder

NewFilter creates a new FilterBuilder.

func (*FilterBuilder) Build

func (b *FilterBuilder) Build() Filter

Build creates the Filter.

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

type InvalidKeyError struct {
	Key    string
	Reason string
}

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

type KeyExistsError struct {
	Key       string
	Namespace string
}

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

type KeyNotFoundError struct {
	Key       string
	Namespace string
}

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

func ContextManager(ctx context.Context) Manager

ContextManager retrieves the Manager from context. Returns nil if no manager is set.

func New

func New(opts ...Option) (Manager, error)

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

type NamespaceFullError struct {
	Namespace string
	Limit     int
}

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

func WithAlias(alias, target string) Option

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

func WithAliases(target string, aliases ...string) Option

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

func WithCache(c Cache) Option

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

func WithCodec(c codec.Codec) Option

WithCodec sets the default codec for encoding/decoding values. Default is JSON if not specified.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets a custom logger.

func WithMaxKeysPerNamespace added in v0.5.4

func WithMaxKeysPerNamespace(n int) Option

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

func WithMemoryCacheTTL(d time.Duration) Option

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

func WithStore(store Store) Option

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

func WithWatchBackoffFactor(f float64) Option

WithWatchBackoffFactor sets the multiplier applied to backoff after each watch failure. Default: 2.0.

func WithWatchInitialBackoff added in v0.1.12

func WithWatchInitialBackoff(d time.Duration) Option

WithWatchInitialBackoff sets the initial wait time between watch reconnection attempts. Default: 100ms.

func WithWatchMaxBackoff added in v0.1.12

func WithWatchMaxBackoff(d time.Duration) Option

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()
}

func NewPage

func NewPage(results map[string]Value, nextCursor string, limit int) Page

NewPage creates a new Page with the given results and pagination info. This is used by Store implementations to create Page results.

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

func NewSecret(s string) *Secret

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

func NewSecretBytes(b []byte) *Secret

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

func SecretFrom(_ context.Context, v Value) (*Secret, error)

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

func (s *Secret) Bytes() []byte

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

func (s *Secret) Clone() *Secret

Clone returns a deep copy of the secret with its own finalizer.

func (*Secret) Equal added in v0.6.5

func (s *Secret) Equal(other *Secret) bool

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

func (s *Secret) GoString() string

GoString implements fmt.GoStringer so %#v also masks the value.

func (*Secret) IsZero added in v0.6.3

func (s *Secret) IsZero() bool

IsZero reports whether the secret holds no value.

func (*Secret) Lock added in v0.6.5

func (s *Secret) Lock() error

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

func (s *Secret) LogValue() slog.Value

LogValue implements slog.LogValuer so structured logging never leaks secrets.

func (*Secret) MarshalBSONValue added in v0.6.5

func (s *Secret) MarshalBSONValue() (byte, []byte, error)

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

func (s *Secret) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler. Always marshals as "******".

func (*Secret) MarshalText added in v0.6.3

func (s *Secret) MarshalText() ([]byte, error)

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

func (s *Secret) Scan(value any) error

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) String added in v0.6.3

func (s *Secret) String() string

String implements fmt.Stringer and always returns "******".

func (*Secret) Unlock added in v0.6.5

func (s *Secret) Unlock() error

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

func (s *Secret) UnmarshalBSONValue(typ byte, data []byte) error

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

func (s *Secret) UnmarshalText(b []byte) error

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

func (s *Secret) Value() (driver.Value, error)

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.

func (*Secret) Wipe added in v0.6.5

func (s *Secret) Wipe()

Wipe zeroes the in-memory backing bytes and resets the secret to zero. After Wipe, Bytes() returns nil and IsZero() returns true. Safe to call multiple times and on a nil receiver.

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

func WithSetCodec(c codec.Codec) SetOption

WithSetCodec sets the codec for encoding the value.

func WithTTL added in v0.6.5

func WithTTL(d time.Duration) SetOption

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))

func WithType

func WithType(t Type) SetOption

WithType explicitly sets the value type.

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

func ParseType(s string) Type

ParseType parses a string into a Type. Returns TypeUnknown for unrecognized strings.

func (Type) IsList

func (t Type) IsList() bool

IsList returns true if the type is a list type.

func (Type) IsMap

func (t Type) IsMap() bool

IsMap returns true if the type is a map type.

func (Type) IsPrimitive

func (t Type) IsPrimitive() bool

IsPrimitive returns true if the type is a primitive (int, float, string, bool).

func (Type) String

func (t Type) String() string

String returns the string representation of the type.

type TypeMismatchError

type TypeMismatchError struct {
	Key      string
	Expected Type
	Actual   Type
}

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

type UnsupportedCodecError struct {
	Codec   string
	Backend string
}

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

func Get(ctx context.Context, key string) (Value, error)

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

func MarkStale(v Value) Value

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

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

type VersionNotFoundError struct {
	Key       string
	Namespace string
	Version   int64
}

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

type WatchHealthError struct {
	ConsecutiveFailures int32
	LastError           string
}

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

func GetWriteMode(v Value) WriteMode

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.

func (WriteMode) String

func (m WriteMode) String() string

String returns the string representation of the write mode.

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.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址