config.go68 lines, 2.3 KB
| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "log/slog" |
| 5 | "strings" |
| 6 | "time" |
| 7 | |
| 8 | "github.com/fiston-user/payments/internal/platform/config" |
| 9 | "github.com/fiston-user/payments/internal/platform/logging" |
| 10 | "github.com/fiston-user/payments/internal/webhook" |
| 11 | ) |
| 12 | |
| 13 | // Config is everything the webhook service reads from its environment. |
| 14 | type Config struct { |
| 15 | Env string // development or production |
| 16 | HTTPAddr string |
| 17 | ShutdownTimeout time.Duration |
| 18 | DrainDelay time.Duration // how long readiness fails before we stop |
| 19 | LogLevel slog.Level |
| 20 | LogFormat string |
| 21 | DatabaseURL string |
| 22 | DBMaxConns int |
| 23 | NATSURL string |
| 24 | PublicKeyFile string |
| 25 | RetrySchedule []time.Duration // the wait before each retry |
| 26 | } |
| 27 | |
| 28 | // loadConfig reads the configuration. Everything has a sensible default except |
| 29 | // secrets, and every missing or invalid variable is reported at once. |
| 30 | func loadConfig(env *config.Env) (Config, error) { |
| 31 | c := Config{ |
| 32 | Env: env.OneOf("APP_ENV", "development", "development", "production"), |
| 33 | HTTPAddr: env.String("WEBHOOK_HTTP_ADDR", ":8085"), |
| 34 | ShutdownTimeout: env.Duration("WEBHOOK_SHUTDOWN_TIMEOUT", 10*time.Second), |
| 35 | DrainDelay: env.Duration("WEBHOOK_DRAIN_DELAY", 0), |
| 36 | LogLevel: config.Parse(env, "LOG_LEVEL", slog.LevelInfo, logging.ParseLevel), |
| 37 | DatabaseURL: env.Required("WEBHOOK_DATABASE_URL"), |
| 38 | DBMaxConns: env.Int("WEBHOOK_DB_MAX_CONNS", 10), |
| 39 | NATSURL: env.String("WEBHOOK_NATS_URL", "nats://localhost:4222"), |
| 40 | PublicKeyFile: env.Required("WEBHOOK_AUTH_PUBLIC_KEY_FILE"), |
| 41 | RetrySchedule: config.Parse(env, "WEBHOOK_RETRY_SCHEDULE", webhook.Schedule, parseDurations), |
| 42 | } |
| 43 | |
| 44 | // Text logs for humans in development, JSON for log collectors in production. |
| 45 | format := "text" |
| 46 | if c.Env == "production" { |
| 47 | format = "json" |
| 48 | } |
| 49 | c.LogFormat = env.OneOf("LOG_FORMAT", format, "text", "json") |
| 50 | |
| 51 | if c.DBMaxConns < 1 || c.DBMaxConns > 100 { |
| 52 | env.Invalid("WEBHOOK_DB_MAX_CONNS", "must be between 1 and 100") |
| 53 | } |
| 54 | return c, env.Err() |
| 55 | } |
| 56 | |
| 57 | // parseDurations reads a list of durations, like 5s,1m,1h. |
| 58 | func parseDurations(s string) ([]time.Duration, error) { |
| 59 | var ds []time.Duration |
| 60 | for f := range strings.SplitSeq(s, ",") { |
| 61 | d, err := time.ParseDuration(strings.TrimSpace(f)) |
| 62 | if err != nil { |
| 63 | return nil, err |
| 64 | } |
| 65 | ds = append(ds, d) |
| 66 | } |
| 67 | return ds, nil |
| 68 | } |