Documentation
¶
Overview ¶
Package config loads the layered configuration (defaults → DB → file → env), decodes it into typed sections and validates its structure. Domain rules are injected as Rules by internal/app; this package imports no domain package (AGENTS.md section 3).
Index ¶
- Constants
- Variables
- func Defaults() map[string]any
- func Export(r *Result) ([]byte, error)
- func IsClockTime(s string) bool
- func IsSecretRef(s string) bool
- func KnownKeys() []string
- func ObjectDefaults() map[string]map[string]any
- func ParsePrefix(s string) (netip.Prefix, error)
- func SecretPaths() map[string][]string
- func UISettingKeys() []string
- func Validate(cfg *Config, rules ...Rule) error
- type App
- type Auth
- type Config
- type Connection
- type Device
- type DeviceAuth
- type Duration
- type Energy
- type Log
- type Meter
- type Problem
- type Problems
- type Result
- type Rule
- type Secret
- type Site
- type Size
- type Source
- type Status
- type Storage
- type ValidationError
Constants ¶
const ( DefaultPort = 8080 DefaultMaxBackups = 3 DefaultLogBackups = 5 DefaultSerialSpeed = 9600 DefaultDataBits = 8 )
Numeric defaults (spec 3).
const EnvPrefix = "PVMON_"
EnvPrefix is the prefix of environment overrides. Nesting uses a double underscore: PVMON_APP__LOG_LEVEL → app.log_level, PVMON_DEVICES__WR1__INTERVAL → devices.wr1.interval.
const Wildcard = "*"
Wildcard stands for an object ID in key paths ("devices.*.interval").
Variables ¶
var ErrNoUnit = errors.New("needs a unit")
ErrNoUnit is returned for durations, sizes and energies given without a unit.
var IDPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`)
IDPattern is the pattern of connection, device and meter IDs.
Functions ¶
func Defaults ¶
Defaults returns the default of every global key (flat koanf paths). A test enforces that every key of Config has one, here or in ObjectDefaults.
func Export ¶
Export renders the configured layers (without defaults) as YAML in the file form. Secrets are masked; references (${env:…}, ${file:…}) are kept.
func IsClockTime ¶
IsClockTime reports whether s is a strict HH:MM time of day.
func IsSecretRef ¶
IsSecretRef reports whether s is a ${env:NAME} or ${file:/path} reference.
func KnownKeys ¶
func KnownKeys() []string
KnownKeys returns every leaf key path of Config, with Wildcard for object IDs.
func ObjectDefaults ¶
ObjectDefaults returns the defaults applied to every object of a kind (connections, devices, meters), keyed by kind and then by the key inside the object. Empty strings mean "taken from elsewhere" (connection timeout, profile read mode, profile netting).
func ParsePrefix ¶
ParsePrefix reads a trusted proxy as an IP address (a single-address prefix) or CIDR.
func SecretPaths ¶
SecretPaths returns the secret key paths inside the objects of each section ("devices" → ["auth.password"]).
func UISettingKeys ¶
func UISettingKeys() []string
UISettingKeys are the settings the UI may change. They apply without restart; the rest (port, paths, logging, sessions, proxies) only in config.yaml or env.
Types ¶
type App ¶
type App struct {
Port int `koanf:"port"`
LogLevel string `koanf:"log_level"`
RequestTimeout Duration `koanf:"request_timeout"`
TrustedProxies []string `koanf:"trusted_proxies"`
}
App holds the app.* settings.
type Auth ¶
type Auth struct {
PublicRead bool `koanf:"public_read"`
SessionIdle Duration `koanf:"session_idle"`
SessionMax Duration `koanf:"session_max"`
}
Auth holds the auth.* settings.
type Config ¶
type Config struct {
App App `koanf:"app"`
Auth Auth `koanf:"auth"`
Storage Storage `koanf:"storage"`
Status Status `koanf:"status"`
Log Log `koanf:"log"`
Site Site `koanf:"site"`
Connections map[string]Connection `koanf:"connections"`
Devices map[string]Device `koanf:"devices"`
Meters map[string]Meter `koanf:"meters"`
}
Config is the effective configuration. Field tags are the YAML/koanf keys.
type Connection ¶
type Connection struct {
Address string `koanf:"address"`
Timeout Duration `koanf:"timeout"`
Speed int `koanf:"speed"`
DataBits int `koanf:"data_bits"`
Parity string `koanf:"parity"`
StopBits int `koanf:"stop_bits"`
}
Connection is one physical access path (spec 2).
type Device ¶
type Device struct {
Connection string `koanf:"connection"`
Address string `koanf:"address"`
Unit int `koanf:"unit"`
Profile string `koanf:"profile"`
// Interval overrides site.interval for this device; 0 = the site interval.
Interval Duration `koanf:"interval"`
Timeout Duration `koanf:"timeout"`
Read string `koanf:"read"`
Rollover string `koanf:"rollover"`
Netting string `koanf:"netting"`
History []string `koanf:"history"`
InsecureTLS bool `koanf:"insecure_tls"`
Auth DeviceAuth `koanf:"auth"`
}
Device is a polled device: a connection (by ID or inline address) plus profile.
type DeviceAuth ¶
DeviceAuth holds device credentials; the password is a Secret.
type Duration ¶
Duration is a time.Duration that must be written with a unit; besides Go's units it accepts d (24h) and y (365d): "5s", "30d", "10y", "1h30m".
func ParseDuration ¶
ParseDuration parses a duration with unit, see Duration.
type Energy ¶
type Energy float64
Energy is an energy in Wh written with a unit: "10kWh", "500 Wh", "1.2MWh".
func ParseEnergy ¶
ParseEnergy parses an energy with unit.
type Log ¶
type Log struct {
File string `koanf:"file"`
MaxSize Size `koanf:"max_size"`
MaxBackups int `koanf:"max_backups"`
MaxAge Duration `koanf:"max_age"`
RotateAt []string `koanf:"rotate_at"`
Compression string `koanf:"compression"`
}
Log holds the log.* settings (spec 3).
type Meter ¶
type Meter struct {
Device string `koanf:"device"`
Source string `koanf:"source"`
Role string `koanf:"role"`
Category string `koanf:"category"`
Parent string `koanf:"parent"`
Label string `koanf:"label"`
KWp float64 `koanf:"kwp"`
Capacity Energy `koanf:"capacity"`
Critical bool `koanf:"critical"`
}
Meter is a logical measuring point provided by one device block (spec 2).
type Problems ¶
type Problems []Problem
Problems is a list of findings.
func CheckLayer ¶
CheckLayer reports the keys of a DB layer that match no configuration key, so the UI cannot store keys that would only be warned about.
type Result ¶
type Result struct {
Config *Config
Dir string // directory of the config file; base for relative profile paths
FileKeys []string // keys defined in the file layer (read-only in the UI)
EnvKeys []string // keys set by environment variables (read-only in the UI)
Layers map[string]any // merged layers without defaults, secrets as given (export)
Warnings []string // unknown or removed keys
}
Result is a loaded and validated configuration.
func Load ¶
Load merges defaults → DB → file → env, decodes and validates. Problems are returned as one *ValidationError listing every problem with its path.
func (*Result) Locked ¶
Locked reports whether path (a setting such as "site.name" or an object such as "devices.wr1") is defined by the file or env layer and therefore read-only in the UI.
func (*Result) Object ¶
Object returns the configured body of an object from the merged layers, secrets masked (references kept), or false.
type Rule ¶
Rule is a domain rule injected by internal/app (spec: config imports no domain package).
type Secret ¶
type Secret struct {
// contains filtered or unexported fields
}
Secret is a credential. Its value never appears in String, JSON or logs.
func (Secret) MarshalJSON ¶
MarshalJSON masks the secret.
func (Secret) MarshalText ¶
MarshalText masks the secret (YAML export, zerolog).
type Site ¶
type Site struct {
Name string `koanf:"name"`
// Interval is the poll interval of every device that does not set its own.
Interval Duration `koanf:"interval"`
}
Site holds the site.* settings.
type Size ¶
type Size int64
Size is a byte size written with a unit: "50MB", "512 KB", "1GB" (decimal units).
type Source ¶
type Source struct {
File string // config.yaml path, "" = none
Data []byte // file layer given as YAML bytes instead of File (simulate)
DB map[string]any // UI layer from configstore (flat or nested keys)
Environ []string // KEY=VALUE pairs, normally os.Environ()
Getenv func(string) (string, bool)
ReadFile func(string) ([]byte, error)
}
Source describes the layers to load. Zero fields are skipped; Getenv and ReadFile default to the os functions and resolve ${env:…} / ${file:…} secret references.
type Status ¶
type Status struct {
OfflineAfter Duration `koanf:"offline_after"`
}
Status holds the status.* settings.
type Storage ¶
type Storage struct {
Path string `koanf:"path"`
Retention Duration `koanf:"retention"`
BackupInterval Duration `koanf:"backup_interval"`
MaxBackups int `koanf:"max_backups"`
}
Storage holds the storage.* settings.
type ValidationError ¶
type ValidationError struct {
Problems Problems
}
ValidationError carries every problem of a configuration.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string