Files
mtusi2026lab3/internal/config/config.go
T

246 lines
7.1 KiB
Go

// Package config loads the explicit runtime configuration of the lab3
// messenger. The container image stays immutable: the same image is configured
// through environment variables (or files referenced by *_FILE variables for
// operators that do not want secrets in the environment).
package config
import (
"fmt"
"log/slog"
"os"
"strconv"
"strings"
"time"
)
const (
// DefaultSessionTTL is the contract default of contracts/README.md.
DefaultSessionTTL = time.Hour
// MaxShutdownTimeout leaves headroom below the 10 second termination
// window promised by the previous lab and expected by the container
// checks, even if an operator overrides the environment variable.
MaxShutdownTimeout = 9 * time.Second
// MaxStartupTimeout bounds the initial PostgreSQL connectivity wait.
MaxStartupTimeout = 120 * time.Second
)
// Config is validated at startup. The process refuses to start with an
// invalid value instead of silently falling back to a different security or
// durability posture.
type Config struct {
Host string
Port int
Env string
LogLevel slog.Level
ShutdownTimeout time.Duration
ShutdownDrain time.Duration
StartupTimeout time.Duration
MetricsAddr string
DatabaseURL string
CacheURL string
SessionTTL time.Duration
DBMaxConns int32
DBMinConns int32
DBConnectTimeout time.Duration
DBStatementTimeout time.Duration
QueryTimeout time.Duration
CachePoolSize int
CacheTimeout time.Duration
}
// Load reads and validates the runtime configuration.
func Load() (Config, error) {
cfg := Config{
Host: envString("APP_HOST", "0.0.0.0"),
Env: envString("APP_ENV", "lab"),
ShutdownTimeout: 6 * time.Second,
ShutdownDrain: 3 * time.Second,
StartupTimeout: 30 * time.Second,
QueryTimeout: 3 * time.Second,
MetricsAddr: envString("METRICS_ADDR", "127.0.0.1:9090"),
}
port, err := envInt("APP_PORT", 8080)
if err != nil {
return Config{}, fmt.Errorf("APP_PORT: %w", err)
}
if port < 1 || port > 65535 {
return Config{}, fmt.Errorf("APP_PORT: must be between 1 and 65535")
}
cfg.Port = port
level, err := parseLogLevel(envString("LOG_LEVEL", "info"))
if err != nil {
return Config{}, fmt.Errorf("LOG_LEVEL: %w", err)
}
cfg.LogLevel = level
if strings.TrimSpace(cfg.Host) == "" {
return Config{}, fmt.Errorf("APP_HOST: must not be empty")
}
databaseURL, err := secret("DATABASE_URL")
if err != nil {
return Config{}, err
}
cfg.DatabaseURL = databaseURL
cacheURL, err := secret("CACHE_URL")
if err != nil {
return Config{}, err
}
cfg.CacheURL = cacheURL
seconds, err := envInt("SESSION_TTL_SECONDS", int(DefaultSessionTTL/time.Second))
if err != nil {
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS: %w", err)
}
if seconds < 1 || seconds > 30*24*60*60 {
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS: must be between 1 and 2592000")
}
cfg.SessionTTL = time.Duration(seconds) * time.Second
maxConns, err := envInt("DB_MAX_CONNS", 8)
if err != nil {
return Config{}, fmt.Errorf("DB_MAX_CONNS: %w", err)
}
if maxConns < 1 || maxConns > 100 {
return Config{}, fmt.Errorf("DB_MAX_CONNS: must be between 1 and 100")
}
cfg.DBMaxConns = int32(maxConns)
minConns, err := envInt("DB_MIN_CONNS", 1)
if err != nil {
return Config{}, fmt.Errorf("DB_MIN_CONNS: %w", err)
}
if minConns < 0 || minConns > maxConns {
return Config{}, fmt.Errorf("DB_MIN_CONNS: must be between 0 and DB_MAX_CONNS")
}
cfg.DBMinConns = int32(minConns)
if cfg.DBConnectTimeout, err = envDurationSeconds("DB_CONNECT_TIMEOUT_SECONDS", 3, 1, 30); err != nil {
return Config{}, err
}
if cfg.DBStatementTimeout, err = envDurationSeconds("DB_STATEMENT_TIMEOUT_SECONDS", 3, 1, 60); err != nil {
return Config{}, err
}
if cfg.QueryTimeout, err = envDurationSeconds("DB_QUERY_TIMEOUT_SECONDS", 3, 1, 60); err != nil {
return Config{}, err
}
cachePool, err := envInt("CACHE_POOL_SIZE", 8)
if err != nil {
return Config{}, fmt.Errorf("CACHE_POOL_SIZE: %w", err)
}
if cachePool < 1 || cachePool > 100 {
return Config{}, fmt.Errorf("CACHE_POOL_SIZE: must be between 1 and 100")
}
cfg.CachePoolSize = cachePool
if cfg.CacheTimeout, err = envDurationSeconds("CACHE_TIMEOUT_SECONDS", 2, 1, 30); err != nil {
return Config{}, err
}
shutdown, err := envDurationSeconds("SHUTDOWN_TIMEOUT_SECONDS", 6, 1, 60)
if err != nil {
return Config{}, err
}
if shutdown > MaxShutdownTimeout {
shutdown = MaxShutdownTimeout
}
cfg.ShutdownTimeout = shutdown
drain, err := envDurationSeconds("SHUTDOWN_DRAIN_SECONDS", 3, 0, 8)
if err != nil {
return Config{}, err
}
// The drain must finish before the hard shutdown window; otherwise a
// SIGTERM could spend the whole grace period advertising readiness and
// never reach http.Server.Shutdown.
if drain >= shutdown {
return Config{}, fmt.Errorf("SHUTDOWN_DRAIN_SECONDS must be smaller than SHUTDOWN_TIMEOUT_SECONDS")
}
cfg.ShutdownDrain = drain
startup, err := envDurationSeconds("STARTUP_TIMEOUT_SECONDS", 30, 1, 120)
if err != nil {
return Config{}, err
}
cfg.StartupTimeout = startup
return cfg, nil
}
// secret resolves NAME or NAME_FILE. A file is preferred when both are set so
// compose-style file secrets win over inherited environment values. Values are
// never echoed in error messages.
func secret(name string) (string, error) {
if path := strings.TrimSpace(os.Getenv(name + "_FILE")); path != "" {
data, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("%s_FILE: cannot read referenced file", name)
}
value := strings.TrimSpace(string(data))
if value == "" {
return "", fmt.Errorf("%s_FILE: referenced file is empty", name)
}
return value, nil
}
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
return value, nil
}
return "", fmt.Errorf("%s or %s_FILE is required", name, name)
}
func envString(key, fallback string) string {
// An environment variable set to an empty string is treated as unset; this
// keeps container defaults working when compose passes "" for an optional
// setting.
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
return value
}
return fallback
}
func envInt(key string, fallback int) (int, error) {
raw, ok := os.LookupEnv(key)
if !ok || strings.TrimSpace(raw) == "" {
return fallback, nil
}
value, err := strconv.Atoi(strings.TrimSpace(raw))
if err != nil {
return 0, fmt.Errorf("expected an integer, got %q", raw)
}
return value, nil
}
func envDurationSeconds(key string, fallback, minimum, maximum int) (time.Duration, error) {
value, err := envInt(key, fallback)
if err != nil {
return 0, fmt.Errorf("%s: %w", key, err)
}
if value < minimum || value > maximum {
return 0, fmt.Errorf("%s: must be between %d and %d", key, minimum, maximum)
}
return time.Duration(value) * time.Second, nil
}
func parseLogLevel(raw string) (slog.Level, error) {
switch strings.ToLower(strings.TrimSpace(raw)) {
case "debug":
return slog.LevelDebug, nil
case "info":
return slog.LevelInfo, nil
case "warn", "warning":
return slog.LevelWarn, nil
case "error":
return slog.LevelError, nil
default:
return 0, fmt.Errorf("expected debug, info, warn or error, got %q", raw)
}
}