sonda/internal/config/config.go
tgiachi 46463846b3 feat(library): named media libraries managed through the API
- feat(storage): libraries table (name, path); audio_files points at a library
  by id instead of repeating the root path; migration 0005 for both drivers
  turns every existing root into a library and keeps file ids, tracks and the
  missing flag
- feat(library): Libraries service validates names and paths: absolute, an
  existing directory, never the filesystem root, never inside or around
  another library (checked on real paths, so symlinks cannot hide an overlap)
- feat(api): admin-only GET/POST /libraries, PATCH/DELETE /libraries/{id} and
  POST /libraries/{id}/scan; deleting a library drops its index entries and
  keeps tracks and listening history
- feat(library): the scanner and the scan manager work on libraries; scanning
  with no libraries answers 409 no_libraries
- feat(streaming): the library directory comes from the database instead of
  a configured list of roots
- breaking(config): library.roots is removed; an old config fails with a hint
  to use POST /api/v1/libraries
- test: CRUD and duplicates on both databases, path change keeps files,
  upgrade of a database written before libraries existed
2026-11-11 13:30:25 +01:00

189 lines
5.4 KiB
Go

// Package config loads and validates the sondad configuration.
//
// Precedence: built-in defaults, then the TOML file, then environment variables.
package config
import (
"bytes"
"errors"
"fmt"
"os"
"time"
"github.com/pelletier/go-toml/v2"
)
const minJWTSecretLen = 32
// Config is the full sondad configuration.
type Config struct {
Server Server `toml:"server"`
Library Library `toml:"library"`
Database Database `toml:"database"`
Log Log `toml:"log"`
Auth Auth `toml:"auth"`
Providers Providers `toml:"providers"`
}
// Server holds HTTP listener settings.
type Server struct {
Listen string `toml:"listen"`
}
// Library holds scanner settings. The libraries themselves (name and path) live
// in the database and are managed through the API.
type Library struct {
ScanWorkers int `toml:"scan_workers"` // parallel tag readers per scan
}
// Database selects and configures the storage backend.
//
// Driver is "sqlite" (uses Path) or "postgres" (uses DSN).
type Database struct {
Driver string `toml:"driver"`
Path string `toml:"path"`
DSN string `toml:"dsn"`
}
// Log holds logging settings. Env is "dev" or "production".
type Log struct {
Env string `toml:"env"`
}
// Auth holds token settings. JWTSecret must be long and random,
// for example: openssl rand -hex 32.
type Auth struct {
JWTSecret string `toml:"jwt_secret"`
AccessTTLMinutes int `toml:"access_ttl_minutes"` // lifetime of an access token
RefreshTTLHours int `toml:"refresh_ttl_hours"` // lifetime of a refresh token
}
// AccessTTL returns the access token lifetime.
func (a Auth) AccessTTL() time.Duration {
return time.Duration(a.AccessTTLMinutes) * time.Minute
}
// RefreshTTL returns the refresh token lifetime.
func (a Auth) RefreshTTL() time.Duration {
return time.Duration(a.RefreshTTLHours) * time.Hour
}
// Providers holds external provider settings.
type Providers struct {
LastFM LastFM `toml:"lastfm"`
}
// LastFM holds the Last.fm API settings.
type LastFM struct {
APIKey string `toml:"api_key"`
}
// Default returns the configuration used when nothing else is set.
func Default() Config {
return Config{
Server: Server{Listen: "127.0.0.1:8080"},
Library: Library{ScanWorkers: 4},
Database: Database{Driver: "sqlite", Path: "sonda.db"},
Log: Log{Env: "production"},
Auth: Auth{AccessTTLMinutes: 15, RefreshTTLHours: 720}, // 15 minutes, 30 days
}
}
// Load builds a Config from defaults, the TOML file at path, and environment
// variables. An empty path skips the file. Unknown keys in the file are errors.
func Load(path string) (Config, error) {
cfg := Default()
if path != "" {
data, err := os.ReadFile(path)
if err != nil {
return Config{}, fmt.Errorf("read config: %w", err)
}
dec := toml.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
if err := dec.Decode(&cfg); err != nil {
return Config{}, explainDecodeError(path, err)
}
}
applyEnv(&cfg)
return cfg, nil
}
func applyEnv(cfg *Config) {
if v := os.Getenv("SONDA_ENV"); v != "" {
cfg.Log.Env = v
}
if v := os.Getenv("SONDA_LISTEN"); v != "" {
cfg.Server.Listen = v
}
if v := os.Getenv("SONDA_DB_DRIVER"); v != "" {
cfg.Database.Driver = v
}
if v := os.Getenv("SONDA_DB_PATH"); v != "" {
cfg.Database.Path = v
}
if v := os.Getenv("SONDA_DB_DSN"); v != "" {
cfg.Database.DSN = v
}
if v := os.Getenv("SONDA_JWT_SECRET"); v != "" {
cfg.Auth.JWTSecret = v
}
if v := os.Getenv("SONDA_LASTFM_API_KEY"); v != "" {
cfg.Providers.LastFM.APIKey = v
}
}
// Validate checks that the configuration is usable.
func (c Config) Validate() error {
var errs []error
if c.Server.Listen == "" {
errs = append(errs, errors.New("server.listen is required"))
}
switch c.Database.Driver {
case "sqlite":
if c.Database.Path == "" {
errs = append(errs, errors.New("database.path is required for the sqlite driver"))
}
case "postgres":
if c.Database.DSN == "" {
errs = append(errs, errors.New("database.dsn is required for the postgres driver"))
}
default:
errs = append(errs, fmt.Errorf("database.driver must be \"sqlite\" or \"postgres\", got %q", c.Database.Driver))
}
if c.Log.Env != "dev" && c.Log.Env != "production" {
errs = append(errs, fmt.Errorf("log.env must be \"dev\" or \"production\", got %q", c.Log.Env))
}
if len(c.Auth.JWTSecret) < minJWTSecretLen {
errs = append(errs, fmt.Errorf("auth.jwt_secret must be at least %d characters (try: openssl rand -hex 32)", minJWTSecretLen))
}
if c.Auth.AccessTTLMinutes <= 0 {
errs = append(errs, errors.New("auth.access_ttl_minutes must be greater than 0"))
}
if c.Auth.RefreshTTLHours <= 0 {
errs = append(errs, errors.New("auth.refresh_ttl_hours must be greater than 0"))
}
if c.Library.ScanWorkers < 1 {
errs = append(errs, errors.New("library.scan_workers must be at least 1"))
}
return errors.Join(errs...)
}
// explainDecodeError turns the strict decoder's "unknown key" into something
// useful for the one key that used to exist.
func explainDecodeError(path string, err error) error {
var missing *toml.StrictMissingError
if errors.As(err, &missing) {
for _, e := range missing.Errors {
key := e.Key()
if len(key) == 2 && key[0] == "library" && key[1] == "roots" {
return fmt.Errorf("parse config %s: library.roots was removed; "+
"remove it and add each directory as a library with POST /api/v1/libraries", path)
}
}
}
return fmt.Errorf("parse config %s: %w", path, err)
}