This commit is contained in:
Vladislav Kunetskiy
2026-10-15 20:45:29 +03:00
parent 1fdaf6299a
commit f4bd361f12
140 changed files with 12784 additions and 2198 deletions
+162 -16
View File
@@ -1,9 +1,13 @@
package config
import (
"errors"
"fmt"
"log/slog"
"net"
"net/url"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
@@ -15,35 +19,134 @@ import (
"mtusi-messenger/internal/logger"
)
const envPrefix = "APP"
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"`
}
type Session 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"`
LogLevel string `mapstructure:"log_level" validate:"required,oneof=debug info warn error"`
LogFormat string `mapstructure:"log_format" validate:"required,oneof=json console"`
}
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{
"host": "0.0.0.0",
"port": 8080,
"read_header_timeout": "10s",
"shutdown_timeout": "10s",
"log_level": "info",
"log_format": "json",
"env": "dev",
"server.host": "0.0.0.0",
"server.port": 8080,
"server.read_header_timeout": "10s",
"server.shutdown_timeout": "10s",
"log.level": "info",
"log.format": "json",
"session.ttl_seconds": 3600,
"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()
v.SetEnvPrefix(envPrefix)
if err := configureSource(v); err != nil {
return Config{}, err
}
v.AllowEmptyEnv(true)
v.AutomaticEnv()
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
for key, value := range defaults {
v.SetDefault(key, value)
for key := range defaults {
if err := v.BindEnv(key); err != nil {
return Config{}, fmt.Errorf("bind env %q: %w", key, err)
}
}
var cfg Config
@@ -55,21 +158,64 @@ func Load() (Config, error) {
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, &notFound) {
return nil
}
return fmt.Errorf("read config: %w", err)
}
return nil
}
func (c Config) Addr() string {
return net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
return net.JoinHostPort(c.Server.Host, strconv.Itoa(c.Server.Port))
}
func (c Config) SlogLevel() slog.Level {
level, _ := logger.ParseLevel(c.LogLevel)
level, _ := logger.ParseLevel(c.Log.Level)
return level
}
func (c Config) LoggerFormat() logger.Format {
format, _ := logger.ParseFormat(c.LogFormat)
format, _ := logger.ParseFormat(c.Log.Format)
return format
}
@@ -89,5 +235,5 @@ func envName(field reflect.StructField) string {
return field.Name
}
return envPrefix + "_" + strings.ToUpper(key)
return strings.ToUpper(key)
}
+296 -137
View File
@@ -1,178 +1,274 @@
package config_test
import (
"os"
"path/filepath"
"testing"
"time"
"github.com/go-playground/validator/v10"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"mtusi-messenger/internal/config"
"mtusi-messenger/internal/logger"
)
type ConfigSuite struct {
suite.Suite
}
func TestConfigSuite(t *testing.T) {
suite.Run(t, new(ConfigSuite))
}
func (s *ConfigSuite) TestDefaults() {
func TestDefaults(t *testing.T) {
cfg, err := config.Load()
s.Require().NoError(err)
require.NoError(t, err)
s.Equal("0.0.0.0", cfg.Host)
s.Equal(8080, cfg.Port)
s.Equal(10*time.Second, cfg.ReadHeaderTimeout)
s.Equal(10*time.Second, cfg.ShutdownTimeout)
s.Equal("info", cfg.LogLevel)
s.Equal("json", cfg.LogFormat)
assert.Equal(t, "0.0.0.0", cfg.Server.Host)
assert.Equal(t, 8080, cfg.Server.Port)
assert.Equal(t, 10*time.Second, cfg.Server.ReadHeaderTimeout)
assert.Equal(t, 10*time.Second, cfg.Server.ShutdownTimeout)
assert.Equal(t, "info", cfg.Log.Level)
assert.Equal(t, "json", cfg.Log.Format)
assert.Equal(t, config.Postgres{}, cfg.Postgres, "postgres defaults live in the adapter")
}
func (s *ConfigSuite) TestEnvOverridesDefaults() {
s.T().Setenv("APP_HOST", "127.0.0.1")
s.T().Setenv("APP_PORT", "9090")
s.T().Setenv("APP_READ_HEADER_TIMEOUT", "3s")
s.T().Setenv("APP_SHUTDOWN_TIMEOUT", "30s")
s.T().Setenv("APP_LOG_LEVEL", "debug")
s.T().Setenv("APP_LOG_FORMAT", "console")
func TestEnvOverridesDefaults(t *testing.T) {
t.Setenv("SERVER_HOST", "127.0.0.1")
t.Setenv("SERVER_PORT", "9090")
t.Setenv("SERVER_READ_HEADER_TIMEOUT", "3s")
t.Setenv("SERVER_SHUTDOWN_TIMEOUT", "30s")
t.Setenv("LOG_LEVEL", "debug")
t.Setenv("LOG_FORMAT", "console")
cfg, err := config.Load()
s.Require().NoError(err)
require.NoError(t, err)
s.Equal("127.0.0.1", cfg.Host)
s.Equal(9090, cfg.Port)
s.Equal(3*time.Second, cfg.ReadHeaderTimeout)
s.Equal(30*time.Second, cfg.ShutdownTimeout)
s.Equal("debug", cfg.LogLevel)
s.Equal("console", cfg.LogFormat)
assert.Equal(t, "127.0.0.1", cfg.Server.Host)
assert.Equal(t, 9090, cfg.Server.Port)
assert.Equal(t, 3*time.Second, cfg.Server.ReadHeaderTimeout)
assert.Equal(t, 30*time.Second, cfg.Server.ShutdownTimeout)
assert.Equal(t, "debug", cfg.Log.Level)
assert.Equal(t, "console", cfg.Log.Format)
}
func (s *ConfigSuite) TestLoggerSettings() {
s.T().Setenv("APP_LOG_LEVEL", "warn")
s.T().Setenv("APP_LOG_FORMAT", "console")
cfg, err := config.Load()
s.Require().NoError(err)
level, err := logger.ParseLevel(cfg.LogLevel)
s.Require().NoError(err)
s.Equal(level, cfg.SlogLevel())
format, err := logger.ParseFormat(cfg.LogFormat)
s.Require().NoError(err)
s.Equal(format, cfg.LoggerFormat())
}
func (s *ConfigSuite) TestAddr() {
s.T().Setenv("APP_HOST", "0.0.0.0")
s.T().Setenv("APP_PORT", "8080")
cfg, err := config.Load()
s.Require().NoError(err)
s.Equal("0.0.0.0:8080", cfg.Addr())
}
func (s *ConfigSuite) TestAddrWithIPv6Host() {
s.T().Setenv("APP_HOST", "::1")
cfg, err := config.Load()
s.Require().NoError(err)
s.Equal("[::1]:8080", cfg.Addr())
}
func (s *ConfigSuite) TestInvalidValues() {
tests := map[string]struct {
env map[string]string
wantField string
wantTag string
}{
"пустой host": {
env: map[string]string{"APP_HOST": ""},
wantField: "APP_HOST",
wantTag: "required",
},
"host не адрес и не имя": {
env: map[string]string{"APP_HOST": "не адрес"},
wantField: "APP_HOST",
wantTag: "hostname|ip",
},
"порт ниже диапазона": {
env: map[string]string{"APP_PORT": "0"},
wantField: "APP_PORT",
wantTag: "required",
},
"порт выше диапазона": {
env: map[string]string{"APP_PORT": "65536"},
wantField: "APP_PORT",
wantTag: "max",
},
"нулевой read header timeout": {
env: map[string]string{"APP_READ_HEADER_TIMEOUT": "0s"},
wantField: "APP_READ_HEADER_TIMEOUT",
wantTag: "required",
},
"отрицательный shutdown timeout": {
env: map[string]string{"APP_SHUTDOWN_TIMEOUT": "-1s"},
wantField: "APP_SHUTDOWN_TIMEOUT",
wantTag: "gt",
},
"неизвестный уровень логирования": {
env: map[string]string{"APP_LOG_LEVEL": "trace"},
wantField: "APP_LOG_LEVEL",
wantTag: "oneof",
},
"неизвестный формат логирования": {
env: map[string]string{"APP_LOG_FORMAT": "xml"},
wantField: "APP_LOG_FORMAT",
wantTag: "oneof",
},
func TestDsnEncodesCredentials(t *testing.T) {
cfg := config.Postgres{
Host: "db",
Port: 5432,
Database: "app",
User: "user",
Password: "p@ss:w/rd",
SSLMode: "disable",
}
for name, tt := range tests {
s.Run(name, func() {
for key, value := range tt.env {
s.T().Setenv(key, value)
}
_, err := config.Load()
s.Require().Error(err)
var validationErrs validator.ValidationErrors
s.Require().ErrorAs(err, &validationErrs)
s.Require().Len(validationErrs, 1)
s.Equal(tt.wantField, validationErrs[0].Field())
s.Equal(tt.wantTag, validationErrs[0].Tag())
})
}
assert.Equal(t, "postgres://user:p%40ss%3Aw%2Frd@db:5432/app?sslmode=disable", cfg.DSN())
}
func (s *ConfigSuite) TestUnparsableValues() {
func writeConfig(t *testing.T, body string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
return path
}
func TestLoadsYAMLFile(t *testing.T) {
path := writeConfig(t, `
env: dev
server:
host: 10.0.0.1
port: 9999
read_header_timeout: 3s
shutdown_timeout: 7s
log:
level: debug
format: console
postgres:
host: db
port: 5433
database: app
user: app
password: secret
ssl_mode: disable
max_conns: 7
min_conns: 2
max_conn_lifetime: 2h
max_conn_idle_time: 10m
connect_timeout: 2s
query_timeout: 3s
`)
t.Setenv("APP_CONFIG", path)
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "10.0.0.1", cfg.Server.Host)
assert.Equal(t, 9999, cfg.Server.Port)
assert.Equal(t, 3*time.Second, cfg.Server.ReadHeaderTimeout)
assert.Equal(t, "debug", cfg.Log.Level)
assert.Equal(t, "console", cfg.Log.Format)
assert.Equal(t, "db", cfg.Postgres.Host)
assert.Equal(t, 5433, cfg.Postgres.Port)
assert.Equal(t, "app", cfg.Postgres.Database)
assert.Equal(t, int32(7), cfg.Postgres.MaxConns)
assert.Equal(t, 2*time.Second, cfg.Postgres.ConnectTimeout)
}
func TestEnvOverridesYAML(t *testing.T) {
path := writeConfig(t, `
env: dev
server:
host: 10.0.0.1
port: 9999
read_header_timeout: 3s
shutdown_timeout: 7s
log:
level: debug
format: console
postgres:
host: db
port: 5433
database: app
user: app
password: file
ssl_mode: disable
`)
t.Setenv("APP_CONFIG", path)
t.Setenv("SERVER_HOST", "127.0.0.1")
t.Setenv("POSTGRES_PASSWORD", "env")
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "127.0.0.1", cfg.Server.Host, "env переопределяет YAML")
assert.Equal(t, 9999, cfg.Server.Port)
assert.Equal(t, "env", cfg.Postgres.Password)
}
func TestSessionTTLFromContractEnv(t *testing.T) {
t.Setenv("SESSION_TTL_SECONDS", "2")
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, 2, cfg.Session.TTLSeconds)
}
func TestInvalidValues(t *testing.T) {
tests := map[string]map[string]string{
"порт не число": {"APP_PORT": "не-число"},
"timeout не длительность": {"APP_READ_HEADER_TIMEOUT": "быстро"},
"пустой server.host": {"SERVER_HOST": ""},
"host не адрес и не имя": {"SERVER_HOST": "не адрес"},
"порт ниже диапазона": {"SERVER_PORT": "0"},
"порт выше диапазона": {"SERVER_PORT": "65536"},
"нулевой read header timeout": {"SERVER_READ_HEADER_TIMEOUT": "0s"},
"отрицательный shutdown": {"SERVER_SHUTDOWN_TIMEOUT": "-1s"},
"неизвестный log level": {"LOG_LEVEL": "trace"},
"неизвестный log format": {"LOG_FORMAT": "xml"},
}
for name, env := range tests {
s.Run(name, func() {
t.Run(name, func(t *testing.T) {
for key, value := range env {
s.T().Setenv(key, value)
t.Setenv(key, value)
}
_, err := config.Load()
s.Require().Error(err)
require.Error(t, err)
var validationErrs validator.ValidationErrors
require.ErrorAs(t, err, &validationErrs)
require.NotEmpty(t, validationErrs)
})
}
}
func TestInvalidPostgresValues(t *testing.T) {
path := writeConfig(t, `
env: dev
postgres:
host: db
port: 5432
database: messenger
user: messenger
ssl_mode: disable
max_conns: 10
`)
tests := map[string]map[string]string{
"неизвестный ssl mode": {"POSTGRES_SSL_MODE": "bogus"},
"отрицательный max_conns": {"POSTGRES_MAX_CONNS": "-1"},
}
for name, env := range tests {
t.Run(name, func(t *testing.T) {
t.Setenv("APP_CONFIG", path)
for key, value := range env {
t.Setenv(key, value)
}
_, err := config.Load()
require.Error(t, err)
var validationErrs validator.ValidationErrors
require.ErrorAs(t, err, &validationErrs)
require.NotEmpty(t, validationErrs)
})
}
}
func TestUnparsableValues(t *testing.T) {
tests := map[string]map[string]string{
"порт не число": {"SERVER_PORT": "не-число"},
"timeout не duration": {"SERVER_READ_HEADER_TIMEOUT": "быстро"},
}
for name, env := range tests {
t.Run(name, func(t *testing.T) {
for key, value := range env {
t.Setenv(key, value)
}
_, err := config.Load()
require.Error(t, err)
})
}
}
func TestLoggerSettings(t *testing.T) {
t.Setenv("LOG_LEVEL", "warn")
t.Setenv("LOG_FORMAT", "console")
cfg, err := config.Load()
require.NoError(t, err)
level, err := logger.ParseLevel(cfg.Log.Level)
require.NoError(t, err)
assert.Equal(t, level, cfg.SlogLevel())
format, err := logger.ParseFormat(cfg.Log.Format)
require.NoError(t, err)
assert.Equal(t, format, cfg.LoggerFormat())
}
func TestAddr(t *testing.T) {
t.Setenv("SERVER_HOST", "0.0.0.0")
t.Setenv("SERVER_PORT", "8080")
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "0.0.0.0:8080", cfg.Addr())
}
func TestAddrWithIPv6Host(t *testing.T) {
t.Setenv("SERVER_HOST", "::1")
cfg, err := config.Load()
require.NoError(t, err)
assert.Equal(t, "[::1]:8080", cfg.Addr())
}
func TestLoadIsIndependentOfProcessState(t *testing.T) {
t.Setenv("APP_PORT", "7070")
t.Setenv("SERVER_PORT", "7070")
first, err := config.Load()
require.NoError(t, err)
@@ -180,5 +276,68 @@ func TestLoadIsIndependentOfProcessState(t *testing.T) {
second, err := config.Load()
require.NoError(t, err)
require.Equal(t, first, second)
assert.Equal(t, first, second)
}
func TestRedisDefaultsDisabled(t *testing.T) {
cfg, err := config.Load()
require.NoError(t, err)
assert.False(t, cfg.Redis.Enabled)
assert.Equal(t, "localhost", cfg.Redis.Host)
assert.Equal(t, 6379, cfg.Redis.Port)
assert.Equal(t, -1, cfg.Redis.MaxRetries)
assert.Equal(t, 300*time.Millisecond, cfg.Redis.DialTimeout)
assert.Equal(t, 200*time.Millisecond, cfg.Redis.ReadTimeout)
assert.Equal(t, 200*time.Millisecond, cfg.Redis.WriteTimeout)
assert.False(t, cfg.Cache.Enabled)
assert.Equal(t, 5*time.Minute, cfg.Cache.ChatListTTL)
assert.Equal(t, 10*time.Second, cfg.Cache.LockTTL)
assert.Equal(t, 2*time.Second, cfg.Cache.LockWaitTimeout)
}
func TestRedisEnvOverrides(t *testing.T) {
t.Setenv("REDIS_ENABLED", "true")
t.Setenv("REDIS_HOST", "cache")
t.Setenv("REDIS_PORT", "6380")
t.Setenv("CACHE_ENABLED", "true")
t.Setenv("CACHE_CHAT_LIST_TTL", "1m")
t.Setenv("CACHE_LOCK_TTL", "7s")
t.Setenv("CACHE_LOCK_WAIT_TIMEOUT", "1500ms")
cfg, err := config.Load()
require.NoError(t, err)
assert.True(t, cfg.Redis.Enabled)
assert.Equal(t, "cache", cfg.Redis.Host)
assert.Equal(t, 6380, cfg.Redis.Port)
assert.True(t, cfg.Cache.Enabled)
assert.Equal(t, time.Minute, cfg.Cache.ChatListTTL)
assert.Equal(t, 7*time.Second, cfg.Cache.LockTTL)
assert.Equal(t, 1500*time.Millisecond, cfg.Cache.LockWaitTimeout)
}
func TestInvalidCacheTTL(t *testing.T) {
for _, key := range []string{
"CACHE_CHAT_LIST_TTL",
"CACHE_LOCK_TTL",
"CACHE_LOCK_WAIT_TIMEOUT",
} {
for _, value := range []string{"0s", "-1s"} {
t.Run(key+"/"+value, func(t *testing.T) {
t.Setenv(key, value)
_, err := config.Load()
require.Error(t, err)
var validationErrs validator.ValidationErrors
require.ErrorAs(t, err, &validationErrs)
})
}
}
}
func TestCacheRequiresRedis(t *testing.T) {
t.Setenv("CACHE_ENABLED", "true")
_, err := config.Load()
require.ErrorContains(t, err, "cache.enabled requires redis.enabled")
}