Files
mtusi2026lab5/internal/config/config.go
T
Vladislav Kunetskiy 01b885e846 lab5: очереди и асинхронная обработка изображений
Durable staging handoff, transactional outbox, at-least-once worker with lease fencing, idempotent versioned pipeline, three variants, operator tooling, contract tests and evidence. Includes the review fixes: reprocess source selection and failure settlement, replay guards, stale-job retirement, PNG structural/raster validation, migration rollback safety and audit events.
2026-10-31 14:34:24 +03:00

426 lines
16 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"`
S3 S3 `mapstructure:"s3"`
Broker Broker `mapstructure:"broker"`
Worker Worker `mapstructure:"worker"`
Relay Relay `mapstructure:"relay"`
Outbox Outbox `mapstructure:"outbox"`
Processing Processing `mapstructure:"processing"`
Staging Staging `mapstructure:"staging"`
Admission Admission `mapstructure:"admission"`
}
// Broker carries the AMQP transport settings. The API never publishes; relay
// and worker require a non-empty URL at startup.
type Broker struct {
URL string `mapstructure:"url"`
ConnectTimeout time.Duration `mapstructure:"connect_timeout"`
ConfirmTimeout time.Duration `mapstructure:"confirm_timeout"`
Heartbeat time.Duration `mapstructure:"heartbeat"`
Exchange string `mapstructure:"exchange" validate:"required"`
DLX string `mapstructure:"dlx" validate:"required"`
Queue string `mapstructure:"queue" validate:"required"`
DLQ string `mapstructure:"dlq" validate:"required"`
Prefetch int `mapstructure:"prefetch" validate:"required,gt=0"`
}
// Worker bounds the process that consumes jobs.
type Worker struct {
Concurrency int `mapstructure:"concurrency" validate:"required,gt=0,lte=32"`
Prefetch int `mapstructure:"prefetch" validate:"required,gt=0,lte=100"`
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout" validate:"required,gt=0"`
HealthAddr string `mapstructure:"health_addr" validate:"required"`
}
// Relay bounds the outbox publisher and lease reaper.
type Relay struct {
HealthAddr string `mapstructure:"health_addr" validate:"required"`
}
// Outbox schedules publications and reclaims abandoned relay claims.
type Outbox struct {
PollInterval time.Duration `mapstructure:"poll_interval" validate:"required,gt=0"`
ClaimTTL time.Duration `mapstructure:"claim_ttl" validate:"required,gt=0"`
Batch int `mapstructure:"batch" validate:"required,gt=0,lte=1000"`
ReaperInterval time.Duration `mapstructure:"reaper_interval" validate:"required,gt=0"`
ReconcileAfter time.Duration `mapstructure:"reconcile_after" validate:"omitempty,gt=0"`
Retention time.Duration `mapstructure:"retention" validate:"required,gt=0"`
}
// Processing holds the shared job contract knobs read by API and worker.
type Processing struct {
PipelineVersion int `mapstructure:"pipeline_version" validate:"required,gte=1,lte=2"`
MaxAttempts int `mapstructure:"max_attempts" validate:"required,gte=1,lte=100"`
JobTimeout time.Duration `mapstructure:"job_timeout" validate:"required,gt=0"`
LeaseTTL time.Duration `mapstructure:"lease_ttl" validate:"required,gt=0"`
Heartbeat time.Duration `mapstructure:"heartbeat" validate:"required,gt=0"`
RetryBase time.Duration `mapstructure:"retry_base" validate:"required,gt=0"`
RetryCap time.Duration `mapstructure:"retry_cap" validate:"required,gt=0"`
}
// Staging controls cleanup of objects that are no longer the active source.
type Staging struct {
OrphanGrace time.Duration `mapstructure:"orphan_grace" validate:"required,gt=0"`
FailedRetention time.Duration `mapstructure:"failed_retention" validate:"required,gt=0"`
}
// Admission bounds accepted-but-unfinished work per user and globally.
type Admission struct {
MaxPendingPerUser int `mapstructure:"max_pending_per_user" validate:"required,gte=0"`
MaxPending int `mapstructure:"max_pending" validate:"required,gte=0"`
MaxStagedBytes int64 `mapstructure:"max_staged_bytes" validate:"required,gte=0"`
MaxConcurrent int `mapstructure:"max_concurrent_uploads" validate:"omitempty,gt=0"`
}
// S3 describes the object store and attachment limits. Access keys are checked
// by the object-store constructor rather than the global validator: cmd/migrate
// and unit tests load this config without any S3 credentials.
type S3 struct {
Endpoint string `mapstructure:"endpoint" validate:"required,url"`
PublicEndpoint string `mapstructure:"public_endpoint" validate:"omitempty,url"`
Region string `mapstructure:"region" validate:"required"`
Bucket string `mapstructure:"bucket" validate:"required"`
AccessKeyID string `mapstructure:"access_key_id"`
SecretAccessKey string `mapstructure:"secret_access_key"`
UsePathStyle bool `mapstructure:"use_path_style"`
Timeout time.Duration `mapstructure:"timeout" validate:"required,gt=0"`
MaxUploadBytes int64 `mapstructure:"max_upload_bytes" validate:"required,gt=0,lte=10485760"`
MaxImagePixels int64 `mapstructure:"max_image_pixels" validate:"required,gt=0,lte=40000000"`
PresignTTL time.Duration `mapstructure:"presign_ttl" validate:"required,gt=0,lte=168h"`
SweepInterval time.Duration `mapstructure:"sweep_interval" validate:"required,gt=0"`
SweepGrace time.Duration `mapstructure:"sweep_grace" validate:"required,gt=0"`
}
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"`
ReadTimeout time.Duration `mapstructure:"read_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.read_timeout": "60s",
"server.shutdown_timeout": "10s",
"server.max_body_bytes": 262144,
"s3.endpoint": "http://localhost:8333",
"s3.public_endpoint": "http://localhost:8333",
"s3.region": "us-east-1",
"s3.bucket": "messenger-attachments",
"s3.access_key_id": "",
"s3.secret_access_key": "",
"s3.use_path_style": true,
"s3.timeout": "30s",
"s3.max_upload_bytes": 10485760,
"s3.max_image_pixels": 40000000,
"s3.presign_ttl": "5m",
"s3.sweep_interval": "1m",
"s3.sweep_grace": "10m",
"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",
"broker.url": "",
"broker.connect_timeout": "5s",
"broker.confirm_timeout": "5s",
"broker.heartbeat": "10s",
"broker.exchange": "attachments.jobs",
"broker.dlx": "attachments.dlx",
"broker.queue": "attachment.process.v1",
"broker.dlq": "attachment.process.dead",
"broker.prefetch": 1,
"worker.concurrency": 1,
"worker.prefetch": 1,
"worker.shutdown_timeout": "30s",
"worker.health_addr": ":8081",
"relay.health_addr": ":8082",
"outbox.poll_interval": "1s",
"outbox.claim_ttl": "30s",
"outbox.batch": 20,
"outbox.reaper_interval": "15s",
"outbox.retention": "168h",
"processing.pipeline_version": 1,
"processing.max_attempts": 5,
"processing.job_timeout": "120s",
"processing.lease_ttl": "180s",
"processing.heartbeat": "30s",
"processing.retry_base": "2s",
"processing.retry_cap": "60s",
"staging.orphan_grace": "1h",
"staging.failed_retention": "168h",
"admission.max_pending_per_user": 20,
"admission.max_pending": 200,
"admission.max_staged_bytes": 2147483648,
}
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)
}
}
// The skeleton suggests MAX_UPLOAD_BYTES / MAX_IMAGE_PIXELS. Keep those
// names while storing the values under the S3 section.
for key, env := range map[string]string{
"s3.max_upload_bytes": "MAX_UPLOAD_BYTES",
"s3.max_image_pixels": "MAX_IMAGE_PIXELS",
} {
if err := v.BindEnv(key, env); err != nil {
return Config{}, fmt.Errorf("bind env %q: %w", env, 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")
}
if c.S3.SweepGrace <= c.S3.PresignTTL {
return errors.New("validate config: s3.sweep_grace must exceed s3.presign_ttl")
}
if c.Processing.LeaseTTL < 3*c.Processing.Heartbeat {
return errors.New("validate config: processing.lease_ttl must be at least 3x processing.heartbeat")
}
if c.Processing.JobTimeout >= c.Processing.LeaseTTL {
return errors.New("validate config: processing.job_timeout must be below processing.lease_ttl")
}
if c.Processing.RetryCap < c.Processing.RetryBase {
return errors.New("validate config: processing.retry_cap must be >= processing.retry_base")
}
if c.Staging.FailedRetention < c.Staging.OrphanGrace {
return errors.New("validate config: staging.failed_retention must be >= staging.orphan_grace")
}
if c.Broker.URL != "" {
if _, err := url.Parse(c.Broker.URL); err != nil {
return fmt.Errorf("validate config: broker.url: %w", err)
}
}
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.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)
}