// 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 S3Endpoint string S3Region string S3Bucket string S3AccessKey string S3SecretKey string S3Timeout time.Duration MaxUploadBytes int64 MaxImagePixels int64 DecodeConcurrency int PutConcurrency int TempDir string } // Load reads and validates the full API configuration. func Load() (Config, error) { return load(true, true) } // LoadMigrate loads only what the one-shot migration command needs. func LoadMigrate() (Config, error) { return load(false, false) } // LoadTool loads the database and S3 configuration used by the offline // reconciler and the bucket/test tools; Valkey is not required. func LoadTool() (Config, error) { return load(false, true) } // load is the shared parser. requireCache and requireS3 select which optional // dependency blocks are mandatory for the calling command. func load(requireCache, requireS3 bool) (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 if requireCache { 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 if requireS3 { if err := loadS3(&cfg); err != nil { return Config{}, err } } return cfg, nil } // loadS3 parses the private object store configuration and the image limits // that must be enforced before any unbounded read or decode. func loadS3(cfg *Config) error { endpoint, err := secret("S3_ENDPOINT") if err != nil { return err } cfg.S3Endpoint = endpoint cfg.S3Region = envString("S3_REGION", "us-east-1") cfg.S3Bucket = envString("S3_BUCKET", "messenger-attachments") if !validBucketName(cfg.S3Bucket) { return fmt.Errorf("S3_BUCKET: must match [a-z0-9][a-z0-9.-]{1,61}[a-z0-9]") } accessKey, err := secret("S3_ACCESS_KEY") if err != nil { return err } secretKey, err := secret("S3_SECRET_KEY") if err != nil { return err } cfg.S3AccessKey = accessKey cfg.S3SecretKey = secretKey timeout, err := envDurationSeconds("S3_TIMEOUT_SECONDS", 10, 5, 120) if err != nil { return err } cfg.S3Timeout = timeout maxUpload, err := envInt64("MAX_UPLOAD_BYTES", 10*1024*1024) if err != nil { return fmt.Errorf("MAX_UPLOAD_BYTES: %w", err) } if maxUpload < 1 || maxUpload > 10*1024*1024 { return fmt.Errorf("MAX_UPLOAD_BYTES: must be between 1 and 10485760") } cfg.MaxUploadBytes = maxUpload maxPixels, err := envInt64("MAX_IMAGE_PIXELS", 40_000_000) if err != nil { return fmt.Errorf("MAX_IMAGE_PIXELS: %w", err) } if maxPixels < 1 || maxPixels > 40_000_000 { return fmt.Errorf("MAX_IMAGE_PIXELS: must be between 1 and 40000000") } cfg.MaxImagePixels = maxPixels concurrency, err := envInt("UPLOAD_DECODE_CONCURRENCY", 1) if err != nil { return fmt.Errorf("UPLOAD_DECODE_CONCURRENCY: %w", err) } if concurrency < 1 || concurrency > 4 { return fmt.Errorf("UPLOAD_DECODE_CONCURRENCY: must be between 1 and 4") } cfg.DecodeConcurrency = concurrency // The single-node SeaweedFS stand was verified stable at one concurrent // PUT per API replica; two concurrent multi-megabyte writes could restart // it. Uploads queue after their body was already streamed to a bounded // temporary file, so queuing does not add unbounded RAM. putConcurrency, err := envInt("S3_PUT_CONCURRENCY", 1) if err != nil { return fmt.Errorf("S3_PUT_CONCURRENCY: %w", err) } if putConcurrency != 1 { return fmt.Errorf("S3_PUT_CONCURRENCY: must be 1 on this single-node stand") } cfg.PutConcurrency = putConcurrency cfg.TempDir = envString("UPLOAD_TEMP_DIR", "") return nil } func validBucketName(value string) bool { if len(value) < 3 || len(value) > 63 { return false } for i := 0; i < len(value); i++ { c := value[i] if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '-' { continue } return false } return value[0] != '.' && value[0] != '-' && value[len(value)-1] != '.' && value[len(value)-1] != '-' } // 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 envInt64(key string, fallback int64) (int64, error) { raw, ok := os.LookupEnv(key) if !ok || strings.TrimSpace(raw) == "" { return fallback, nil } value, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64) 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) } }