config

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 19 Imported by: 0 modules, 0 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.

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

View Source
const (
	DefaultPort        = 8080
	DefaultMaxBackups  = 3
	DefaultLogBackups  = 5
	DefaultSerialSpeed = 9600
	DefaultDataBits    = 8
)

Numeric defaults (spec 3).

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

View Source
const Wildcard = "*"

Wildcard stands for an object ID in key paths ("devices.*.interval").

Variables

View Source
var ErrNoUnit = errors.New("needs a unit")

ErrNoUnit is returned for durations, sizes and energies given without a unit.

View Source
var IDPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`)

IDPattern is the pattern of connection, device and meter IDs.

Functions

func Defaults

func Defaults() map[string]any

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

func Export(r *Result) ([]byte, error)

Export renders the configured layers (without defaults) as YAML in the file form. Secrets are masked; references (${env:…}, ${file:…}) are kept.

func IsClockTime

func IsClockTime(s string) bool

IsClockTime reports whether s is a strict HH:MM time of day.

func IsSecretRef

func IsSecretRef(s string) bool

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

func ObjectDefaults() map[string]map[string]any

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

func ParsePrefix(s string) (netip.Prefix, error)

ParsePrefix reads a trusted proxy as an IP address (a single-address prefix) or CIDR.

func SecretPaths

func SecretPaths() map[string][]string

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.

func Validate

func Validate(cfg *Config, rules ...Rule) error

Validate runs the structural checks and every rule and reports all problems at once.

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

type DeviceAuth struct {
	User     string `koanf:"user"`
	Password Secret `koanf:"password"`
}

DeviceAuth holds device credentials; the password is a Secret.

type Duration

type Duration time.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

func ParseDuration(s string) (Duration, error)

ParseDuration parses a duration with unit, see Duration.

func (Duration) D

func (d Duration) D() time.Duration

D returns the value as time.Duration.

func (Duration) String

func (d Duration) String() string

String renders the duration in Go notation.

type Energy

type Energy float64

Energy is an energy in Wh written with a unit: "10kWh", "500 Wh", "1.2MWh".

func ParseEnergy

func ParseEnergy(s string) (Energy, error)

ParseEnergy parses an energy with unit.

func (Energy) Wh

func (e Energy) Wh() float64

Wh returns the energy in watt-hours.

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 Problem

type Problem struct {
	Path    string `json:"path"`
	Message string `json:"message"`
}

Problem is one validation finding with the key path it refers to.

func (Problem) String

func (p Problem) String() string

type Problems

type Problems []Problem

Problems is a list of findings.

func CheckLayer

func CheckLayer(layer map[string]any) Problems

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.

func (Problems) Err

func (ps Problems) Err() error

Err returns nil for no problems, else a *ValidationError sorted by path.

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

func Load(src Source, rules ...Rule) (*Result, error)

Load merges defaults → DB → file → env, decodes and validates. Problems are returned as one *ValidationError listing every problem with its path.

func (*Result) Locked

func (r *Result) Locked(path string) bool

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

func (r *Result) Object(section, id string) (map[string]any, bool)

Object returns the configured body of an object from the merged layers, secrets masked (references kept), or false.

func (*Result) ObjectIDs

func (r *Result) ObjectIDs(section string) []string

ObjectIDs returns the IDs of a section's objects in the merged layers.

func (*Result) Value

func (r *Result) Value(key string) any

Value returns the effective value of a global key: configured or default.

type Rule

type Rule func(cfg *Config) Problems

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 NewSecret

func NewSecret(v string) Secret

NewSecret wraps a plain value.

func (Secret) IsSet

func (s Secret) IsSet() bool

IsSet reports whether the secret has a value.

func (Secret) MarshalJSON

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

MarshalJSON masks the secret.

func (Secret) MarshalText

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

MarshalText masks the secret (YAML export, zerolog).

func (Secret) String

func (s Secret) String() string

String masks the secret.

func (Secret) Value

func (s Secret) Value() string

Value returns the plain secret for the component that needs it.

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

func ParseSize

func ParseSize(s string) (Size, error)

ParseSize parses a byte size with unit.

func (Size) MB

func (s Size) MB() int

MB returns the size in whole megabytes, at least 1 for a non-zero size.

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

Jump to

Keyboard shortcuts

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