config

package
v0.0.0-...-5ed4770 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package config provides configuration loading and validation for the Sequify server.

Configuration is loaded in three stages with increasing priority:

  1. Default values (via confmap provider)
  2. YAML config file (via file + yaml parser providers)
  3. Environment variables (via env/v2 provider, prefix: SEQUIFY_)

Environment variable mapping: SEQUIFY_LOG__LEVEL -> log.level Double underscore (__) separates hierarchy levels; single underscores are preserved. (strip prefix, lowercase, replace _ with .)

Index

Constants

View Source
const (
	// DefaultLLMRetryMaxDelay is the maximum delay between LLM retry attempts.
	DefaultLLMRetryMaxDelay = 30 * time.Second

	// DefaultSendTimeout is the timeout for sending updates to clients.
	DefaultSendTimeout = 5 * time.Second

	// DefaultRedisDialTimeout is the default dial timeout for Redis connections.
	DefaultRedisDialTimeout = 5 * time.Second

	// DefaultRedisReadTimeout is the default read timeout for Redis connections.
	DefaultRedisReadTimeout = 5 * time.Second

	// DefaultRedisWriteTimeout is the default write timeout for Redis connections.
	DefaultRedisWriteTimeout = 5 * time.Second

	// DefaultMaxRetries is the default number of retry attempts.
	DefaultMaxRetries = 3
)

Default configuration constants used across the codebase. These provide named references for values that would otherwise appear as magic numbers in multiple files.

Variables

View Source
var (
	// ErrMissingRequired is returned when a required config field is empty.
	ErrMissingRequired = errors.New("missing required config field")

	// ErrInvalidFormat is returned when config file parsing fails.
	ErrInvalidFormat = errors.New("invalid config format")

	// ErrInvalidValue is returned when a config value fails validation.
	ErrInvalidValue = errors.New("invalid config value")

	// ErrAPIKeyNotConfigured is returned when security.require_api_key is true
	// but security.apikey is empty. This prevents silent authentication bypass.
	ErrAPIKeyNotConfigured = errors.New("API key authentication is required but no API key is configured")
)

Sentinel errors for configuration validation.

These errors are used with fmt.Errorf("%w", ErrXxx) to preserve the error chain. Callers use errors.Is(err, ErrMissingRequired) to check error types.

Functions

func LevelVar

func LevelVar() *slog.LevelVar

LevelVar returns the shared log level variable. Use with server.WithLogLevel to enable the /log-level endpoint.

func NewLogger

func NewLogger(logFile string) *slog.Logger

NewLogger creates a slog.Logger that writes JSON to both stdout and the specified log file. The log file is rotated by lumberjack.

Both output destinations share the same logLevel, so changing it at runtime affects both stdout and file output simultaneously.

Types

type AgentConfig

type AgentConfig struct {
	ToolTimeout       time.Duration `koanf:"tool_timeout"`        // default 30s
	MaxIterations     int           `koanf:"max_iterations"`      // default 50
	CompressThreshold int           `koanf:"compress_threshold"`  // 0 = derive from ContextWindow/2, disabled if ContextWindow also 0
	KeepRecentRounds  int           `koanf:"keep_recent_rounds"`  // default 5
	MaxToolResultLen  int           `koanf:"max_tool_result_len"` // default 50000
	MaxContentLength  int           `koanf:"max_content_length"`  // max user message content length in characters, default 100000
	TypingInterval    time.Duration `koanf:"typing_interval"`     // default 5s

	// Phase 33: LLM retry configuration
	LLMMaxRetries     int           `koanf:"llm_max_retries"`      // default 3
	LLMRetryBaseDelay time.Duration `koanf:"llm_retry_base_delay"` // default 1s (exponential backoff base)
	LLMRetryMaxDelay  time.Duration `koanf:"llm_retry_max_delay"`  // default 30s (cap for exponential backoff)
}

AgentConfig holds agent layer configuration.

type Config

type Config struct {
	Listen    string          `koanf:"listen"`
	Log       LogConfig       `koanf:"log"`
	Database  DatabaseConfig  `koanf:"database"`
	Redis     RedisConfig     `koanf:"redis"`
	Queue     QueueConfig     `koanf:"queue"`
	LLM       LLMConfig       `koanf:"llm"`
	WebSocket WebSocketConfig `koanf:"websocket"`
	Session   SessionConfig   `koanf:"session"`
	Agent     AgentConfig     `koanf:"agent"`
	Webhook   WebhookConfig   `koanf:"webhook"`
	Security  SecurityConfig  `koanf:"security"`
	Telemetry TelemetryConfig `koanf:"telemetry"`
}

Config holds all application configuration.

func Load

func Load(envName string) (*Config, error)

Load loads configuration from defaults, optional YAML file, and environment variables (in that priority order, highest last).

The envName parameter selects the config file: "dev" -> etc/config.dev.yaml. When envName is empty, only defaults and environment variables are used (pure env mode).

func (*Config) LogLevelHandler

func (c *Config) LogLevelHandler() *LogLevelHandler

LogLevelHandler returns the HTTP handler for dynamic log level control.

func (*Config) Logger

func (c *Config) Logger() *slog.Logger

Logger creates a slog.Logger from the config's log settings. The initial log level is set from c.Log.Level.

func (*Config) ValidateAndDerive

func (c *Config) ValidateAndDerive() error

ValidateAndDerive checks the configuration for required fields and valid values. It also derives computed values from other config fields (e.g., CompressThreshold from ContextWindow).

type DatabaseConfig

type DatabaseConfig struct {
	Dialect         string `koanf:"dialect"` // postgres, sqlite, mysql
	DSN             string `koanf:"dsn"`
	MaxOpenConns    int    `koanf:"max_open_conns"`    // default 25
	MaxIdleConns    int    `koanf:"max_idle_conns"`    // default 5
	ConnMaxLifetime int    `koanf:"conn_max_lifetime"` // seconds, default 300
	AutoMigrate     bool   `koanf:"auto_migrate"`      // default true
}

DatabaseConfig holds database configuration.

type LLMConfig

type LLMConfig struct {
	Provider      string `koanf:"provider"`
	APIKey        string `koanf:"apikey"`
	BaseURL       string `koanf:"baseurl"`
	Model         string `koanf:"model"`
	MaxTokens     int    `koanf:"max_tokens"`
	ContextWindow int    `koanf:"context_window"` // default 128000
}

LLMConfig holds LLM provider configuration.

Note: koanf struct tags use "apikey" and "baseurl" (no underscores) because the env var transform function replaces ALL underscores with dots. SEQUIFY_LLM__APIKEY -> llm.apikey maps correctly. Using "api_key" would require SEQUIFY_LLM_API_KEY -> llm.api.key (mismatch).

type LogConfig

type LogConfig struct {
	Level string `koanf:"level"`
	File  string `koanf:"file"`
}

LogConfig holds logging configuration.

type LogLevelHandler

type LogLevelHandler struct {
	// contains filtered or unexported fields
}

LogLevelHandler provides HTTP handlers for runtime log level control.

Use GetLevel (GET /log-level) to read the current level. Use SetLevel (PUT /log-level) to change the level.

func NewLogLevelHandler

func NewLogLevelHandler() *LogLevelHandler

NewLogLevelHandler creates a LogLevelHandler bound to the shared logLevel.

func (*LogLevelHandler) ServeHTTP

func (h *LogLevelHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP dispatches to GetLevel or SetLevel based on HTTP method.

type MetricsConfig

type MetricsConfig struct {
	Enabled     bool   `koanf:"enabled"`
	Path        string `koanf:"path"`         // default "/metrics"
	RequireAuth bool   `koanf:"require_auth"` // require API key authentication, default true
}

MetricsConfig holds Prometheus metrics configuration.

type QueueConfig

type QueueConfig struct {
	Concurrency int `koanf:"concurrency"` // worker count, default 10
}

QueueConfig holds task queue configuration.

type RedisConfig

type RedisConfig struct {
	URL      string `koanf:"url"`
	PoolSize int    `koanf:"pool_size"`
}

RedisConfig holds Redis configuration.

type SecurityConfig

type SecurityConfig struct {
	APIKey         string  `koanf:"apikey"`           // X-API-Key header value (empty = no auth)
	RequireAPIKey  bool    `koanf:"require_api_key"`  // require API Key to be configured (default true)
	RateLimitRPS   float64 `koanf:"rate_limit_rps"`   // requests per second per key, default 100
	RateLimitBurst int     `koanf:"rate_limit_burst"` // burst size, default 200
	MaxRequestBody int64   `koanf:"max_request_body"` // max HTTP body bytes, default 1MB
}

SecurityConfig holds HTTP security settings.

type SessionConfig

type SessionConfig struct {
	FetchDebounce time.Duration `koanf:"fetch_debounce"` // default 300ms
}

SessionConfig holds session layer configuration.

type TelemetryConfig

type TelemetryConfig struct {
	Metrics MetricsConfig `koanf:"metrics"`
	Tracing TracingConfig `koanf:"tracing"`
}

TelemetryConfig holds observability configuration.

type TracingConfig

type TracingConfig struct {
	Enabled        bool    `koanf:"enabled"`
	Endpoint       string  `koanf:"endpoint"`        // OTLP collector endpoint
	SamplingRate   float64 `koanf:"sampling_rate"`   // 0.0-1.0, default 1.0
	Insecure       bool    `koanf:"insecure"`        // skip TLS (default false)
	ServiceVersion string  `koanf:"service_version"` // e.g. "1.0.0"
	Environment    string  `koanf:"environment"`     // e.g. "production"
}

TracingConfig holds OpenTelemetry tracing configuration.

type WebSocketConfig

type WebSocketConfig struct {
	PingInterval  time.Duration `koanf:"ping_interval"`
	PongTimeout   time.Duration `koanf:"pong_timeout"`
	MinSDKVersion int           `koanf:"min_sdk_version"`
	GracePeriod   time.Duration `koanf:"grace_period"`

	// Phase 23: connection count and drain
	MaxConnsPerUser   int           `koanf:"max_conns_per_user"`  // default 10
	ConnRenewInterval time.Duration `koanf:"conn_renew_interval"` // default 120s
	ConnCountTTL      time.Duration `koanf:"conn_count_ttl"`      // default 360s
	DrainTimeout      time.Duration `koanf:"drain_timeout"`       // default 5s
	AllowedOrigins    []string      `koanf:"allowed_origins"`     // allowed WebSocket origin patterns (empty = localhost only for dev safety)
	MessageRateLimit  int           `koanf:"message_rate_limit"`  // messages per second per connection (0 = disabled)
	MessageBurstSize  int           `koanf:"message_burst_size"`  // burst size (0 = 2x rate limit)
}

WebSocketConfig holds WebSocket connection configuration.

type WebhookConfig

type WebhookConfig struct {
	URL         string        `koanf:"url"`          // global webhook URL (empty = disabled)
	HTTPTimeout time.Duration `koanf:"http_timeout"` // HTTP request timeout, default 10s
	MaxRetry    int           `koanf:"max_retry"`    // max retry count, default 5
	Secret      string        `koanf:"secret"`       // HMAC-SHA256 signing secret (empty = no signature)
}

WebhookConfig holds webhook delivery configuration.

Jump to

Keyboard shortcuts

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