Lab3 baseline: HAProxy, replicated stateless API, shared PostgreSQL/Valkey, idempotent messages
This commit is contained in:
@@ -0,0 +1,245 @@
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var allKeys = []string{
|
||||
"APP_HOST", "APP_PORT", "APP_ENV", "LOG_LEVEL", "SESSION_TTL_SECONDS",
|
||||
"DB_MAX_CONNS", "DB_MIN_CONNS", "DB_CONNECT_TIMEOUT_SECONDS",
|
||||
"DB_STATEMENT_TIMEOUT_SECONDS", "DB_QUERY_TIMEOUT_SECONDS",
|
||||
"CACHE_POOL_SIZE", "CACHE_TIMEOUT_SECONDS", "SHUTDOWN_TIMEOUT_SECONDS",
|
||||
"STARTUP_TIMEOUT_SECONDS", "DATABASE_URL", "DATABASE_URL_FILE",
|
||||
"CACHE_URL", "CACHE_URL_FILE",
|
||||
}
|
||||
|
||||
func clearEnvironment(t *testing.T) {
|
||||
t.Helper()
|
||||
for _, key := range allKeys {
|
||||
t.Setenv(key, "")
|
||||
}
|
||||
}
|
||||
|
||||
func baseEnvironment(t *testing.T) {
|
||||
t.Helper()
|
||||
clearEnvironment(t)
|
||||
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres:5432/db?sslmode=disable")
|
||||
t.Setenv("CACHE_URL", "redis://:pass@valkey:6379/0")
|
||||
}
|
||||
|
||||
func TestLoadDefaults(t *testing.T) {
|
||||
baseEnvironment(t)
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.Port != 8080 || cfg.SessionTTL != time.Hour {
|
||||
t.Fatalf("unexpected defaults: %+v", cfg)
|
||||
}
|
||||
if cfg.DBMaxConns != 8 || cfg.DBMinConns != 1 || cfg.QueryTimeout != 3*time.Second {
|
||||
t.Fatalf("unexpected pool defaults: %+v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadReadsSecretsFromFiles(t *testing.T) {
|
||||
clearEnvironment(t)
|
||||
directory := t.TempDir()
|
||||
databaseFile := filepath.Join(directory, "database_url")
|
||||
cacheFile := filepath.Join(directory, "cache_url")
|
||||
if err := os.WriteFile(databaseFile, []byte("postgres://file:secret@postgres/db\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(cacheFile, []byte("redis://:file-secret@valkey:6379/0\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("DATABASE_URL_FILE", databaseFile)
|
||||
t.Setenv("CACHE_URL_FILE", cacheFile)
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.DatabaseURL != "postgres://file:secret@postgres/db" {
|
||||
t.Fatalf("database URL was not read from file: %q", cfg.DatabaseURL)
|
||||
}
|
||||
if cfg.CacheURL != "redis://:file-secret@valkey:6379/0" {
|
||||
t.Fatalf("cache URL was not read from file: %q", cfg.CacheURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsInvalidValues(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
key string
|
||||
value string
|
||||
}{
|
||||
{"zero ttl", "SESSION_TTL_SECONDS", "0"},
|
||||
{"huge ttl", "SESSION_TTL_SECONDS", "99999999"},
|
||||
{"zero port", "APP_PORT", "0"},
|
||||
{"bad log level", "LOG_LEVEL", "verbose"},
|
||||
{"zero max conns", "DB_MAX_CONNS", "0"},
|
||||
{"min above max", "DB_MIN_CONNS", "9"},
|
||||
{"bad timeout", "DB_QUERY_TIMEOUT_SECONDS", "0"},
|
||||
{"bad int", "APP_PORT", "eighty"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
baseEnvironment(t)
|
||||
t.Setenv(tc.key, tc.value)
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatalf("Load accepted %s=%q", tc.key, tc.value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRequiresDatabaseAndCacheURLs(t *testing.T) {
|
||||
clearEnvironment(t)
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatal("Load accepted missing DATABASE_URL/CACHE_URL")
|
||||
}
|
||||
t.Setenv("DATABASE_URL", "postgres://user:pass@postgres/db")
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatal("Load accepted missing CACHE_URL")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShutdownTimeoutIsClamped(t *testing.T) {
|
||||
baseEnvironment(t)
|
||||
t.Setenv("SHUTDOWN_TIMEOUT_SECONDS", "60")
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if cfg.ShutdownTimeout != MaxShutdownTimeout {
|
||||
t.Fatalf("shutdown timeout = %v, want clamp to %v", cfg.ShutdownTimeout, MaxShutdownTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecretFileErrorsDoNotLeakThePath(t *testing.T) {
|
||||
clearEnvironment(t)
|
||||
t.Setenv("DATABASE_URL_FILE", "/nonexistent/path/database_url")
|
||||
_, err := Load()
|
||||
if err == nil {
|
||||
t.Fatal("Load accepted a missing secret file")
|
||||
}
|
||||
if got := err.Error(); got != "DATABASE_URL_FILE: cannot read referenced file" {
|
||||
t.Fatalf("error leaks path: %q", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user