package config import ( "log/slog" "os" "strconv" "strings" "time" ) type Config struct { Host string Port string Env string SessionTTLSeconds int DatabaseURL string CacheURL string SessionStore string LogLevel slog.Level ShutdownTimeout time.Duration CacheEnabled bool InstanceID string IdempotencyTTL time.Duration DrainDelay time.Duration DBPoolMax int32 CacheInvalidation string InternalAddr string } func Load() Config { return Config{ Host: getEnv("APP_HOST", "0.0.0.0"), Port: getEnv("APP_PORT", "8080"), Env: getEnv("APP_ENV", "lab"), SessionTTLSeconds: getInt("SESSION_TTL_SECONDS", 3600), DatabaseURL: readSecretFile("DATABASE_URL_FILE"), CacheURL: readSecretFile("CACHE_URL_FILE"), SessionStore: getEnv("SESSION_STORE", "postgres"), LogLevel: parseLevel(getEnv("LOG_LEVEL", "info")), ShutdownTimeout: parseDuration(getEnv("SHUTDOWN_TIMEOUT", "8s")), CacheEnabled: getEnv("CACHE_ENABLED", "true") == "true", InstanceID: instanceID(), IdempotencyTTL: time.Duration(getInt("IDEMPOTENCY_TTL_SECONDS", 86400)) * time.Second, DrainDelay: parseDuration(getEnv("DRAIN_DELAY", "3s")), DBPoolMax: int32(max(1, getInt("DB_POOL_MAX", 20))), CacheInvalidation: getEnv("CACHE_INVALIDATION", "version"), InternalAddr: getEnv("INTERNAL_ADDR", ":9090"), } } // instanceID — идентификатор реплики для X-Instance-Id. По умолчанию hostname, // который в Docker равен короткому ID контейнера: так stop-one.sh однозначно // находит контейнер. В lab7 его заменит непрозрачный alias. func instanceID() string { if v := os.Getenv("INSTANCE_ID"); v != "" { return v } if h, err := os.Hostname(); err == nil && h != "" { return h } return "unknown" } func (c Config) SessionTTL() time.Duration { return time.Duration(c.SessionTTLSeconds) * time.Second } func (c Config) Addr() string { return c.Host + ":" + c.Port } func getEnv(key, def string) string { if v := os.Getenv(key); v != "" { return v } return def } func getInt(key string, def int) int { if v := os.Getenv(key); v != "" { if n, err := strconv.Atoi(v); err == nil { return n } } return def } func readSecretFile(envKey string) string { path := os.Getenv(envKey) if path == "" { return "" } b, err := os.ReadFile(path) if err != nil { slog.Warn("secret file not readable", "path", path, "err", err) return "" } return strings.TrimSpace(string(b)) } func parseLevel(s string) slog.Level { var l slog.Level if err := l.UnmarshalText([]byte(s)); err != nil { return slog.LevelInfo } return l } func parseDuration(s string) time.Duration { d, err := time.ParseDuration(s) if err != nil { return 8 * time.Second } return d }