257 lines
7.9 KiB
Go
257 lines
7.9 KiB
Go
package config
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
defaultHTTPAddr = ":8080"
|
|
defaultMetricsAddr = ":9090"
|
|
defaultRedisAddr = "localhost:6379"
|
|
defaultLogLevel = "info"
|
|
defaultRedisTimeout = time.Second
|
|
defaultReadinessTimeout = time.Second
|
|
defaultShutdownTimeout = 10 * time.Second
|
|
// Startup migrations are on by default so a deployed binary never serves
|
|
// with a schema older than the one it was built for.
|
|
defaultDatabaseMigrateOnStart = true
|
|
maxPortNumber = 65535
|
|
)
|
|
|
|
type Config struct {
|
|
HTTPAddr string
|
|
MetricsAddr string
|
|
DatabaseURL string
|
|
// DatabaseMigrateOnStart applies embedded migrations before serving.
|
|
DatabaseMigrateOnStart bool
|
|
RedisAddr string
|
|
RedisPassword string
|
|
RedisDB int
|
|
RedisTimeout time.Duration
|
|
SeaweedFSEndpoint string
|
|
SeaweedFSAccessKey string
|
|
SeaweedFSSecretKey string
|
|
SeaweedFSBucket string
|
|
SeaweedFSRegion string
|
|
SeaweedFSTimeout time.Duration
|
|
KafkaBrokers []string
|
|
// EmailProvider selects the only active mail transport. Settings of the
|
|
// other transports are not loaded.
|
|
EmailProvider EmailProvider
|
|
// EmailFrom is the sender mailbox for every outgoing message.
|
|
EmailFrom string
|
|
EmailTimeout time.Duration
|
|
// AppPublicURL is the public origin without a trailing slash, for links
|
|
// in mail.
|
|
AppPublicURL string
|
|
ResendAPIKey string
|
|
SMTPHost string
|
|
SMTPPort int
|
|
SMTPUsername string
|
|
SMTPPassword string
|
|
SMTPTLSMode SMTPTLSMode
|
|
LogLevel string
|
|
ReadinessTimeout time.Duration
|
|
ShutdownTimeout time.Duration
|
|
|
|
// PasswordHashConcurrency is the number of password hash derivations
|
|
// that may run at once; further logins and registrations wait.
|
|
PasswordHashConcurrency int
|
|
}
|
|
|
|
type LookupEnv func(string) (string, bool)
|
|
|
|
func Load() (Config, error) {
|
|
return LoadFromEnv(os.LookupEnv)
|
|
}
|
|
|
|
func LoadFromEnv(lookup LookupEnv) (Config, error) {
|
|
config := Config{
|
|
HTTPAddr: valueOrDefault(lookup, "HTTP_ADDR", defaultHTTPAddr),
|
|
MetricsAddr: valueOrDefault(lookup, "METRICS_ADDR", defaultMetricsAddr),
|
|
DatabaseURL: DatabaseURLFromEnv(lookup),
|
|
RedisAddr: strings.TrimSpace(valueOrDefault(lookup, "REDIS_ADDR", defaultRedisAddr)),
|
|
RedisPassword: valueOrDefault(lookup, "REDIS_PASSWORD", ""),
|
|
RedisTimeout: defaultRedisTimeout,
|
|
SeaweedFSEndpoint: strings.TrimSpace(valueOrDefault(lookup, "SEAWEEDFS_ENDPOINT", defaultSeaweedFSEndpoint)),
|
|
SeaweedFSAccessKey: valueOrDefault(lookup, "SEAWEEDFS_ACCESS_KEY", ""),
|
|
SeaweedFSSecretKey: valueOrDefault(lookup, "SEAWEEDFS_SECRET_KEY", ""),
|
|
SeaweedFSBucket: strings.TrimSpace(valueOrDefault(lookup, "SEAWEEDFS_BUCKET", defaultSeaweedFSBucket)),
|
|
SeaweedFSRegion: strings.TrimSpace(valueOrDefault(lookup, "SEAWEEDFS_REGION", defaultSeaweedFSRegion)),
|
|
SeaweedFSTimeout: defaultSeaweedFSTimeout,
|
|
KafkaBrokers: parseKafkaBrokers(valueOrDefault(lookup, "KAFKA_BROKERS", defaultKafkaBrokers)),
|
|
LogLevel: strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "LOG_LEVEL", defaultLogLevel))),
|
|
ReadinessTimeout: defaultReadinessTimeout,
|
|
ShutdownTimeout: defaultShutdownTimeout,
|
|
}
|
|
|
|
if err := config.loadRedis(lookup); err != nil {
|
|
return Config{}, err
|
|
}
|
|
if err := config.loadMail(lookup); err != nil {
|
|
return Config{}, err
|
|
}
|
|
if err := config.loadPasswordHash(lookup); err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
var err error
|
|
config.DatabaseMigrateOnStart, err = boolOrDefault(lookup, "DATABASE_MIGRATE_ON_START", defaultDatabaseMigrateOnStart)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
config.SeaweedFSTimeout, err = durationOrDefault(lookup, "SEAWEEDFS_TIMEOUT", config.SeaweedFSTimeout)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
config.ReadinessTimeout, err = durationOrDefault(lookup, "READINESS_TIMEOUT", config.ReadinessTimeout)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
config.ShutdownTimeout, err = durationOrDefault(lookup, "SHUTDOWN_TIMEOUT", config.ShutdownTimeout)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
if err := config.Validate(); err != nil {
|
|
return Config{}, err
|
|
}
|
|
return config, nil
|
|
}
|
|
|
|
func (config Config) Validate() error {
|
|
if err := config.ValidateSeaweedFS(); err != nil {
|
|
return err
|
|
}
|
|
if err := config.ValidateRedis(); err != nil {
|
|
return err
|
|
}
|
|
if err := config.ValidateKafka(); err != nil {
|
|
return err
|
|
}
|
|
if err := config.ValidateMail(); err != nil {
|
|
return err
|
|
}
|
|
if err := config.ValidatePasswordHash(); err != nil {
|
|
return err
|
|
}
|
|
if err := validateAddress("HTTP_ADDR", config.HTTPAddr); err != nil {
|
|
return err
|
|
}
|
|
if err := validateAddress("METRICS_ADDR", config.MetricsAddr); err != nil {
|
|
return err
|
|
}
|
|
if config.ReadinessTimeout <= 0 {
|
|
return errors.New("Config.Validate - READINESS_TIMEOUT must be positive")
|
|
}
|
|
if config.ShutdownTimeout <= 0 {
|
|
return errors.New("Config.Validate - SHUTDOWN_TIMEOUT must be positive")
|
|
}
|
|
switch config.LogLevel {
|
|
case "debug", "info", "warn", "error":
|
|
default:
|
|
return errors.New("Config.Validate - LOG_LEVEL must be one of debug, info, warn, or error")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func valueOrDefault(lookup LookupEnv, key, fallback string) string {
|
|
if value, ok := lookup(key); ok {
|
|
return value
|
|
}
|
|
return fallback
|
|
}
|
|
|
|
// DatabaseURLFromEnv reads DATABASE_URL for commands that need only the
|
|
// database, such as the migration command.
|
|
func DatabaseURLFromEnv(lookup LookupEnv) string {
|
|
return strings.TrimSpace(valueOrDefault(lookup, "DATABASE_URL", ""))
|
|
}
|
|
|
|
// boolOrDefault accepts only "true" or "false", ignoring case and surrounding
|
|
// spaces. strconv.ParseBool would also accept 1, t, and similar shorthands,
|
|
// which are easy to mistype in deployment files.
|
|
func boolOrDefault(lookup LookupEnv, key string, fallback bool) (bool, error) {
|
|
value, ok := lookup(key)
|
|
if !ok {
|
|
return fallback, nil
|
|
}
|
|
switch strings.ToLower(strings.TrimSpace(value)) {
|
|
case "true":
|
|
return true, nil
|
|
case "false":
|
|
return false, nil
|
|
default:
|
|
return false, fmt.Errorf("config.boolOrDefault - %s must be true or false", key)
|
|
}
|
|
}
|
|
|
|
func durationOrDefault(lookup LookupEnv, key string, fallback time.Duration) (time.Duration, error) {
|
|
value, ok := lookup(key)
|
|
if !ok {
|
|
return fallback, nil
|
|
}
|
|
duration, err := time.ParseDuration(value)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("config.durationOrDefault - parse %s: %w", key, err)
|
|
}
|
|
return duration, nil
|
|
}
|
|
|
|
func validateAddress(name, address string) error {
|
|
if address == "" {
|
|
return fmt.Errorf("config.validateAddress - %s must not be empty", name)
|
|
}
|
|
_, port, err := net.SplitHostPort(address)
|
|
if err != nil {
|
|
return fmt.Errorf("config.validateAddress - %s must be a host:port address: %w", name, err)
|
|
}
|
|
number, err := strconv.Atoi(port)
|
|
if err != nil || number < 0 || number > maxPortNumber {
|
|
return fmt.Errorf("config.validateAddress - %s port must be between 0 and %d", name, maxPortNumber)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (config *Config) loadRedis(lookup LookupEnv) error {
|
|
if value, ok := lookup("REDIS_DB"); ok {
|
|
database, err := strconv.Atoi(value)
|
|
if err != nil {
|
|
return fmt.Errorf("Config.loadRedis - parse REDIS_DB: %w", err)
|
|
}
|
|
config.RedisDB = database
|
|
}
|
|
|
|
var err error
|
|
config.RedisTimeout, err = durationOrDefault(lookup, "REDIS_TIMEOUT", config.RedisTimeout)
|
|
return err
|
|
}
|
|
|
|
func (config Config) ValidateRedis() error {
|
|
if err := validateAddress("REDIS_ADDR", config.RedisAddr); err != nil {
|
|
return err
|
|
}
|
|
// validateAddress already checked both parsing operations above.
|
|
host, port, _ := net.SplitHostPort(config.RedisAddr)
|
|
number, _ := strconv.Atoi(port)
|
|
if host == "" || number == 0 {
|
|
return errors.New("Config.ValidateRedis - REDIS_ADDR must contain a host and a nonzero port")
|
|
}
|
|
if config.RedisDB < 0 {
|
|
return errors.New("Config.ValidateRedis - REDIS_DB must not be negative")
|
|
}
|
|
if config.RedisTimeout <= 0 {
|
|
return errors.New("Config.ValidateRedis - REDIS_TIMEOUT must be positive")
|
|
}
|
|
return nil
|
|
}
|