252 lines
7.5 KiB
Go
252 lines
7.5 KiB
Go
package config
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/go-playground/validator/v10"
|
|
"github.com/spf13/viper"
|
|
|
|
"mtusi-messenger/internal/logger"
|
|
)
|
|
|
|
const (
|
|
configEnvKey = "APP_CONFIG"
|
|
envKey = "APP_ENV"
|
|
configName = "config"
|
|
defaultEnv = "dev"
|
|
configDir = "./config/"
|
|
)
|
|
|
|
type Config struct {
|
|
Env string `mapstructure:"env" validate:"omitempty,eq=dev"`
|
|
Server Server `mapstructure:"server"`
|
|
Log Log `mapstructure:"log"`
|
|
Postgres Postgres `mapstructure:"postgres"`
|
|
Redis Redis `mapstructure:"redis"`
|
|
Cache Cache `mapstructure:"cache"`
|
|
Session Session `mapstructure:"session"`
|
|
Idempotency Idempotency `mapstructure:"idempotency"`
|
|
}
|
|
|
|
type Session struct {
|
|
TTLSeconds int `mapstructure:"ttl_seconds" validate:"required,gt=0"`
|
|
}
|
|
|
|
// Idempotency holds the retention window of a message Idempotency-Key (contract
|
|
// 1.3.0 requires at least 24 hours).
|
|
type Idempotency struct {
|
|
TTLSeconds int `mapstructure:"ttl_seconds" validate:"required,gt=0"`
|
|
}
|
|
|
|
type Redis struct {
|
|
Enabled bool `mapstructure:"enabled"`
|
|
Host string `mapstructure:"host" validate:"omitempty,hostname|ip"`
|
|
Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"`
|
|
Password string `mapstructure:"password"`
|
|
DB int `mapstructure:"db" validate:"omitempty,gte=0,lte=15"`
|
|
MaxRetries int `mapstructure:"max_retries" validate:"omitempty,gte=-1"`
|
|
DialTimeout time.Duration `mapstructure:"dial_timeout" validate:"omitempty,gt=0"`
|
|
ReadTimeout time.Duration `mapstructure:"read_timeout" validate:"omitempty,gt=0"`
|
|
WriteTimeout time.Duration `mapstructure:"write_timeout" validate:"omitempty,gt=0"`
|
|
PoolSize int `mapstructure:"pool_size" validate:"omitempty,gt=0"`
|
|
}
|
|
|
|
type Cache struct {
|
|
Enabled bool `mapstructure:"enabled"`
|
|
ChatListTTL time.Duration `mapstructure:"chat_list_ttl" validate:"required,gt=0"`
|
|
LockTTL time.Duration `mapstructure:"lock_ttl" validate:"required,gt=1s"`
|
|
LockWaitTimeout time.Duration `mapstructure:"lock_wait_timeout" validate:"required,gt=0"`
|
|
}
|
|
|
|
type Server struct {
|
|
Host string `mapstructure:"host" validate:"required,hostname|ip"`
|
|
Port int `mapstructure:"port" validate:"required,min=1,max=65535"`
|
|
ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout" validate:"required,gt=0"`
|
|
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout" validate:"required,gt=0"`
|
|
// MaxBodyBytes bounds a request body before the transport decodes it; uploads
|
|
// of a later lab raise it explicitly (contract 4: 10 MiB attachments).
|
|
MaxBodyBytes int64 `mapstructure:"max_body_bytes" validate:"required,gt=0"`
|
|
}
|
|
|
|
type Log struct {
|
|
Level string `mapstructure:"level" validate:"required,oneof=debug info warn error"`
|
|
Format string `mapstructure:"format" validate:"required,oneof=json console"`
|
|
}
|
|
|
|
type Postgres struct {
|
|
Host string `mapstructure:"host" validate:"omitempty,hostname|ip"`
|
|
Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"`
|
|
Database string `mapstructure:"database" validate:"omitempty,min=1"`
|
|
User string `mapstructure:"user" validate:"omitempty,min=1"`
|
|
Password string `mapstructure:"password"`
|
|
SSLMode string `mapstructure:"ssl_mode" validate:"omitempty,oneof=disable require verify-ca verify-full"`
|
|
MaxConns int32 `mapstructure:"max_conns" validate:"omitempty,gt=0"`
|
|
MinConns int32 `mapstructure:"min_conns" validate:"omitempty,gte=0"`
|
|
MaxConnLifetime time.Duration `mapstructure:"max_conn_lifetime" validate:"omitempty,gt=0"`
|
|
MaxConnIdleTime time.Duration `mapstructure:"max_conn_idle_time" validate:"omitempty,gt=0"`
|
|
ConnectTimeout time.Duration `mapstructure:"connect_timeout" validate:"omitempty,gt=0"`
|
|
QueryTimeout time.Duration `mapstructure:"query_timeout" validate:"omitempty,gt=0"`
|
|
}
|
|
|
|
func (p Postgres) DSN() string {
|
|
u := &url.URL{
|
|
Scheme: "postgres",
|
|
Host: net.JoinHostPort(p.Host, strconv.Itoa(p.Port)),
|
|
Path: "/" + p.Database,
|
|
}
|
|
|
|
if p.Password == "" {
|
|
u.User = url.User(p.User)
|
|
} else {
|
|
u.User = url.UserPassword(p.User, p.Password)
|
|
}
|
|
|
|
query := url.Values{}
|
|
query.Set("sslmode", p.SSLMode)
|
|
u.RawQuery = query.Encode()
|
|
|
|
return u.String()
|
|
}
|
|
|
|
var defaults = map[string]any{
|
|
"env": "dev",
|
|
"server.host": "0.0.0.0",
|
|
"server.port": 8080,
|
|
"server.read_header_timeout": "10s",
|
|
"server.shutdown_timeout": "10s",
|
|
"server.max_body_bytes": 262144,
|
|
"log.level": "info",
|
|
"log.format": "json",
|
|
"session.ttl_seconds": 3600,
|
|
"idempotency.ttl_seconds": 86400,
|
|
"redis.enabled": false,
|
|
"redis.host": "localhost",
|
|
"redis.port": 6379,
|
|
"redis.db": 0,
|
|
"redis.max_retries": -1,
|
|
"redis.dial_timeout": "300ms",
|
|
"redis.read_timeout": "200ms",
|
|
"redis.write_timeout": "200ms",
|
|
"redis.pool_size": 10,
|
|
"cache.enabled": false,
|
|
"cache.chat_list_ttl": "5m",
|
|
"cache.lock_ttl": "10s",
|
|
"cache.lock_wait_timeout": "2s",
|
|
}
|
|
|
|
func Load() (Config, error) {
|
|
v := viper.New()
|
|
|
|
if err := configureSource(v); err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
v.AllowEmptyEnv(true)
|
|
v.AutomaticEnv()
|
|
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
|
|
|
for key := range defaults {
|
|
if err := v.BindEnv(key); err != nil {
|
|
return Config{}, fmt.Errorf("bind env %q: %w", key, err)
|
|
}
|
|
}
|
|
|
|
var cfg Config
|
|
if err := v.Unmarshal(&cfg); err != nil {
|
|
return Config{}, fmt.Errorf("unmarshal config: %w", err)
|
|
}
|
|
|
|
if err := validate.Struct(cfg); err != nil {
|
|
return Config{}, fmt.Errorf("validate config: %w", err)
|
|
}
|
|
|
|
if err := cfg.validateDependencies(); err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
return cfg, nil
|
|
}
|
|
|
|
func (c Config) validateDependencies() error {
|
|
if c.Cache.Enabled && !c.Redis.Enabled {
|
|
return errors.New("validate config: cache.enabled requires redis.enabled")
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func configureSource(v *viper.Viper) error {
|
|
for key, value := range defaults {
|
|
v.SetDefault(key, value)
|
|
}
|
|
|
|
v.SetConfigType("yaml")
|
|
|
|
if path := os.Getenv(configEnvKey); path != "" {
|
|
v.SetConfigFile(path)
|
|
} else {
|
|
env := os.Getenv(envKey)
|
|
if env == "" {
|
|
env = defaultEnv
|
|
}
|
|
|
|
v.SetConfigName(configName)
|
|
v.AddConfigPath(filepath.Join(configDir, env))
|
|
}
|
|
|
|
if err := v.ReadInConfig(); err != nil {
|
|
var notFound viper.ConfigFileNotFoundError
|
|
if errors.As(err, ¬Found) {
|
|
return nil
|
|
}
|
|
|
|
return fmt.Errorf("read config: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (c Config) Addr() string {
|
|
return net.JoinHostPort(c.Server.Host, strconv.Itoa(c.Server.Port))
|
|
}
|
|
|
|
func (c Config) SlogLevel() slog.Level {
|
|
level, _ := logger.ParseLevel(c.Log.Level)
|
|
|
|
return level
|
|
}
|
|
|
|
func (c Config) LoggerFormat() logger.Format {
|
|
format, _ := logger.ParseFormat(c.Log.Format)
|
|
|
|
return format
|
|
}
|
|
|
|
var validate = newValidator()
|
|
|
|
func newValidator() *validator.Validate {
|
|
v := validator.New(validator.WithRequiredStructEnabled())
|
|
v.RegisterTagNameFunc(envName)
|
|
|
|
return v
|
|
}
|
|
|
|
func envName(field reflect.StructField) string {
|
|
key := field.Tag.Get("mapstructure")
|
|
if key == "" {
|
|
return field.Name
|
|
}
|
|
|
|
return strings.ToUpper(key)
|
|
}
|