Files
mtusi2026lab6/internal/config/config.go
T

149 lines
4.6 KiB
Go

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
S3Endpoint string
S3Region string
S3Bucket string
S3AccessKey string
S3SecretKey string
MaxUploadBytes int64
MaxImagePixels int64
// Pipeline (lab5)
BrokerURL string
PipelineVersion int
JobMaxAttempts int
JobTimeout time.Duration
WorkerConcurrency int
StagingRetention time.Duration
WebPQuality int
PixelBudget int64
RetryBaseDelay time.Duration
RetryMaxDelay time.Duration
}
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"),
S3Endpoint: getEnv("S3_ENDPOINT", "http://s3:9000"),
S3Region: getEnv("S3_REGION", "us-east-1"),
S3Bucket: getEnv("S3_BUCKET", "messenger-attachments"),
S3AccessKey: readSecretFile("S3_ACCESS_KEY_ID_FILE"),
S3SecretKey: readSecretFile("S3_SECRET_ACCESS_KEY_FILE"),
MaxUploadBytes: int64(getInt("MAX_UPLOAD_BYTES", 10*1024*1024)),
MaxImagePixels: int64(getInt("MAX_IMAGE_PIXELS", 40_000_000)),
BrokerURL: readSecretFile("BROKER_URL_FILE"),
PipelineVersion: max(1, getInt("PIPELINE_VERSION", 1)),
JobMaxAttempts: max(1, getInt("JOB_MAX_ATTEMPTS", 5)),
JobTimeout: time.Duration(max(5, getInt("JOB_TIMEOUT_SECONDS", 60))) * time.Second,
WorkerConcurrency: max(1, getInt("WORKER_CONCURRENCY", 2)),
StagingRetention: time.Duration(max(60, getInt("STAGING_RETENTION_SECONDS", 86400))) * time.Second,
WebPQuality: min(100, max(1, getInt("WEBP_QUALITY", 80))),
PixelBudget: int64(max(1_000_000, getInt("WORKER_PIXEL_BUDGET", 60_000_000))),
RetryBaseDelay: parseDuration(getEnv("RETRY_BASE_DELAY", "2s")),
RetryMaxDelay: parseDuration(getEnv("RETRY_MAX_DELAY", "60s")),
}
}
// 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
}