forked from mtusi2026/mtusi2026lab6
chore: import lab5 baseline
This commit is contained in:
@@ -0,0 +1,416 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type ServerConfig struct {
|
||||
Address string
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
SessionTTL time.Duration
|
||||
IdempotencyTTL time.Duration
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
DBMaxConnectionAge time.Duration
|
||||
DBMaxConnectionIdle time.Duration
|
||||
DBHealthCheckPeriod time.Duration
|
||||
DependencyTimeout time.Duration
|
||||
RequestTimeout time.Duration
|
||||
HTTPReadHeaderTimeout time.Duration
|
||||
HTTPReadTimeout time.Duration
|
||||
HTTPWriteTimeout time.Duration
|
||||
HTTPIdleTimeout time.Duration
|
||||
HTTPShutdownTimeout time.Duration
|
||||
PasswordMemoryKiB uint32
|
||||
PasswordIterations uint32
|
||||
PasswordParallelism uint8
|
||||
PasswordSaltLength uint32
|
||||
PasswordKeyLength uint32
|
||||
SwaggerPort string
|
||||
S3Endpoint string
|
||||
S3Region string
|
||||
S3Bucket string
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
S3UseTLS bool
|
||||
S3Timeout time.Duration
|
||||
AttachmentMaxBytes int64
|
||||
AttachmentMaxPixels int64
|
||||
AttachmentBodyMemory int64
|
||||
AttachmentDecodeMemory int64
|
||||
PipelineVersion int
|
||||
}
|
||||
|
||||
type MigrationConfig struct {
|
||||
DatabaseURL string
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
DBMaxConnectionAge time.Duration
|
||||
DBMaxConnectionIdle time.Duration
|
||||
DBHealthCheckPeriod time.Duration
|
||||
DependencyTimeout time.Duration
|
||||
MigrationTimeout time.Duration
|
||||
}
|
||||
|
||||
type ReconciliationConfig struct {
|
||||
DatabaseURL string
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
DBMaxConnectionAge time.Duration
|
||||
DBMaxConnectionIdle time.Duration
|
||||
DBHealthCheckPeriod time.Duration
|
||||
DependencyTimeout time.Duration
|
||||
S3Endpoint string
|
||||
S3Region string
|
||||
S3Bucket string
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
S3UseTLS bool
|
||||
S3Timeout time.Duration
|
||||
}
|
||||
|
||||
type databaseConfig struct {
|
||||
url string
|
||||
maxConns int
|
||||
minConns int
|
||||
maxConnectionAge time.Duration
|
||||
maxConnectionIdle time.Duration
|
||||
healthCheckPeriod time.Duration
|
||||
dependencyTimeout time.Duration
|
||||
}
|
||||
|
||||
type objectStorageConfig struct {
|
||||
endpoint string
|
||||
region string
|
||||
bucket string
|
||||
accessKey string
|
||||
secretKey string
|
||||
useTLS bool
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func LoadServer() (ServerConfig, error) {
|
||||
values, err := loadValues()
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
|
||||
host, err := requiredString(values, "server.host")
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
port, err := requiredPort(values, "server.port")
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
database, err := loadDatabaseConfig(values)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
cacheURL, err := requiredString(values, "cache.url")
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
store, err := requiredString(values, "server.session_store")
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
if store != "valkey" {
|
||||
return ServerConfig{}, errors.New("server.session_store must be valkey")
|
||||
}
|
||||
|
||||
sessionTTL, err := duration(values, "server.session_ttl", time.Second, 30*24*time.Hour)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
idempotencyTTL, err := duration(values, "server.idempotency_ttl", 24*time.Hour, 30*24*time.Hour)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
requestTimeout, err := duration(values, "server.request_timeout", time.Second, 5*time.Minute)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
readHeaderTimeout, err := duration(values, "server.http.read_header_timeout", time.Second, 5*time.Minute)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
readTimeout, err := duration(values, "server.http.read_timeout", time.Second, 5*time.Minute)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
writeTimeout, err := duration(values, "server.http.write_timeout", time.Second, 5*time.Minute)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
idleTimeout, err := duration(values, "server.http.idle_timeout", time.Second, time.Hour)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
shutdownTimeout, err := duration(values, "server.http.shutdown_timeout", time.Second, 5*time.Minute)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
passwordMemory, err := integer(values, "server.password.memory_kib", 8*1024, 1024*1024)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
passwordIterations, err := integer(values, "server.password.iterations", 1, 20)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
passwordParallelism, err := integer(values, "server.password.parallelism", 1, 255)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
passwordSaltLength, err := integer(values, "server.password.salt_length", 8, 1024)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
passwordKeyLength, err := integer(values, "server.password.key_length", 16, 1024)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
swaggerPort, err := requiredPort(values, "server.swagger_port")
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
storage, err := loadObjectStorageConfig(values)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
attachmentMaxBytes, err := integer(values, "attachments.max_bytes", 1, 10*1024*1024)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
attachmentMaxPixels, err := integer(values, "attachments.max_pixels", 1, 40_000_000)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
attachmentBodyMemory, err := integer(values, "attachments.body_memory_bytes", 1, 1024*1024*1024)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
if int64(attachmentBodyMemory) < int64(attachmentMaxBytes) {
|
||||
return ServerConfig{}, fmt.Errorf("attachments.body_memory_bytes: must be at least %d", attachmentMaxBytes)
|
||||
}
|
||||
attachmentDecodeMemory, err := integer(values, "attachments.decode_memory_bytes", 1, 1024*1024*1024)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
minimumDecodeMemory := int64(attachmentMaxPixels) * 8
|
||||
if int64(attachmentDecodeMemory) < minimumDecodeMemory {
|
||||
return ServerConfig{}, fmt.Errorf("attachments.decode_memory_bytes: must be at least %d", minimumDecodeMemory)
|
||||
}
|
||||
pipelineVersion, err := integer(values, "pipeline.version", 1, 1000)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
|
||||
return ServerConfig{
|
||||
Address: net.JoinHostPort(host, port), DatabaseURL: database.url, CacheURL: cacheURL,
|
||||
SessionTTL: sessionTTL, IdempotencyTTL: idempotencyTTL,
|
||||
DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns),
|
||||
DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle,
|
||||
DBHealthCheckPeriod: database.healthCheckPeriod, DependencyTimeout: database.dependencyTimeout,
|
||||
RequestTimeout: requestTimeout,
|
||||
HTTPReadHeaderTimeout: readHeaderTimeout, HTTPReadTimeout: readTimeout,
|
||||
HTTPWriteTimeout: writeTimeout, HTTPIdleTimeout: idleTimeout,
|
||||
HTTPShutdownTimeout: shutdownTimeout, PasswordMemoryKiB: uint32(passwordMemory),
|
||||
PasswordIterations: uint32(passwordIterations), PasswordParallelism: uint8(passwordParallelism),
|
||||
PasswordSaltLength: uint32(passwordSaltLength), PasswordKeyLength: uint32(passwordKeyLength),
|
||||
SwaggerPort: swaggerPort, S3Endpoint: storage.endpoint, S3Region: storage.region, S3Bucket: storage.bucket,
|
||||
S3AccessKey: storage.accessKey, S3SecretKey: storage.secretKey,
|
||||
S3UseTLS: storage.useTLS, S3Timeout: storage.timeout,
|
||||
AttachmentMaxBytes: int64(attachmentMaxBytes), AttachmentMaxPixels: int64(attachmentMaxPixels),
|
||||
AttachmentBodyMemory: int64(attachmentBodyMemory),
|
||||
AttachmentDecodeMemory: int64(attachmentDecodeMemory),
|
||||
PipelineVersion: pipelineVersion,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func LoadMigration() (MigrationConfig, error) {
|
||||
values, err := loadValues()
|
||||
if err != nil {
|
||||
return MigrationConfig{}, err
|
||||
}
|
||||
database, err := loadDatabaseConfig(values)
|
||||
if err != nil {
|
||||
return MigrationConfig{}, err
|
||||
}
|
||||
migrationTimeout, err := duration(values, "migration.timeout", time.Second, 10*time.Minute)
|
||||
if err != nil {
|
||||
return MigrationConfig{}, err
|
||||
}
|
||||
return MigrationConfig{
|
||||
DatabaseURL: database.url, DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns),
|
||||
DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle,
|
||||
DBHealthCheckPeriod: database.healthCheckPeriod, DependencyTimeout: database.dependencyTimeout,
|
||||
MigrationTimeout: migrationTimeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func LoadReconciliation() (ReconciliationConfig, error) {
|
||||
values, err := loadValues()
|
||||
if err != nil {
|
||||
return ReconciliationConfig{}, err
|
||||
}
|
||||
database, err := loadDatabaseConfig(values)
|
||||
if err != nil {
|
||||
return ReconciliationConfig{}, err
|
||||
}
|
||||
storage, err := loadObjectStorageConfig(values)
|
||||
if err != nil {
|
||||
return ReconciliationConfig{}, err
|
||||
}
|
||||
return ReconciliationConfig{
|
||||
DatabaseURL: database.url, DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns),
|
||||
DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle,
|
||||
DBHealthCheckPeriod: database.healthCheckPeriod, DependencyTimeout: database.dependencyTimeout,
|
||||
S3Endpoint: storage.endpoint, S3Region: storage.region, S3Bucket: storage.bucket,
|
||||
S3AccessKey: storage.accessKey, S3SecretKey: storage.secretKey,
|
||||
S3UseTLS: storage.useTLS, S3Timeout: storage.timeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func loadObjectStorageConfig(values *viper.Viper) (objectStorageConfig, error) {
|
||||
endpoint, err := requiredString(values, "object_storage.endpoint")
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
region, err := requiredString(values, "object_storage.region")
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
bucket, err := requiredString(values, "object_storage.bucket")
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
accessKey, err := requiredString(values, "object_storage.access_key")
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
secretKey, err := requiredString(values, "object_storage.secret_key")
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
useTLS, err := boolean(values, "object_storage.use_tls")
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
timeout, err := duration(values, "object_storage.timeout", time.Second, 5*time.Minute)
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
return objectStorageConfig{
|
||||
endpoint: endpoint, region: region, bucket: bucket, accessKey: accessKey,
|
||||
secretKey: secretKey, useTLS: useTLS, timeout: timeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func loadDatabaseConfig(values *viper.Viper) (databaseConfig, error) {
|
||||
databaseURL, err := requiredString(values, "database.url")
|
||||
if err != nil {
|
||||
return databaseConfig{}, err
|
||||
}
|
||||
maxConns, err := integer(values, "database.max_connections", 1, 100)
|
||||
if err != nil {
|
||||
return databaseConfig{}, err
|
||||
}
|
||||
minConns, err := integer(values, "database.min_connections", 0, maxConns)
|
||||
if err != nil {
|
||||
return databaseConfig{}, err
|
||||
}
|
||||
maxConnectionAge, err := duration(values, "database.max_connection_age", time.Second, 24*time.Hour)
|
||||
if err != nil {
|
||||
return databaseConfig{}, err
|
||||
}
|
||||
maxConnectionIdle, err := duration(values, "database.max_connection_idle", time.Second, 24*time.Hour)
|
||||
if err != nil {
|
||||
return databaseConfig{}, err
|
||||
}
|
||||
healthCheckPeriod, err := duration(values, "database.health_check_period", time.Second, time.Hour)
|
||||
if err != nil {
|
||||
return databaseConfig{}, err
|
||||
}
|
||||
dependencyTimeout, err := duration(values, "database.dependency_timeout", time.Second, time.Minute)
|
||||
if err != nil {
|
||||
return databaseConfig{}, err
|
||||
}
|
||||
return databaseConfig{
|
||||
url: databaseURL, maxConns: maxConns, minConns: minConns,
|
||||
maxConnectionAge: maxConnectionAge, maxConnectionIdle: maxConnectionIdle,
|
||||
healthCheckPeriod: healthCheckPeriod, dependencyTimeout: dependencyTimeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func requiredString(values *viper.Viper, name string) (string, error) {
|
||||
value := strings.TrimSpace(values.GetString(name))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("%s is required", name)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func requiredPort(values *viper.Viper, name string) (string, error) {
|
||||
value, err := requiredString(values, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := integerValue(value, 1, 65535); err != nil {
|
||||
return "", fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func duration(values *viper.Viper, name string, minimum, maximum time.Duration) (time.Duration, error) {
|
||||
value, err := requiredString(values, name)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
parsed, err := time.ParseDuration(value)
|
||||
if err != nil || parsed < minimum || parsed > maximum {
|
||||
return 0, fmt.Errorf("%s: must be between %s and %s", name, minimum, maximum)
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
func integer(values *viper.Viper, name string, minimum, maximum int) (int, error) {
|
||||
value, err := requiredString(values, name)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
parsed, err := integerValue(value, minimum, maximum)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
func integerValue(value string, minimum, maximum int) (int, error) {
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil || parsed < minimum || parsed > maximum {
|
||||
return 0, fmt.Errorf("must be between %d and %d", minimum, maximum)
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
func boolean(values *viper.Viper, name string) (bool, error) {
|
||||
value, err := requiredString(values, name)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
parsed, err := strconv.ParseBool(value)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s: must be true or false", name)
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestLoadReconciliationDoesNotRequireServerSettings(t *testing.T) {
|
||||
setConfigEnvironment(t, validTestConfig)
|
||||
t.Setenv("APP_HOST", "")
|
||||
t.Setenv("CACHE_URL", "")
|
||||
t.Setenv("SWAGGER_PORT", "")
|
||||
|
||||
settings, err := LoadReconciliation()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "attachments", settings.S3Bucket)
|
||||
}
|
||||
|
||||
func TestLoadWorkerUsesYAMLForRuntimeSettings(t *testing.T) {
|
||||
setConfigEnvironment(t, validTestConfig)
|
||||
t.Setenv("WORKER_CONCURRENCY", "64")
|
||||
|
||||
settings, err := LoadWorker()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, settings.Concurrency)
|
||||
require.Equal(t, 5*time.Second, settings.HeartbeatInterval)
|
||||
}
|
||||
|
||||
func TestLoadWorkerRejectsHeartbeatAtLeaseBoundary(t *testing.T) {
|
||||
content := strings.Replace(validTestConfig, "heartbeat_interval: 5s", "heartbeat_interval: 30s", 1)
|
||||
setConfigEnvironment(t, content)
|
||||
|
||||
_, err := LoadWorker()
|
||||
require.ErrorContains(t, err, "heartbeat_interval must be less than worker.lease")
|
||||
}
|
||||
|
||||
func TestLoadValuesRejectsUnknownVersion(t *testing.T) {
|
||||
setConfigEnvironment(t, "version: 2\n")
|
||||
|
||||
_, err := loadValues()
|
||||
require.ErrorContains(t, err, "version: must be 1")
|
||||
}
|
||||
|
||||
func setConfigEnvironment(t *testing.T, content string) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "messenger.yaml")
|
||||
require.NoError(t, os.WriteFile(path, []byte(content), 0o600))
|
||||
t.Setenv("MESSENGER_CONFIG_PATH", path)
|
||||
for name, value := range map[string]string{
|
||||
"APP_HOST": "0.0.0.0", "APP_PORT": "8080", "SWAGGER_PORT": "8081",
|
||||
"DATABASE_URL": "postgres://user:password@postgres:5432/messenger",
|
||||
"CACHE_URL": "redis://valkey:6379/0", "BROKER_URL": "redis://redis-broker:6379/0",
|
||||
"S3_ENDPOINT": "s3:9000", "S3_REGION": "us-east-1", "S3_BUCKET": "attachments",
|
||||
"S3_ACCESS_KEY": "application", "S3_SECRET_KEY": "application-secret",
|
||||
} {
|
||||
t.Setenv(name, value)
|
||||
}
|
||||
}
|
||||
|
||||
const validTestConfig = `version: 1
|
||||
server:
|
||||
session_store: valkey
|
||||
session_ttl: 1h
|
||||
idempotency_ttl: 24h
|
||||
request_timeout: 5s
|
||||
http:
|
||||
read_header_timeout: 5s
|
||||
read_timeout: 10s
|
||||
write_timeout: 10s
|
||||
idle_timeout: 1m
|
||||
shutdown_timeout: 5s
|
||||
password:
|
||||
memory_kib: 65536
|
||||
iterations: 3
|
||||
parallelism: 2
|
||||
salt_length: 16
|
||||
key_length: 32
|
||||
database:
|
||||
min_connections: 0
|
||||
max_connections: 4
|
||||
max_connection_age: 5m
|
||||
max_connection_idle: 1m
|
||||
health_check_period: 30s
|
||||
dependency_timeout: 5s
|
||||
migration:
|
||||
timeout: 30s
|
||||
object_storage:
|
||||
use_tls: false
|
||||
timeout: 5s
|
||||
attachments:
|
||||
max_bytes: 10485760
|
||||
max_pixels: 40000000
|
||||
body_memory_bytes: 67108864
|
||||
decode_memory_bytes: 402653184
|
||||
pipeline:
|
||||
version: 1
|
||||
broker:
|
||||
stream: attachment-jobs
|
||||
consumer_group: attachment-workers
|
||||
failed_stream: attachment-jobs-failed
|
||||
failed_stream_max_length: 10000
|
||||
outbox:
|
||||
batch_size: 32
|
||||
lease: 15s
|
||||
poll_interval: 1s
|
||||
recovery_interval: 10s
|
||||
retry_delay: 2s
|
||||
retention: 168h
|
||||
cleanup_interval: 1m
|
||||
cleanup_batch_size: 1000
|
||||
worker:
|
||||
concurrency: 2
|
||||
prefetch: 4
|
||||
lease: 30s
|
||||
heartbeat_interval: 5s
|
||||
processing_timeout: 20s
|
||||
read_block: 2s
|
||||
reclaim_interval: 5s
|
||||
max_attempts: 5
|
||||
retry:
|
||||
base: 1s
|
||||
max: 30s
|
||||
memory_bytes: 738197504
|
||||
monitoring:
|
||||
metrics_address: 0.0.0.0:9091
|
||||
`
|
||||
@@ -0,0 +1,47 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const supportedConfigVersion = 1
|
||||
|
||||
var environmentKeys = map[string]string{
|
||||
"server.host": "APP_HOST",
|
||||
"server.port": "APP_PORT",
|
||||
"server.swagger_port": "SWAGGER_PORT",
|
||||
"database.url": "DATABASE_URL",
|
||||
"cache.url": "CACHE_URL",
|
||||
"object_storage.endpoint": "S3_ENDPOINT",
|
||||
"object_storage.region": "S3_REGION",
|
||||
"object_storage.bucket": "S3_BUCKET",
|
||||
"object_storage.access_key": "S3_ACCESS_KEY",
|
||||
"object_storage.secret_key": "S3_SECRET_KEY",
|
||||
"broker.url": "BROKER_URL",
|
||||
}
|
||||
|
||||
func loadValues() (*viper.Viper, error) {
|
||||
path := strings.TrimSpace(os.Getenv("MESSENGER_CONFIG_PATH"))
|
||||
if path == "" {
|
||||
return nil, errors.New("MESSENGER_CONFIG_PATH is required")
|
||||
}
|
||||
values := viper.New()
|
||||
values.SetConfigFile(path)
|
||||
if err := values.ReadInConfig(); err != nil {
|
||||
return nil, fmt.Errorf("read messenger config: %w", err)
|
||||
}
|
||||
if version := values.GetInt("version"); version != supportedConfigVersion {
|
||||
return nil, fmt.Errorf("version: must be %d", supportedConfigVersion)
|
||||
}
|
||||
for key, name := range environmentKeys {
|
||||
if err := values.BindEnv(key, name); err != nil {
|
||||
return nil, fmt.Errorf("bind %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type DispatcherConfig struct {
|
||||
DatabaseURL string
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
DBMaxConnectionAge time.Duration
|
||||
DBMaxConnectionIdle time.Duration
|
||||
DBHealthCheckPeriod time.Duration
|
||||
DependencyTimeout time.Duration
|
||||
BrokerURL string
|
||||
Stream string
|
||||
ConsumerGroup string
|
||||
FailedStream string
|
||||
FailedStreamMaxLength int64
|
||||
BatchSize int
|
||||
LeaseDuration time.Duration
|
||||
PollInterval time.Duration
|
||||
RecoveryInterval time.Duration
|
||||
RetryDelay time.Duration
|
||||
Retention time.Duration
|
||||
CleanupInterval time.Duration
|
||||
CleanupBatchSize int
|
||||
MetricsAddress string
|
||||
}
|
||||
|
||||
type WorkerConfig struct {
|
||||
DatabaseURL string
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
DBMaxConnectionAge time.Duration
|
||||
DBMaxConnectionIdle time.Duration
|
||||
DBHealthCheckPeriod time.Duration
|
||||
DependencyTimeout time.Duration
|
||||
S3Endpoint string
|
||||
S3Region string
|
||||
S3Bucket string
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
S3UseTLS bool
|
||||
S3Timeout time.Duration
|
||||
BrokerURL string
|
||||
Stream string
|
||||
ConsumerGroup string
|
||||
FailedStream string
|
||||
FailedStreamMaxLength int64
|
||||
Concurrency int
|
||||
Prefetch int
|
||||
LeaseDuration time.Duration
|
||||
HeartbeatInterval time.Duration
|
||||
ProcessingTimeout time.Duration
|
||||
ReadBlock time.Duration
|
||||
ReclaimInterval time.Duration
|
||||
MaxAttempts int
|
||||
RetryBase time.Duration
|
||||
RetryMax time.Duration
|
||||
AttachmentMaxBytes int64
|
||||
AttachmentMaxPixels int64
|
||||
MemoryBytes int64
|
||||
MetricsAddress string
|
||||
}
|
||||
|
||||
type JobAdminConfig struct {
|
||||
DatabaseURL string
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
DBMaxConnectionAge time.Duration
|
||||
DBMaxConnectionIdle time.Duration
|
||||
DBHealthCheckPeriod time.Duration
|
||||
DependencyTimeout time.Duration
|
||||
}
|
||||
|
||||
type brokerConfig struct {
|
||||
url string
|
||||
stream string
|
||||
consumerGroup string
|
||||
failedStream string
|
||||
failedStreamMaxLength int
|
||||
}
|
||||
|
||||
func LoadJobAdmin() (JobAdminConfig, error) {
|
||||
values, err := loadValues()
|
||||
if err != nil {
|
||||
return JobAdminConfig{}, err
|
||||
}
|
||||
database, err := loadDatabaseConfig(values)
|
||||
if err != nil {
|
||||
return JobAdminConfig{}, err
|
||||
}
|
||||
return JobAdminConfig{
|
||||
DatabaseURL: database.url, DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns),
|
||||
DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle,
|
||||
DBHealthCheckPeriod: database.healthCheckPeriod, DependencyTimeout: database.dependencyTimeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func LoadDispatcher() (DispatcherConfig, error) {
|
||||
values, err := loadValues()
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
database, err := loadDatabaseConfig(values)
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
broker, err := loadBrokerConfig(values)
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
batchSize, err := integer(values, "outbox.batch_size", 1, 1000)
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
leaseDuration, err := duration(values, "outbox.lease", time.Second, 10*time.Minute)
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
pollInterval, err := duration(values, "outbox.poll_interval", time.Millisecond, time.Minute)
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
recoveryInterval, err := duration(values, "outbox.recovery_interval", time.Second, time.Hour)
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
retryDelay, err := duration(values, "outbox.retry_delay", time.Second, time.Hour)
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
retention, err := duration(values, "outbox.retention", time.Hour, 365*24*time.Hour)
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
cleanupInterval, err := duration(values, "outbox.cleanup_interval", time.Minute, 24*time.Hour)
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
cleanupBatchSize, err := integer(values, "outbox.cleanup_batch_size", 1, 1000)
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
metricsAddress, err := metricsAddress(values)
|
||||
if err != nil {
|
||||
return DispatcherConfig{}, err
|
||||
}
|
||||
return DispatcherConfig{
|
||||
DatabaseURL: database.url, DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns),
|
||||
DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle,
|
||||
DBHealthCheckPeriod: database.healthCheckPeriod, DependencyTimeout: database.dependencyTimeout,
|
||||
BrokerURL: broker.url, Stream: broker.stream, ConsumerGroup: broker.consumerGroup,
|
||||
FailedStream: broker.failedStream, FailedStreamMaxLength: int64(broker.failedStreamMaxLength),
|
||||
BatchSize: batchSize, LeaseDuration: leaseDuration, PollInterval: pollInterval,
|
||||
RecoveryInterval: recoveryInterval, RetryDelay: retryDelay,
|
||||
Retention: retention, CleanupInterval: cleanupInterval, CleanupBatchSize: cleanupBatchSize,
|
||||
MetricsAddress: metricsAddress,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func LoadWorker() (WorkerConfig, error) {
|
||||
values, err := loadValues()
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
database, err := loadDatabaseConfig(values)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
storage, err := loadObjectStorageConfig(values)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
broker, err := loadBrokerConfig(values)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
concurrency, err := integer(values, "worker.concurrency", 1, 64)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
prefetch, err := integer(values, "worker.prefetch", concurrency, 1024)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
leaseDuration, err := duration(values, "worker.lease", time.Second, time.Hour)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
heartbeatInterval, err := duration(values, "worker.heartbeat_interval", 100*time.Millisecond, time.Hour)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
if heartbeatInterval >= leaseDuration {
|
||||
return WorkerConfig{}, errors.New("worker.heartbeat_interval must be less than worker.lease")
|
||||
}
|
||||
processingTimeout, err := duration(values, "worker.processing_timeout", time.Second, time.Hour)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
if processingTimeout >= leaseDuration {
|
||||
return WorkerConfig{}, errors.New("worker.processing_timeout must be less than worker.lease")
|
||||
}
|
||||
readBlock, err := duration(values, "worker.read_block", 100*time.Millisecond, time.Minute)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
reclaimInterval, err := duration(values, "worker.reclaim_interval", time.Second, time.Hour)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
maxAttempts, err := integer(values, "worker.max_attempts", 1, 100)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
retryBase, err := duration(values, "worker.retry.base", time.Second, time.Hour)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
retryMax, err := duration(values, "worker.retry.max", time.Second, 24*time.Hour)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
if retryMax < retryBase {
|
||||
return WorkerConfig{}, errors.New("worker.retry.max must be at least worker.retry.base")
|
||||
}
|
||||
attachmentMaxBytes, err := integer(values, "attachments.max_bytes", 1, 10*1024*1024)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
attachmentMaxPixels, err := integer(values, "attachments.max_pixels", 1, 40_000_000)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
memoryBytes, err := integer(values, "worker.memory_bytes", attachmentMaxBytes, 2*1024*1024*1024)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
metricsAddress, err := metricsAddress(values)
|
||||
if err != nil {
|
||||
return WorkerConfig{}, err
|
||||
}
|
||||
return WorkerConfig{
|
||||
DatabaseURL: database.url, DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns),
|
||||
DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle,
|
||||
DBHealthCheckPeriod: database.healthCheckPeriod, DependencyTimeout: database.dependencyTimeout,
|
||||
S3Endpoint: storage.endpoint, S3Region: storage.region, S3Bucket: storage.bucket,
|
||||
S3AccessKey: storage.accessKey, S3SecretKey: storage.secretKey, S3UseTLS: storage.useTLS,
|
||||
S3Timeout: storage.timeout, BrokerURL: broker.url, Stream: broker.stream,
|
||||
ConsumerGroup: broker.consumerGroup, FailedStream: broker.failedStream,
|
||||
FailedStreamMaxLength: int64(broker.failedStreamMaxLength),
|
||||
Concurrency: concurrency, Prefetch: prefetch, LeaseDuration: leaseDuration,
|
||||
HeartbeatInterval: heartbeatInterval, ProcessingTimeout: processingTimeout, ReadBlock: readBlock,
|
||||
ReclaimInterval: reclaimInterval, MaxAttempts: maxAttempts, RetryBase: retryBase, RetryMax: retryMax,
|
||||
AttachmentMaxBytes: int64(attachmentMaxBytes), AttachmentMaxPixels: int64(attachmentMaxPixels),
|
||||
MemoryBytes: int64(memoryBytes), MetricsAddress: metricsAddress,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func metricsAddress(values *viper.Viper) (string, error) {
|
||||
address, err := requiredString(values, "monitoring.metrics_address")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
_, port, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("monitoring.metrics_address: %w", err)
|
||||
}
|
||||
if _, err := integerValue(port, 1, 65535); err != nil {
|
||||
return "", fmt.Errorf("monitoring.metrics_address: %w", err)
|
||||
}
|
||||
return address, nil
|
||||
}
|
||||
|
||||
func loadBrokerConfig(values *viper.Viper) (brokerConfig, error) {
|
||||
url, err := requiredString(values, "broker.url")
|
||||
if err != nil {
|
||||
return brokerConfig{}, err
|
||||
}
|
||||
stream, err := requiredString(values, "broker.stream")
|
||||
if err != nil {
|
||||
return brokerConfig{}, err
|
||||
}
|
||||
consumerGroup, err := requiredString(values, "broker.consumer_group")
|
||||
if err != nil {
|
||||
return brokerConfig{}, err
|
||||
}
|
||||
failedStream, err := requiredString(values, "broker.failed_stream")
|
||||
if err != nil {
|
||||
return brokerConfig{}, err
|
||||
}
|
||||
failedStreamMaxLength, err := integer(values, "broker.failed_stream_max_length", 100, 10_000_000)
|
||||
if err != nil {
|
||||
return brokerConfig{}, err
|
||||
}
|
||||
return brokerConfig{
|
||||
url: url, stream: stream, consumerGroup: consumerGroup,
|
||||
failedStream: failedStream, failedStreamMaxLength: failedStreamMaxLength,
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user