forked from mtusi2026/mtusi2026lab4
466 lines
9.9 KiB
Go
466 lines
9.9 KiB
Go
package config
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"os"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type Config struct {
|
|
HTTPHost string
|
|
HTTPPort string
|
|
InstanceID string
|
|
|
|
SessionTTL time.Duration
|
|
IdempotencyTTL time.Duration
|
|
SessionCookieSecure bool
|
|
CursorSigningKey string
|
|
|
|
DatabaseURL string
|
|
DatabaseMaxConns int32
|
|
DatabaseMinConns int32
|
|
DatabaseMaxConnLifetime time.Duration
|
|
DatabaseMaxConnIdleTime time.Duration
|
|
DatabaseHealthCheckPeriod time.Duration
|
|
DatabaseConnectTimeout time.Duration
|
|
DatabaseQueryTimeout time.Duration
|
|
|
|
RedisURL string
|
|
RedisCacheTTL time.Duration
|
|
RedisOperationTimeout time.Duration
|
|
RedisPoolSize int
|
|
|
|
S3Endpoint string
|
|
S3Region string
|
|
S3Bucket string
|
|
S3AccessKeyID string
|
|
S3SecretAccessKey string
|
|
S3OperationTimeout time.Duration
|
|
|
|
ReadinessTimeout time.Duration
|
|
ShutdownDrainDelay time.Duration
|
|
ShutdownTimeout time.Duration
|
|
}
|
|
|
|
func Load() (Config, error) {
|
|
instanceID, err := instanceIDFromEnv()
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
sessionTTL, err := secondsDurationFromEnv(
|
|
"SESSION_TTL_SECONDS",
|
|
3600,
|
|
)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
idempotencyTTL, err := secondsDurationFromEnv(
|
|
"IDEMPOTENCY_TTL_SECONDS",
|
|
86400,
|
|
)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
sessionCookieSecure, err := boolFromEnv("SESSION_COOKIE_SECURE", false)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
databaseURL, err := requiredValueOrFile(
|
|
"DATABASE_URL",
|
|
"DATABASE_URL_FILE",
|
|
)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
cursorSigningKey, err := requiredValueOrFile(
|
|
"CURSOR_SIGNING_KEY",
|
|
"CURSOR_SIGNING_KEY_FILE",
|
|
)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
s3AccessKeyID, err := requiredValueOrFile(
|
|
"S3_ACCESS_KEY_ID",
|
|
"S3_ACCESS_KEY_ID_FILE",
|
|
)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
s3SecretAccessKey, err := requiredValueOrFile(
|
|
"S3_SECRET_ACCESS_KEY",
|
|
"S3_SECRET_ACCESS_KEY_FILE",
|
|
)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
s3OperationTimeout, err := durationFromEnv("S3_OPERATION_TIMEOUT", 5*time.Second)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
databaseMaxConns, err := int32FromEnv("DB_MAX_CONNS", 10, 1)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
databaseMinConns, err := int32FromEnv("DB_MIN_CONNS", 2, 0)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
databaseMaxConnLifetime, err := durationFromEnv(
|
|
"DB_MAX_CONN_LIFETIME",
|
|
30*time.Minute,
|
|
)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
databaseMaxConnIdleTime, err := durationFromEnv(
|
|
"DB_MAX_CONN_IDLE_TIME",
|
|
5*time.Minute,
|
|
)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
databaseHealthCheckPeriod, err := durationFromEnv(
|
|
"DB_HEALTH_CHECK_PERIOD",
|
|
30*time.Second,
|
|
)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
databaseConnectTimeout, err := durationFromEnv(
|
|
"DB_CONNECT_TIMEOUT",
|
|
5*time.Second,
|
|
)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
databaseQueryTimeout, err := durationFromEnv(
|
|
"DB_QUERY_TIMEOUT",
|
|
3*time.Second,
|
|
)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
redisURL, err := optionalValueOrFile("CACHE_URL", "CACHE_URL_FILE")
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
redisCacheTTL, err := durationFromEnv(
|
|
"CACHE_TTL",
|
|
5*time.Minute,
|
|
)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
redisOperationTimeout, err := durationFromEnv(
|
|
"CACHE_OPERATION_TIMEOUT",
|
|
250*time.Millisecond,
|
|
)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
redisPoolSize, err := int32FromEnv("CACHE_POOL_SIZE", 10, 1)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
readinessTimeout, err := durationFromEnv(
|
|
"READINESS_TIMEOUT",
|
|
2*time.Second,
|
|
)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
shutdownDrainDelay, err := durationFromEnv(
|
|
"SHUTDOWN_DRAIN_DELAY",
|
|
2*time.Second,
|
|
)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
shutdownTimeout, err := durationFromEnv(
|
|
"SHUTDOWN_TIMEOUT",
|
|
10*time.Second,
|
|
)
|
|
if err != nil {
|
|
return Config{}, err
|
|
}
|
|
|
|
if databaseMinConns > databaseMaxConns {
|
|
return Config{}, errors.New(
|
|
"DB_MIN_CONNS must not be greater than DB_MAX_CONNS",
|
|
)
|
|
}
|
|
|
|
if idempotencyTTL < 24*time.Hour {
|
|
return Config{}, errors.New(
|
|
"IDEMPOTENCY_TTL_SECONDS must be at least 86400",
|
|
)
|
|
}
|
|
|
|
if shutdownDrainDelay >= shutdownTimeout {
|
|
return Config{}, errors.New(
|
|
"SHUTDOWN_DRAIN_DELAY must be less than SHUTDOWN_TIMEOUT",
|
|
)
|
|
}
|
|
|
|
return Config{
|
|
HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"),
|
|
HTTPPort: envOrDefault("APP_PORT", "8080"),
|
|
InstanceID: instanceID,
|
|
SessionTTL: sessionTTL,
|
|
IdempotencyTTL: idempotencyTTL,
|
|
SessionCookieSecure: sessionCookieSecure,
|
|
CursorSigningKey: cursorSigningKey,
|
|
|
|
DatabaseURL: databaseURL,
|
|
DatabaseMaxConns: databaseMaxConns,
|
|
DatabaseMinConns: databaseMinConns,
|
|
DatabaseMaxConnLifetime: databaseMaxConnLifetime,
|
|
DatabaseMaxConnIdleTime: databaseMaxConnIdleTime,
|
|
DatabaseHealthCheckPeriod: databaseHealthCheckPeriod,
|
|
DatabaseConnectTimeout: databaseConnectTimeout,
|
|
DatabaseQueryTimeout: databaseQueryTimeout,
|
|
|
|
RedisURL: redisURL,
|
|
RedisCacheTTL: redisCacheTTL,
|
|
RedisOperationTimeout: redisOperationTimeout,
|
|
RedisPoolSize: int(redisPoolSize),
|
|
|
|
S3Endpoint: envOrDefault("S3_ENDPOINT", "http://minio:9000"),
|
|
S3Region: envOrDefault("S3_REGION", "us-east-1"),
|
|
S3Bucket: envOrDefault("S3_BUCKET", "messenger-attachments"),
|
|
S3AccessKeyID: s3AccessKeyID,
|
|
S3SecretAccessKey: s3SecretAccessKey,
|
|
S3OperationTimeout: s3OperationTimeout,
|
|
ReadinessTimeout: readinessTimeout,
|
|
ShutdownDrainDelay: shutdownDrainDelay,
|
|
ShutdownTimeout: shutdownTimeout,
|
|
}, nil
|
|
}
|
|
|
|
var instanceIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
|
|
|
|
func instanceIDFromEnv() (string, error) {
|
|
instanceID := strings.TrimSpace(os.Getenv("INSTANCE_ID"))
|
|
if instanceID == "" {
|
|
hostname, err := os.Hostname()
|
|
if err != nil {
|
|
return "", fmt.Errorf("resolve instance id from hostname: %w", err)
|
|
}
|
|
instanceID = hostname
|
|
}
|
|
|
|
if !instanceIDPattern.MatchString(instanceID) {
|
|
return "", errors.New(
|
|
"INSTANCE_ID or hostname must match [A-Za-z0-9][A-Za-z0-9._-]{0,127}",
|
|
)
|
|
}
|
|
|
|
return instanceID, nil
|
|
}
|
|
|
|
func (c Config) HTTPAddress() string {
|
|
return net.JoinHostPort(c.HTTPHost, c.HTTPPort)
|
|
}
|
|
|
|
func requiredValueOrFile(valueEnv, fileEnv string) (string, error) {
|
|
value, valueExists := os.LookupEnv(valueEnv)
|
|
filePath, fileExists := os.LookupEnv(fileEnv)
|
|
|
|
if valueExists && fileExists {
|
|
return "", fmt.Errorf(
|
|
"%s and %s must not be set at the same time",
|
|
valueEnv,
|
|
fileEnv,
|
|
)
|
|
}
|
|
|
|
if valueExists {
|
|
value = strings.TrimSpace(value)
|
|
if value == "" {
|
|
return "", fmt.Errorf("%s must not be empty", valueEnv)
|
|
}
|
|
|
|
return value, nil
|
|
}
|
|
|
|
if fileExists {
|
|
filePath = strings.TrimSpace(filePath)
|
|
if filePath == "" {
|
|
return "", fmt.Errorf("%s must not be empty", fileEnv)
|
|
}
|
|
|
|
data, err := os.ReadFile(filePath)
|
|
if err != nil {
|
|
return "", fmt.Errorf("read %s: %w", fileEnv, err)
|
|
}
|
|
|
|
value = strings.TrimSpace(string(data))
|
|
if value == "" {
|
|
return "", fmt.Errorf("file from %s must not be empty", fileEnv)
|
|
}
|
|
|
|
return value, nil
|
|
}
|
|
|
|
return "", fmt.Errorf("%s or %s must be set", valueEnv, fileEnv)
|
|
}
|
|
|
|
func optionalValueOrFile(valueEnv, fileEnv string) (string, error) {
|
|
value, valueExists := os.LookupEnv(valueEnv)
|
|
filePath, fileExists := os.LookupEnv(fileEnv)
|
|
|
|
if valueExists && fileExists {
|
|
return "", fmt.Errorf(
|
|
"%s and %s must not be set at the same time",
|
|
valueEnv,
|
|
fileEnv,
|
|
)
|
|
}
|
|
|
|
if valueExists {
|
|
value = strings.TrimSpace(value)
|
|
if value == "" {
|
|
return "", fmt.Errorf("%s must not be empty", valueEnv)
|
|
}
|
|
|
|
return value, nil
|
|
}
|
|
|
|
if fileExists {
|
|
filePath = strings.TrimSpace(filePath)
|
|
if filePath == "" {
|
|
return "", fmt.Errorf("%s must not be empty", fileEnv)
|
|
}
|
|
|
|
data, err := os.ReadFile(filePath)
|
|
if err != nil {
|
|
return "", fmt.Errorf("read %s: %w", fileEnv, err)
|
|
}
|
|
|
|
value = strings.TrimSpace(string(data))
|
|
if value == "" {
|
|
return "", fmt.Errorf("file from %s must not be empty", fileEnv)
|
|
}
|
|
|
|
return value, nil
|
|
}
|
|
|
|
return "", nil
|
|
}
|
|
|
|
func envOrDefault(name, fallback string) string {
|
|
value := strings.TrimSpace(os.Getenv(name))
|
|
if value == "" {
|
|
return fallback
|
|
}
|
|
|
|
return value
|
|
}
|
|
|
|
func int32FromEnv(name string, fallback, minimum int32) (int32, error) {
|
|
raw := strings.TrimSpace(os.Getenv(name))
|
|
if raw == "" {
|
|
return fallback, nil
|
|
}
|
|
|
|
value, err := strconv.ParseInt(raw, 10, 32)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("%s must be an integer: %w", name, err)
|
|
}
|
|
|
|
if value < int64(minimum) {
|
|
return 0, fmt.Errorf("%s must be at least %d", name, minimum)
|
|
}
|
|
|
|
return int32(value), nil
|
|
}
|
|
|
|
func boolFromEnv(name string, fallback bool) (bool, error) {
|
|
raw := strings.TrimSpace(os.Getenv(name))
|
|
if raw == "" {
|
|
return fallback, nil
|
|
}
|
|
|
|
value, err := strconv.ParseBool(raw)
|
|
if err != nil {
|
|
return false, fmt.Errorf("%s must be true or false: %w", name, err)
|
|
}
|
|
|
|
return value, nil
|
|
}
|
|
|
|
func durationFromEnv(name string, fallback time.Duration) (time.Duration, error) {
|
|
raw := strings.TrimSpace(os.Getenv(name))
|
|
if raw == "" {
|
|
return fallback, nil
|
|
}
|
|
|
|
value, err := time.ParseDuration(raw)
|
|
if err != nil {
|
|
return 0, fmt.Errorf(
|
|
"%s must be a Go duration such as 3s or 5m: %w",
|
|
name,
|
|
err,
|
|
)
|
|
}
|
|
|
|
if value <= 0 {
|
|
return 0, fmt.Errorf("%s must be positive", name)
|
|
}
|
|
|
|
return value, nil
|
|
}
|
|
|
|
func secondsDurationFromEnv(
|
|
name string,
|
|
fallbackSeconds int64,
|
|
) (time.Duration, error) {
|
|
raw := strings.TrimSpace(os.Getenv(name))
|
|
if raw == "" {
|
|
raw = strconv.FormatInt(fallbackSeconds, 10)
|
|
}
|
|
|
|
seconds, err := strconv.ParseInt(raw, 10, 64)
|
|
if err != nil {
|
|
return 0, fmt.Errorf(
|
|
"%s must be an integer number of seconds: %w",
|
|
name,
|
|
err,
|
|
)
|
|
}
|
|
|
|
if seconds <= 0 {
|
|
return 0, fmt.Errorf("%s must be positive", name)
|
|
}
|
|
|
|
duration, err := time.ParseDuration(raw + "s")
|
|
if err != nil {
|
|
return 0, fmt.Errorf("%s is too large: %w", name, err)
|
|
}
|
|
|
|
return duration, nil
|
|
}
|