refactor(backend): standardize errors and simplify configuration and test setup
This commit is contained in:
1 parent
1535c19b8c
commit
138666a7bb
92 files changed
+3994
-210
No files matched your search
+118
-31
@@ -1,6 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
@@ -9,13 +10,34 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultHTTPAddr = ":8080"
|
||||
defaultMetricsAddr = ":9090"
|
||||
defaultRedisAddr = "localhost:6379"
|
||||
defaultLogLevel = "info"
|
||||
defaultRedisTimeout = time.Second
|
||||
defaultReadinessTimeout = time.Second
|
||||
defaultShutdownTimeout = 10 * time.Second
|
||||
maxPortNumber = 65535
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
HTTPAddr string
|
||||
MetricsAddr string
|
||||
DatabaseURL string
|
||||
LogLevel string
|
||||
ReadinessTimeout time.Duration
|
||||
ShutdownTimeout time.Duration
|
||||
HTTPAddr string
|
||||
MetricsAddr string
|
||||
DatabaseURL string
|
||||
RedisAddr string
|
||||
RedisPassword string
|
||||
RedisDB int
|
||||
RedisTimeout time.Duration
|
||||
SeaweedFSEndpoint string
|
||||
SeaweedFSAccessKey string
|
||||
SeaweedFSSecretKey string
|
||||
SeaweedFSBucket string
|
||||
SeaweedFSRegion string
|
||||
SeaweedFSTimeout time.Duration
|
||||
LogLevel string
|
||||
ReadinessTimeout time.Duration
|
||||
ShutdownTimeout time.Duration
|
||||
}
|
||||
|
||||
type LookupEnv func(string) (string, bool)
|
||||
@@ -26,27 +48,41 @@ func Load() (Config, error) {
|
||||
|
||||
func LoadFromEnv(lookup LookupEnv) (Config, error) {
|
||||
config := Config{
|
||||
HTTPAddr: valueOrDefault(lookup, "HTTP_ADDR", ":8080"),
|
||||
MetricsAddr: valueOrDefault(lookup, "METRICS_ADDR", ":9090"),
|
||||
DatabaseURL: strings.TrimSpace(valueOrDefault(lookup, "DATABASE_URL", "")),
|
||||
LogLevel: strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "LOG_LEVEL", "info"))),
|
||||
ReadinessTimeout: time.Second,
|
||||
ShutdownTimeout: 10 * time.Second,
|
||||
HTTPAddr: valueOrDefault(lookup, "HTTP_ADDR", defaultHTTPAddr),
|
||||
MetricsAddr: valueOrDefault(lookup, "METRICS_ADDR", defaultMetricsAddr),
|
||||
DatabaseURL: strings.TrimSpace(valueOrDefault(lookup, "DATABASE_URL", "")),
|
||||
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,
|
||||
LogLevel: strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "LOG_LEVEL", defaultLogLevel))),
|
||||
ReadinessTimeout: defaultReadinessTimeout,
|
||||
ShutdownTimeout: defaultShutdownTimeout,
|
||||
}
|
||||
|
||||
if value, ok := lookup("READINESS_TIMEOUT"); ok {
|
||||
duration, err := time.ParseDuration(value)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("parse READINESS_TIMEOUT: %w", err)
|
||||
}
|
||||
config.ReadinessTimeout = duration
|
||||
if err := config.loadRedis(lookup); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if value, ok := lookup("SHUTDOWN_TIMEOUT"); ok {
|
||||
duration, err := time.ParseDuration(value)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("parse SHUTDOWN_TIMEOUT: %w", err)
|
||||
}
|
||||
config.ShutdownTimeout = duration
|
||||
|
||||
var err error
|
||||
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 {
|
||||
@@ -56,6 +92,12 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) {
|
||||
}
|
||||
|
||||
func (config Config) Validate() error {
|
||||
if err := config.ValidateSeaweedFS(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := config.ValidateRedis(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateAddress("HTTP_ADDR", config.HTTPAddr); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -63,15 +105,15 @@ func (config Config) Validate() error {
|
||||
return err
|
||||
}
|
||||
if config.ReadinessTimeout <= 0 {
|
||||
return fmt.Errorf("READINESS_TIMEOUT must be positive")
|
||||
return errors.New("Config.Validate - READINESS_TIMEOUT must be positive")
|
||||
}
|
||||
if config.ShutdownTimeout <= 0 {
|
||||
return fmt.Errorf("SHUTDOWN_TIMEOUT must be positive")
|
||||
return errors.New("Config.Validate - SHUTDOWN_TIMEOUT must be positive")
|
||||
}
|
||||
switch config.LogLevel {
|
||||
case "debug", "info", "warn", "error":
|
||||
default:
|
||||
return fmt.Errorf("LOG_LEVEL must be one of debug, info, warn, or error")
|
||||
return errors.New("Config.Validate - LOG_LEVEL must be one of debug, info, warn, or error")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -83,17 +125,62 @@ func valueOrDefault(lookup LookupEnv, key, fallback string) string {
|
||||
return fallback
|
||||
}
|
||||
|
||||
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("%s must not be empty", name)
|
||||
return fmt.Errorf("config.validateAddress - %s must not be empty", name)
|
||||
}
|
||||
_, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s must be a host:port address: %w", name, err)
|
||||
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 > 65535 {
|
||||
return fmt.Errorf("%s port must be between 0 and 65535", name)
|
||||
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
|
||||
}
|
||||
Reference in new issue
Block a user