// Package config reads the process configuration from the environment. // Settings have defaults suited to the lab stand, except credentials, which // are required and read from files named by *_FILE variables so that their // values never appear in the environment. An invalid value stops the process // at start-up with a message naming the variable, never the secret. package config import ( "fmt" "log/slog" "net" "os" "strconv" "strings" "time" ) // Allow a 30s binary request, its independent 3s cleanup, and 5s margin. const defaultShutdownTimeout = 38 * time.Second type Logging struct { Env string Level slog.Level } func (l Logging) NewLogger() *slog.Logger { opts := &slog.HandlerOptions{Level: l.Level} if l.Env == "dev" { return slog.New(slog.NewTextHandler(os.Stdout, opts)) } return slog.New(slog.NewJSONHandler(os.Stdout, opts)) } type Config struct { Logging Host string Port int ShutdownTimeout time.Duration MaxBodyBytes int64 DatabaseURL string SessionStoreURL string SessionTTL time.Duration // DrainDelay keeps a stopping process serving with readiness off; it must // exceed the balancer's detection time. DrainDelay time.Duration IdempotencyTTL time.Duration DBMaxConns int32 DebugAddr string S3 S3 } type Migrate struct { Logging DatabaseURL string } // Lookup reads one variable, reporting whether it was set; os.LookupEnv // in production, a map in tests. type Lookup func(key string) (string, bool) func Load(lookup Lookup) (Config, error) { cfg := Config{ Host: "0.0.0.0", Port: 8080, ShutdownTimeout: defaultShutdownTimeout, MaxBodyBytes: 64 * 1024, SessionTTL: time.Hour, DrainDelay: 2 * time.Second, IdempotencyTTL: 24 * time.Hour, DBMaxConns: 10, } if v, ok := lookup("APP_HOST"); ok { if strings.TrimSpace(v) == "" { return Config{}, fmt.Errorf("APP_HOST must not be empty") } cfg.Host = v } if v, ok := lookup("APP_PORT"); ok { port, err := strconv.Atoi(v) if err != nil || port < 1 || port > 65535 { return Config{}, fmt.Errorf("APP_PORT must be an integer between 1 and 65535, got %q", v) } cfg.Port = port } var err error if cfg.Logging, err = loadLogging(lookup); err != nil { return Config{}, err } if v, ok := lookup("APP_SHUTDOWN_TIMEOUT"); ok { d, err := time.ParseDuration(v) if err != nil || d <= 0 { return Config{}, fmt.Errorf("APP_SHUTDOWN_TIMEOUT must be a positive duration such as 8s, got %q", v) } cfg.ShutdownTimeout = d } if v, ok := lookup("APP_MAX_BODY_BYTES"); ok { n, err := strconv.ParseInt(v, 10, 64) if err != nil || n <= 0 { return Config{}, fmt.Errorf("APP_MAX_BODY_BYTES must be a positive integer, got %q", v) } cfg.MaxBodyBytes = n } if v, ok := lookup("SESSION_TTL_SECONDS"); ok { n, err := strconv.ParseUint(v, 10, 32) if err != nil || n == 0 { return Config{}, fmt.Errorf("SESSION_TTL_SECONDS must be a positive whole number of seconds, got %q", v) } cfg.SessionTTL = time.Duration(n) * time.Second } if v, ok := lookup("APP_DRAIN_DELAY"); ok { d, err := time.ParseDuration(v) if err != nil || d < 0 { return Config{}, fmt.Errorf("APP_DRAIN_DELAY must be a non-negative duration such as 2s, got %q", v) } cfg.DrainDelay = d } if v, ok := lookup("IDEMPOTENCY_TTL_SECONDS"); ok { n, err := strconv.ParseUint(v, 10, 32) if err != nil || n == 0 { return Config{}, fmt.Errorf("IDEMPOTENCY_TTL_SECONDS must be a positive whole number of seconds, got %q", v) } cfg.IdempotencyTTL = time.Duration(n) * time.Second } if v, ok := lookup("DB_MAX_CONNS"); ok { n, err := strconv.ParseInt(v, 10, 32) if err != nil || n < 1 || n > 1000 { return Config{}, fmt.Errorf("DB_MAX_CONNS must be an integer between 1 and 1000, got %q", v) } cfg.DBMaxConns = int32(n) } if v, ok := lookup("APP_DEBUG_ADDR"); ok && v != "" { if _, _, err := net.SplitHostPort(v); err != nil { return Config{}, fmt.Errorf("APP_DEBUG_ADDR must be host:port such as :9090, got %q", v) } cfg.DebugAddr = v } if cfg.DatabaseURL, err = LoadDatabaseURL(lookup); err != nil { return Config{}, err } if cfg.SessionStoreURL, err = secret(lookup, "SESSION_STORE_URL_FILE"); err != nil { return Config{}, err } if _, ok := lookup("S3_ENDPOINT"); ok { if cfg.S3, err = LoadS3(lookup); err != nil { return Config{}, err } } return cfg, nil } func LoadMigrate(lookup Lookup) (Migrate, error) { var cfg Migrate var err error if cfg.Logging, err = loadLogging(lookup); err != nil { return Migrate{}, err } if cfg.DatabaseURL, err = LoadDatabaseURL(lookup); err != nil { return Migrate{}, err } return cfg, nil } func LoadDatabaseURL(lookup Lookup) (string, error) { return secret(lookup, "DATABASE_URL_FILE") } func loadLogging(lookup Lookup) (Logging, error) { l := Logging{Env: "lab", Level: slog.LevelInfo} if v, ok := lookup("APP_ENV"); ok && strings.TrimSpace(v) != "" { l.Env = v } if v, ok := lookup("APP_LOG_LEVEL"); ok { if err := l.Level.UnmarshalText([]byte(v)); err != nil { return Logging{}, fmt.Errorf("APP_LOG_LEVEL must be debug, info, warn or error, got %q", v) } } return l, nil } // secret reads the file named by the variable; surrounding whitespace, // including the trailing newline editors add, is dropped. func secret(lookup Lookup, key string) (string, error) { path, ok := lookup(key) if !ok || strings.TrimSpace(path) == "" { return "", fmt.Errorf("%s must name a file with the value", key) } raw, err := os.ReadFile(path) if err != nil { return "", fmt.Errorf("%s: cannot read %s: %w", key, path, err) } value := strings.TrimSpace(string(raw)) if value == "" { return "", fmt.Errorf("%s: file %s is empty", key, path) } return value, nil } func (c Config) Addr() string { return net.JoinHostPort(c.Host, strconv.Itoa(c.Port)) }