Files
lincodex/backend/config/config.go
T

434 lines
14 KiB
Go

package config
import (
"errors"
"fmt"
"net"
"net/netip"
"os"
"strconv"
"strings"
"time"
)
const (
defaultHTTPAddr = ":8080"
defaultMetricsAddr = ":9090"
defaultRedisAddr = "localhost:6379"
defaultLogLevel = "info"
defaultRedisTimeout = time.Second
defaultReadinessTimeout = time.Second
defaultShutdownTimeout = 10 * time.Second
// Startup migrations are on by default so a deployed binary never serves
// with a schema older than the one it was built for.
defaultDatabaseMigrateOnStart = true
maxPortNumber = 65535
)
type Config struct {
HTTPAddr string
MetricsAddr string
DatabaseURL string
// DatabaseMigrateOnStart applies embedded migrations before serving.
DatabaseMigrateOnStart bool
RedisAddr string
RedisPassword string
RedisDB int
RedisTimeout time.Duration
SeaweedFSEndpoint string
SeaweedFSAccessKey string
SeaweedFSSecretKey string
SeaweedFSBucket string
SeaweedFSRegion string
SeaweedFSTimeout time.Duration
KafkaBrokers []string
// KafkaEventsTopic receives every published domain event.
KafkaEventsTopic string
KafkaEventsTopicPartitions int32
// KafkaEventsTopicReplicationFactor is -1 for the broker default.
KafkaEventsTopicReplicationFactor int16
// KafkaEventsTopicMinInsyncReplicas is 0 for the broker default.
KafkaEventsTopicMinInsyncReplicas int16
// KafkaProvisionTopics lets the relay create a missing events topic.
KafkaProvisionTopics bool
// RelayEnabled runs the outbox relay next to the HTTP servers.
RelayEnabled bool
RelayBatchSize int
RelayPollInterval time.Duration
RelayProduceTimeout time.Duration
// RelayStatementTimeout bounds each SQL statement of a relay pass.
RelayStatementTimeout time.Duration
RelayBackoffInitial time.Duration
RelayBackoffMax time.Duration
// ConsumerEnabled runs the registered event consumers next to the HTTP
// servers.
ConsumerEnabled bool
// NotificationSyntheticEnabled lets the inbox consume and render the
// synthetic notification event. Off by default; a development or browser
// test stand turns it on.
NotificationSyntheticEnabled bool
// ConsumerGroupPrefix and a consumer name form the consumer group ID.
ConsumerGroupPrefix string
ConsumerMaxAttempts int
ConsumerBackoffInitial time.Duration
ConsumerBackoffMax time.Duration
// ConsumerHandlerTimeout bounds one consumer transaction.
ConsumerHandlerTimeout time.Duration
ConsumerMaxPollRecords int
ConsumerCommitTimeout time.Duration
// ConsumerShutdownGrace bounds the record in progress after shutdown
// begins.
ConsumerShutdownGrace time.Duration
// ConsumerRebalanceTimeout is the Kafka rebalance timeout of every
// consumer group member.
ConsumerRebalanceTimeout time.Duration
// JobsEnabled runs the scheduled job worker next to the HTTP servers
// when a job handler is registered.
JobsEnabled bool
JobsPollInterval time.Duration
JobsBatchSize int
JobsLeaseDuration time.Duration
// JobsMaxAttempts applies to jobs scheduled without their own limit.
JobsMaxAttempts int
JobsBackoffInitial time.Duration
JobsBackoffMax time.Duration
// JobsShutdownGrace bounds the job in progress after shutdown begins.
JobsShutdownGrace time.Duration
// EmailProvider selects the only active mail transport. Settings of the
// other transports are not loaded.
EmailProvider EmailProvider
// EmailFrom is the sender mailbox for every outgoing message.
EmailFrom string
// EmailAccount labels the provider account that new deliveries are
// pinned to. It is configuration identity, never a credential.
EmailAccount string
EmailTimeout time.Duration
// EmailQuotaDaily and EmailQuotaMonthly limit the recipients sent
// through the configured provider account per UTC day and UTC month.
EmailQuotaDaily int
EmailQuotaMonthly int
// EmailServiceReserveDaily and EmailServiceReserveMonthly keep recipients
// of the daily and monthly quota free for service mail: product
// notifications are admitted only while the windows stay above them.
EmailServiceReserveDaily int
EmailServiceReserveMonthly int
// AppPublicURL is the public origin without a trailing slash, for links
// in mail.
AppPublicURL string
ResendAPIKey string
SMTPHost string
SMTPPort int
SMTPUsername string
SMTPPassword string
SMTPTLSMode SMTPTLSMode
LogLevel string
ReadinessTimeout time.Duration
ShutdownTimeout time.Duration
// PasswordHashConcurrency is the number of password hash derivations
// that may run at once; further logins and registrations wait.
PasswordHashConcurrency int
// IdentityKeySecret seeds domain-separated HMAC keys for idempotency
// scopes, rate limit buckets, and session CSRF tokens. Empty means a random
// secret for the life of the process.
IdentityKeySecret string
// IdentityAllowEphemeralKey lets a development stand run without
// IDENTITY_KEY_SECRET, with a random secret per process.
IdentityAllowEphemeralKey bool
// VerificationMailMinInterval and VerificationMailDailyLimit bound the
// verification messages to one address: the registration and every
// resend count against both.
VerificationMailMinInterval time.Duration
VerificationMailDailyLimit int
// IdentityClientHourlyLimit bounds the registrations and resends of one
// client network address per hour.
IdentityClientHourlyLimit int
// IdentityLoginEmailHourlyLimit bounds login attempts for one normalized
// email address per hour.
IdentityLoginEmailHourlyLimit int
// IdentitySessionIdleTimeout ends a session after this much inactivity.
IdentitySessionIdleTimeout time.Duration
// IdentitySessionAbsoluteLifetime is the maximum lifetime of a session,
// even when it remains active.
IdentitySessionAbsoluteLifetime time.Duration
// AssessmentDemoCategoriesEnabled explicitly enables synthetic demo category
// assignment. Reviewed source provenance is required separately.
AssessmentDemoCategoriesEnabled bool
// Semantic configures semantic matching and repository checks.
Semantic SemanticSettings
// CodeRunner configures the client of the own code runner. It is disabled
// unless CODE_RUNNER_URL is set.
CodeRunner CodeRunnerSettings
// Practice configures the debug run limits and the practice queue worker.
Practice PracticeSettings
// TrustedProxyCIDRs are the reverse proxies in front of the API. The
// client address is taken from X-Forwarded-For only through them (see
// middleware.ClientIP). Empty trusts no proxy.
TrustedProxyCIDRs []netip.Prefix
}
type LookupEnv func(string) (string, bool)
func Load() (Config, error) {
return LoadFromEnv(os.LookupEnv)
}
func LoadFromEnv(lookup LookupEnv) (Config, error) {
config := Config{
HTTPAddr: valueOrDefault(lookup, "HTTP_ADDR", defaultHTTPAddr),
MetricsAddr: valueOrDefault(lookup, "METRICS_ADDR", defaultMetricsAddr),
DatabaseURL: DatabaseURLFromEnv(lookup),
RedisAddr: strings.TrimSpace(valueOrDefault(lookup, "REDIS_ADDR", defaultRedisAddr)),
RedisPassword: valueOrDefault(lookup, "REDIS_PASSWORD", ""),
RedisTimeout: defaultRedisTimeout,
SeaweedFSEndpoint: strings.TrimSpace(valueOrDefault(lookup, "SEAWEEDFS_ENDPOINT", defaultSeaweedFSEndpoint)),
SeaweedFSAccessKey: valueOrDefault(lookup, "SEAWEEDFS_ACCESS_KEY", ""),
SeaweedFSSecretKey: valueOrDefault(lookup, "SEAWEEDFS_SECRET_KEY", ""),
SeaweedFSBucket: strings.TrimSpace(valueOrDefault(lookup, "SEAWEEDFS_BUCKET", defaultSeaweedFSBucket)),
SeaweedFSRegion: strings.TrimSpace(valueOrDefault(lookup, "SEAWEEDFS_REGION", defaultSeaweedFSRegion)),
SeaweedFSTimeout: defaultSeaweedFSTimeout,
KafkaBrokers: parseKafkaBrokers(valueOrDefault(lookup, "KAFKA_BROKERS", defaultKafkaBrokers)),
LogLevel: strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "LOG_LEVEL", defaultLogLevel))),
ReadinessTimeout: defaultReadinessTimeout,
ShutdownTimeout: defaultShutdownTimeout,
}
if err := config.loadRedis(lookup); err != nil {
return Config{}, err
}
if err := config.loadKafkaTopics(lookup); err != nil {
return Config{}, err
}
if err := config.loadRelay(lookup); err != nil {
return Config{}, err
}
if err := config.loadConsumer(lookup); err != nil {
return Config{}, err
}
if err := config.loadNotification(lookup); err != nil {
return Config{}, err
}
if err := config.loadJobs(lookup); err != nil {
return Config{}, err
}
if err := config.loadMail(lookup); err != nil {
return Config{}, err
}
if err := config.loadPasswordHash(lookup); err != nil {
return Config{}, err
}
if err := config.loadIdentityAndProxySettings(lookup); err != nil {
return Config{}, err
}
var err error
config.DatabaseMigrateOnStart, err = boolOrDefault(lookup, "DATABASE_MIGRATE_ON_START", defaultDatabaseMigrateOnStart)
if err != nil {
return Config{}, err
}
config.SeaweedFSTimeout, err = durationOrDefault(lookup, "SEAWEEDFS_TIMEOUT", config.SeaweedFSTimeout)
if err != nil {
return Config{}, err
}
config.ReadinessTimeout, err = durationOrDefault(lookup, "READINESS_TIMEOUT", config.ReadinessTimeout)
if err != nil {
return Config{}, err
}
config.ShutdownTimeout, err = durationOrDefault(lookup, "SHUTDOWN_TIMEOUT", config.ShutdownTimeout)
if err != nil {
return Config{}, err
}
if err := config.Validate(); err != nil {
return Config{}, err
}
return config, nil
}
func (config *Config) loadIdentityAndProxySettings(lookup LookupEnv) error {
if err := config.loadIdentity(lookup); err != nil {
return err
}
if err := config.loadAssessment(lookup); err != nil {
return err
}
semantic, err := LoadSemanticSettings(lookup)
if err != nil {
return err
}
config.Semantic = semantic
codeRunner, err := LoadCodeRunnerSettings(lookup)
if err != nil {
return err
}
config.CodeRunner = codeRunner
practice, err := LoadPracticeSettings(lookup, codeRunner.RequestTimeout)
if err != nil {
return err
}
config.Practice = practice
return config.loadTrustedProxies(lookup)
}
func (config Config) Validate() error {
if err := config.ValidateSeaweedFS(); err != nil {
return err
}
if err := config.ValidateRedis(); err != nil {
return err
}
if err := config.ValidateKafka(); err != nil {
return err
}
if err := config.ValidateRelay(); err != nil {
return err
}
if err := config.ValidateMail(); err != nil {
return err
}
if err := config.ValidatePasswordHash(); err != nil {
return err
}
if err := config.ValidateIdentity(); err != nil {
return err
}
if err := validateAddress("HTTP_ADDR", config.HTTPAddr); err != nil {
return err
}
if err := validateAddress("METRICS_ADDR", config.MetricsAddr); err != nil {
return err
}
if config.ReadinessTimeout <= 0 {
return errors.New("Config.Validate - READINESS_TIMEOUT must be positive")
}
if config.ShutdownTimeout <= 0 {
return errors.New("Config.Validate - SHUTDOWN_TIMEOUT must be positive")
}
// The consumer and job shutdown graces are checked against
// SHUTDOWN_TIMEOUT, so they follow that check.
if err := config.ValidateConsumer(); err != nil {
return err
}
if err := config.ValidateJobs(); err != nil {
return err
}
switch config.LogLevel {
case "debug", "info", "warn", "error":
default:
return errors.New("Config.Validate - LOG_LEVEL must be one of debug, info, warn, or error")
}
return nil
}
func valueOrDefault(lookup LookupEnv, key, fallback string) string {
if value, ok := lookup(key); ok {
return value
}
return fallback
}
// DatabaseURLFromEnv reads DATABASE_URL for commands that need only the
// database, such as the migration command.
func DatabaseURLFromEnv(lookup LookupEnv) string {
return strings.TrimSpace(valueOrDefault(lookup, "DATABASE_URL", ""))
}
// boolOrDefault accepts only "true" or "false", ignoring case and surrounding
// spaces. strconv.ParseBool would also accept 1, t, and similar shorthands,
// which are easy to mistype in deployment files.
func boolOrDefault(lookup LookupEnv, key string, fallback bool) (bool, error) {
value, ok := lookup(key)
if !ok {
return fallback, nil
}
switch strings.ToLower(strings.TrimSpace(value)) {
case "true":
return true, nil
case "false":
return false, nil
default:
return false, fmt.Errorf("config.boolOrDefault - %s must be true or false", key)
}
}
// intOrDefault parses a decimal integer, ignoring surrounding spaces. An empty
// value is an error rather than the default.
func intOrDefault(lookup LookupEnv, key string, fallback int) (int, error) {
value, ok := lookup(key)
if !ok {
return fallback, nil
}
number, err := strconv.Atoi(strings.TrimSpace(value))
if err != nil {
return 0, fmt.Errorf("config.intOrDefault - %s must be an integer", key)
}
return number, nil
}
func durationOrDefault(lookup LookupEnv, key string, fallback time.Duration) (time.Duration, error) {
value, ok := lookup(key)
if !ok {
return fallback, nil
}
duration, err := time.ParseDuration(value)
if err != nil {
return 0, fmt.Errorf("config.durationOrDefault - parse %s: %w", key, err)
}
return duration, nil
}
func validateAddress(name, address string) error {
if address == "" {
return fmt.Errorf("config.validateAddress - %s must not be empty", name)
}
_, port, err := net.SplitHostPort(address)
if err != nil {
return fmt.Errorf("config.validateAddress - %s must be a host:port address: %w", name, err)
}
number, err := strconv.Atoi(port)
if err != nil || number < 0 || number > maxPortNumber {
return fmt.Errorf("config.validateAddress - %s port must be between 0 and %d", name, maxPortNumber)
}
return nil
}
func (config *Config) loadRedis(lookup LookupEnv) error {
if value, ok := lookup("REDIS_DB"); ok {
database, err := strconv.Atoi(value)
if err != nil {
return fmt.Errorf("Config.loadRedis - parse REDIS_DB: %w", err)
}
config.RedisDB = database
}
var err error
config.RedisTimeout, err = durationOrDefault(lookup, "REDIS_TIMEOUT", config.RedisTimeout)
return err
}
func (config Config) ValidateRedis() error {
if err := validateAddress("REDIS_ADDR", config.RedisAddr); err != nil {
return err
}
// validateAddress already checked both parsing operations above.
host, port, _ := net.SplitHostPort(config.RedisAddr)
number, _ := strconv.Atoi(port)
if host == "" || number == 0 {
return errors.New("Config.ValidateRedis - REDIS_ADDR must contain a host and a nonzero port")
}
if config.RedisDB < 0 {
return errors.New("Config.ValidateRedis - REDIS_DB must not be negative")
}
if config.RedisTimeout <= 0 {
return errors.New("Config.ValidateRedis - REDIS_TIMEOUT must be positive")
}
return nil
}