config

package
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package config holds the runtime configuration populated from environment variables with optional .env file support.

Environment loading for llm-router: process variables with optional .env file support. Process variables win over the file. A missing file is not an error. .env.example mirrors DefaultTemplate.

XDG directory layout for llm-router: portable defaults plus managed directory creation. All four bases honor the XDG variable first and fall back to a home-relative directory on every OS. Home-relative means the same suffix on Unix and Windows (no native AppData switch).

Mirror: scripts/shared/xdg.go carries the same semantics for the scripts module. The two files stay in sync; stability tests in both modules lock the behavior.

Index

Constants

View Source
const (
	DefaultHost                = "localhost"
	DefaultPort                = "8080"
	DefaultLogLevel            = "info"
	DefaultEventsRetentionDays = 3
	// DefaultLuaPoolBucketSize caps idle Lua states stored per plugin
	// bucket when LUA_POOL_BUCKET_SIZE is blank.
	DefaultLuaPoolBucketSize = 16
)

Configuration defaults for environment loading. Storage and dotenv defaults live in xdg.go (portable XDG forms).

View Source
const (
	DefaultDatabasePath = "~/.local/share/llm-router/llm-router.sqlite3"
	DefaultCachePath    = "~/.cache/llm-router/llm-router.cache.sqlite3"
	DefaultEventsPath   = "~/.local/state/llm-router/llm-router.events.sqlite3"
	DefaultDotenvPath   = "~/.config/llm-router/.env"
	// DefaultCredentialsKeyPath holds the credential encryption key. It sits
	// in the configuration directory, apart from the data directory, so a
	// copied database file alone never carries its key.
	DefaultCredentialsKeyPath = "~/.config/llm-router/credentials.key"

	DefaultDevDatabasePath = "~/.local/share/llm-router/llm-router.dev.sqlite3"
	DefaultDevCachePath    = "~/.cache/llm-router/llm-router.cache.dev.sqlite3"
	DefaultDevEventsPath   = "~/.local/state/llm-router/llm-router.events.dev.sqlite3"
	DefaultDevDotenvPath   = "~/.config/llm-router/.env.dev"
)

Portable dotenv and storage defaults (unexpanded). Load expands them through ExpandPath, so every OS resolves the same text.

View Source
const AdminHost = "127.0.0.1"

AdminHost pins the admin listener to loopback regardless of HOST. The loopback bind is the only protection on an authentication-free listener, so it is hardcoded, never configured.

View Source
const ApplicationDirectoryName = "llm-router"

ApplicationDirectoryName is the single directory entry under each XDG base that llm-router owns.

Variables

View Source
var (
	ErrInvalidPort              = errors.New("invalid port")
	ErrInvalidLogLevel          = errors.New("invalid log level")
	ErrInvalidEventsRetention   = errors.New("invalid events retention")
	ErrInvalidLuaPoolBucketSize = errors.New("invalid lua pool bucket size")
	ErrConfigFileExists         = errors.New("configuration file exists")
	ErrMissingTargetPath        = errors.New("configuration target path is required")
)

Sentinel errors for environment loading. Match with errors.Is.

View Source
var (
	ErrHomeDirectoryUnresolvable = errors.New("home directory unresolvable")
	ErrUnsupportedTilde          = errors.New("unsupported tilde expression")
)

Sentinel errors for path expansion. Match with errors.Is.

View Source
var ErrParentMissing = errors.New("parent directory missing")

Sentinel errors for managed directory creation. Match with errors.Is.

Functions

func CacheApplicationDirectory added in v0.4.0

func CacheApplicationDirectory() (string, error)

CacheApplicationDirectory returns the expanded cache application directory ($XDG_CACHE_HOME/llm-router else ~/.cache).

func CheckDistinctPaths added in v0.6.1

func CheckDistinctPaths(values map[string]string) error

CheckDistinctPaths fails when two of the database path keys in values resolve to the same file. Missing keys are skipped.

func ConfigurationApplicationDirectory added in v0.4.0

func ConfigurationApplicationDirectory() (string, error)

ConfigurationApplicationDirectory returns the expanded configuration application directory ($XDG_CONFIG_HOME/llm-router else ~/.config).

func DataApplicationDirectory added in v0.4.0

func DataApplicationDirectory() (string, error)

DataApplicationDirectory returns the expanded data application directory ($XDG_DATA_HOME/llm-router else ~/.local/share).

func DefaultTemplate added in v0.4.0

func DefaultTemplate() string

DefaultTemplate renders the default .env content. .env.example mirrors it.

func EnsureParentDirectory added in v0.4.0

func EnsureParentDirectory(path string) error

EnsureParentDirectory creates the parent of path when missing and managed, requires it when missing and unmanaged, and does nothing when present. Relative parents (".") always exist. Custom directories never gain directories implicitly: a missing custom parent returns ErrParentMissing.

func ExpandPath added in v0.4.0

func ExpandPath(path string) (string, error)

ExpandPath resolves a leading tilde, Windows %NAME% references and POSIX $VAR/${VAR} references in path, then cleans the result.

Tilde expansion is platform-agnostic and applies only at position zero: "~" alone returns the home directory, "~/" and "~\" join the home directory with the remainder. "~other/..." returns ErrUnsupportedTilde. A tilde elsewhere ("/test/~") stays literal. Tilde expansion runs once before variable expansion with no re-scan, so values introduced by variables never gain tilde treatment.

Percent and dollar expansion run on every OS. "%NAME%" with NAME=[A-Za-z0-9_]+ resolves through the process environment (missing resolves to empty, "%%" resolves to "%", a lone "%" stays literal). "$VAR" and "${VAR}" resolve through os.ExpandEnv (missing resolves to empty).

Empty input returns empty without error. Non-empty results return with filepath.Clean applied; Windows drive, UNC and backslash forms survive because Clean is OS-aware.

Mirror: scripts/shared/expand.go carries the same semantics for the scripts module. The two files stay in sync; stability tests in both modules lock the behavior.

func IsManagedPath added in v0.4.0

func IsManagedPath(path string) bool

IsManagedPath reports whether path sits inside one of the four managed application directories. Both the XDG-resolved and the home-fallback locations count as managed, so generated home-relative templates keep working when an XDG override points elsewhere. Unresolvable bases report false (fail closed).

func ReplaceDefaultFile added in v0.6.1

func ReplaceDefaultFile(target string) error

ReplaceDefaultFile writes DefaultTemplate to target and overwrites an existing file. Managed parent directories are created.

func ResolveDotenvPath added in v0.4.0

func ResolveDotenvPath() string

ResolveDotenvPath returns the dotenv path: ENV_FILE or the prod XDG default.

func StateApplicationDirectory added in v0.4.0

func StateApplicationDirectory() (string, error)

StateApplicationDirectory returns the expanded state application directory ($XDG_STATE_HOME/llm-router else ~/.local/state).

func WriteDefaultFile added in v0.4.0

func WriteDefaultFile(target string) error

WriteDefaultFile writes DefaultTemplate to target. It fails when the target exists or the path is blank. Managed configuration parents are created; custom parents must exist.

Types

type Config

type Config struct {
	// Addr is the address the single HTTP server binds to (e.g. "localhost:8080").
	// Dashboard SPA, dashboard JSON API (/api) and OpenAI-compatible API
	// (/v1) share this listener; routing splits by path prefix.
	Addr string

	// DBPath is the path to the SQLite database file.
	DBPath string

	// CachePath is the path to the SQLite cache file. The cache holds
	// rebuildable state only: deleting it while stopped never loses
	// configuration, and startup recreates it empty.
	CachePath string

	// EventsPath is the path to the SQLite events file. The events file
	// holds operator telemetry only: deleting it while stopped loses log
	// history and nothing else.
	EventsPath string

	// EventsRetentionDays bounds event history. Pruning deletes rows older
	// than this many days on startup and hourly.
	EventsRetentionDays int

	// LogLevel bounds operator telemetry: events below this severity are
	// neither rendered nor persisted.
	LogLevel LogLevel

	// AdminAddr is the address of the optional admin listener (always
	// loopback, e.g. "127.0.0.1:38082"). It serves the same JSON API
	// without authentication or bootstrapping. Empty disables it.
	AdminAddr string

	// DevUIRedirect, when non-empty, is the origin (e.g. "http://localhost:8080")
	// that the dashboard 302-redirects browser navigations to instead of
	// serving its own embedded SPA. Set through DEV_UI_REDIRECT by `make start`
	// in dev; empty disables the redirect — the normal/production behavior.
	DevUIRedirect string

	// LuaPoolBucketSize caps idle Lua states stored per plugin bucket.
	// Zero disables pooling; every call builds a fresh state.
	LuaPoolBucketSize int

	// CredentialsKey is the base64 AES-256 key encrypting stored credential
	// data (CREDENTIALS_KEY). Empty falls back to CredentialsKeyFile.
	CredentialsKey string

	// CredentialsKeyFile holds the key when CredentialsKey is empty
	// (CREDENTIALS_KEY_FILE). A missing file is created with a fresh random
	// key and mode 0600 on first start.
	CredentialsKeyFile string

	// Version is the build version shown in the dashboard. Not read from
	// the environment: the serve command sets it from the stamped binary.
	Version string
}

Config is the central runtime configuration for llm-router. All values originate from environment variables with optional .env file support (see Load).

func Load added in v0.4.0

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

Load reads the dotenv file (when present) and builds Config from the resulting process environment. It returns the loaded file path or empty when no file was present.

func (*Config) Validate

func (configuration *Config) Validate() error

Validate checks that all required configuration fields are set.

type DotenvFile added in v0.6.1

type DotenvFile struct {
	Path string
}

DotenvFile edits one dotenv file line by line. Comments, blank lines and the order of untouched assignments survive every edit.

func (DotenvFile) Lookup added in v0.6.1

func (file DotenvFile) Lookup(name string) (string, bool, error)

Lookup returns the last assignment of name. Found is false when the file or the assignment is missing.

func (DotenvFile) Set added in v0.6.1

func (file DotenvFile) Set(name, value string) error

Set replaces the last assignment of name or appends one. A missing file starts from the default template.

func (DotenvFile) Unset added in v0.6.1

func (file DotenvFile) Unset(name string) (bool, error)

Unset removes every assignment of name and reports whether one existed. A missing file is not an error.

type Key added in v0.6.1

type Key struct {
	Name        string
	Default     string
	Description string
	// contains filtered or unexported fields
}

Key describes one deployment setting stored in the dotenv file. The table below is the single owner of names, defaults and validation: the default template, `llm-router config` and the help text all derive from it.

func Keys added in v0.6.1

func Keys() []Key

Keys returns the configuration keys in display order.

func LookupKey added in v0.6.1

func LookupKey(name string) (Key, bool)

LookupKey finds a key by name, ignoring case.

func (Key) Normalize added in v0.6.1

func (key Key) Normalize(raw string) (string, error)

Normalize validates raw and returns the canonical text stored in the dotenv file. A blank value fails: unset the key to restore the default.

type LogLevel

type LogLevel string

LogLevel bounds log verbosity for stderr display and events persistence. Parsed from environment text.

const (
	LogLevelDebug LogLevel = "debug"
	LogLevelInfo  LogLevel = "info"
	LogLevelWarn  LogLevel = "warn"
	LogLevelError LogLevel = "error"
)

func (*LogLevel) Set

func (l *LogLevel) Set(value string) error

func (LogLevel) SlogLevel

func (l LogLevel) SlogLevel() slog.Level

SlogLevel returns the slog.Level for this LogLevel.

func (*LogLevel) String

func (l *LogLevel) String() string

func (*LogLevel) Type

func (l *LogLevel) Type() string

type Port

type Port uint16

Port is a TCP port number (1-65535) parsed from environment text.

func (*Port) Set

func (p *Port) Set(value string) error

func (*Port) String

func (p *Port) String() string

func (*Port) Type

func (p *Port) Type() string

type Setting added in v0.6.1

type Setting struct {
	Key    Key
	Value  string
	Source Source
}

Setting is one key with its effective value and the place it comes from.

func ResolveSettings added in v0.6.1

func ResolveSettings(path string) ([]Setting, error)

ResolveSettings returns every key with its effective value. Process environment wins over the file, the file wins over the default. Blank values count as unset, matching Load.

type Source added in v0.6.1

type Source string

Source names where an effective setting value comes from.

const (
	SourceEnvironment Source = "env"
	SourceFile        Source = "file"
	SourceDefault     Source = "default"
)

Jump to

Keyboard shortcuts

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