lab2 fix
Application / Lint (pull_request) Canceled after 0s
Application / Unit tests (pull_request) Canceled after 0s
Application / Docker build (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Vladislav Kunetskiy
2026-10-10 00:50:24 +03:00
parent 1e38dbdf35
commit da9fcf346a
36 changed files with 995 additions and 1038 deletions
+30 -17
View File
@@ -20,8 +20,8 @@ import (
)
const (
envPrefix = "APP"
configEnvKey = "APP_CONFIG"
envKey = "APP_ENV"
configName = "config"
defaultEnv = "dev"
configDir = "./config/"
@@ -47,7 +47,7 @@ type Redis struct {
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=0"`
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"`
@@ -55,12 +55,10 @@ type Redis struct {
}
type Cache struct {
Enabled bool `mapstructure:"enabled"`
ChatListTTL time.Duration `mapstructure:"chat_list_ttl" validate:"required,gt=0"`
SessionTTL time.Duration `mapstructure:"session_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"`
LockTimeoutPolicy string `mapstructure:"lock_timeout_policy" validate:"required,oneof=error load"`
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 {
@@ -123,17 +121,15 @@ var defaults = map[string]any{
"redis.host": "localhost",
"redis.port": 6379,
"redis.db": 0,
"redis.max_retries": 3,
"redis.dial_timeout": "5s",
"redis.read_timeout": "3s",
"redis.write_timeout": "3s",
"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.session_ttl": "5m",
"cache.lock_ttl": "10s",
"cache.lock_wait_timeout": "2s",
"cache.lock_timeout_policy": "error",
}
func Load() (Config, error) {
@@ -143,11 +139,16 @@ func Load() (Config, error) {
return Config{}, err
}
v.SetEnvPrefix(envPrefix)
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)
@@ -157,9 +158,21 @@ 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)
@@ -170,7 +183,7 @@ func configureSource(v *viper.Viper) error {
if path := os.Getenv(configEnvKey); path != "" {
v.SetConfigFile(path)
} else {
env := os.Getenv(envPrefix + "_ENV")
env := os.Getenv(envKey)
if env == "" {
env = defaultEnv
}
@@ -222,5 +235,5 @@ func envName(field reflect.StructField) string {
return field.Name
}
return envPrefix + "_" + strings.ToUpper(key)
return strings.ToUpper(key)
}
+57 -55
View File
@@ -28,12 +28,12 @@ func TestDefaults(t *testing.T) {
}
func TestEnvOverridesDefaults(t *testing.T) {
t.Setenv("APP_SERVER_HOST", "127.0.0.1")
t.Setenv("APP_SERVER_PORT", "9090")
t.Setenv("APP_SERVER_READ_HEADER_TIMEOUT", "3s")
t.Setenv("APP_SERVER_SHUTDOWN_TIMEOUT", "30s")
t.Setenv("APP_LOG_LEVEL", "debug")
t.Setenv("APP_LOG_FORMAT", "console")
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()
require.NoError(t, err)
@@ -132,27 +132,36 @@ postgres:
`)
t.Setenv("APP_CONFIG", path)
t.Setenv("APP_SERVER_HOST", "127.0.0.1")
t.Setenv("APP_POSTGRES_PASSWORD", "env")
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, "APP_* переопределяет YAML")
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{
"пустой server.host": {"APP_SERVER_HOST": ""},
"host не адрес и не имя": {"APP_SERVER_HOST": "не адрес"},
"порт ниже диапазона": {"APP_SERVER_PORT": "0"},
"порт выше диапазона": {"APP_SERVER_PORT": "65536"},
"нулевой read header timeout": {"APP_SERVER_READ_HEADER_TIMEOUT": "0s"},
"отрицательный shutdown": {"APP_SERVER_SHUTDOWN_TIMEOUT": "-1s"},
"неизвестный log level": {"APP_LOG_LEVEL": "trace"},
"неизвестный log format": {"APP_LOG_FORMAT": "xml"},
"пустой 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 {
@@ -184,8 +193,8 @@ postgres:
`)
tests := map[string]map[string]string{
"неизвестный ssl mode": {"APP_POSTGRES_SSL_MODE": "bogus"},
"отрицательный max_conns": {"APP_POSTGRES_MAX_CONNS": "-1"},
"неизвестный ssl mode": {"POSTGRES_SSL_MODE": "bogus"},
"отрицательный max_conns": {"POSTGRES_MAX_CONNS": "-1"},
}
for name, env := range tests {
@@ -207,8 +216,8 @@ postgres:
func TestUnparsableValues(t *testing.T) {
tests := map[string]map[string]string{
"порт не число": {"APP_SERVER_PORT": "не-число"},
"timeout не duration": {"APP_SERVER_READ_HEADER_TIMEOUT": "быстро"},
"порт не число": {"SERVER_PORT": "не-число"},
"timeout не duration": {"SERVER_READ_HEADER_TIMEOUT": "быстро"},
}
for name, env := range tests {
@@ -224,8 +233,8 @@ func TestUnparsableValues(t *testing.T) {
}
func TestLoggerSettings(t *testing.T) {
t.Setenv("APP_LOG_LEVEL", "warn")
t.Setenv("APP_LOG_FORMAT", "console")
t.Setenv("LOG_LEVEL", "warn")
t.Setenv("LOG_FORMAT", "console")
cfg, err := config.Load()
require.NoError(t, err)
@@ -240,8 +249,8 @@ func TestLoggerSettings(t *testing.T) {
}
func TestAddr(t *testing.T) {
t.Setenv("APP_SERVER_HOST", "0.0.0.0")
t.Setenv("APP_SERVER_PORT", "8080")
t.Setenv("SERVER_HOST", "0.0.0.0")
t.Setenv("SERVER_PORT", "8080")
cfg, err := config.Load()
require.NoError(t, err)
@@ -250,7 +259,7 @@ func TestAddr(t *testing.T) {
}
func TestAddrWithIPv6Host(t *testing.T) {
t.Setenv("APP_SERVER_HOST", "::1")
t.Setenv("SERVER_HOST", "::1")
cfg, err := config.Load()
require.NoError(t, err)
@@ -259,7 +268,7 @@ func TestAddrWithIPv6Host(t *testing.T) {
}
func TestLoadIsIndependentOfProcessState(t *testing.T) {
t.Setenv("APP_SERVER_PORT", "7070")
t.Setenv("SERVER_PORT", "7070")
first, err := config.Load()
require.NoError(t, err)
@@ -277,25 +286,24 @@ func TestRedisDefaultsDisabled(t *testing.T) {
assert.False(t, cfg.Redis.Enabled)
assert.Equal(t, "localhost", cfg.Redis.Host)
assert.Equal(t, 6379, cfg.Redis.Port)
assert.Equal(t, 5*time.Second, cfg.Redis.DialTimeout)
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, 5*time.Minute, cfg.Cache.SessionTTL)
assert.Equal(t, 10*time.Second, cfg.Cache.LockTTL)
assert.Equal(t, 2*time.Second, cfg.Cache.LockWaitTimeout)
assert.Equal(t, "error", cfg.Cache.LockTimeoutPolicy)
}
func TestRedisEnvOverrides(t *testing.T) {
t.Setenv("APP_REDIS_ENABLED", "true")
t.Setenv("APP_REDIS_HOST", "cache")
t.Setenv("APP_REDIS_PORT", "6380")
t.Setenv("APP_CACHE_ENABLED", "true")
t.Setenv("APP_CACHE_CHAT_LIST_TTL", "1m")
t.Setenv("APP_CACHE_SESSION_TTL", "30s")
t.Setenv("APP_CACHE_LOCK_TTL", "7s")
t.Setenv("APP_CACHE_LOCK_WAIT_TIMEOUT", "1500ms")
t.Setenv("APP_CACHE_LOCK_TIMEOUT_POLICY", "load")
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)
@@ -305,28 +313,15 @@ func TestRedisEnvOverrides(t *testing.T) {
assert.Equal(t, 6380, cfg.Redis.Port)
assert.True(t, cfg.Cache.Enabled)
assert.Equal(t, time.Minute, cfg.Cache.ChatListTTL)
assert.Equal(t, 30*time.Second, cfg.Cache.SessionTTL)
assert.Equal(t, 7*time.Second, cfg.Cache.LockTTL)
assert.Equal(t, 1500*time.Millisecond, cfg.Cache.LockWaitTimeout)
assert.Equal(t, "load", cfg.Cache.LockTimeoutPolicy)
}
func TestInvalidLockTimeoutPolicy(t *testing.T) {
t.Setenv("APP_CACHE_LOCK_TIMEOUT_POLICY", "bogus")
_, err := config.Load()
require.Error(t, err)
var validationErrs validator.ValidationErrors
require.ErrorAs(t, err, &validationErrs)
}
func TestInvalidCacheTTL(t *testing.T) {
for _, key := range []string{
"APP_CACHE_CHAT_LIST_TTL",
"APP_CACHE_SESSION_TTL",
"APP_CACHE_LOCK_TTL",
"APP_CACHE_LOCK_WAIT_TIMEOUT",
"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) {
@@ -339,3 +334,10 @@ func TestInvalidCacheTTL(t *testing.T) {
}
}
}
func TestCacheRequiresRedis(t *testing.T) {
t.Setenv("CACHE_ENABLED", "true")
_, err := config.Load()
require.ErrorContains(t, err, "cache.enabled requires redis.enabled")
}