2.2 KiB · text History 7f67051
use sea_orm::DatabaseConnection;
use std::env;

/// Runtime configuration, sourced entirely from environment variables so the
/// same binary works in local dev, compose, and production without a config
/// file. Every field has a sensible default that matches `compose.yml`.
#[derive(Debug, Clone)]
pub struct Config {
    pub database_url: String,
    pub bind_address: String,
    pub amqp_url: String,
    pub session_duration_hours: i64,
    pub registration_token_duration_days: i64,
    /// Unacked messages a single worker will hold at once.
    pub worker_prefetch: u16,
    /// Delivery attempts before a failing job is dropped.
    pub worker_max_attempts: i64,
    /// Run pending migrations on webservice boot.
    pub auto_migrate: bool,
    /// Allow public self-registration (still requires a valid invite token).
    pub registration_enabled: bool,
}

impl Config {
    pub fn from_env() -> Self {
        Config {
            database_url: env::var("DATABASE_URL").unwrap_or_else(|_| {
                "postgres://app_user:app_password@localhost:5433/app".to_string()
            }),
            bind_address: env::var("BIND_ADDRESS").unwrap_or_else(|_| "0.0.0.0:3999".to_string()),
            amqp_url: env::var("AMQP_URL")
                .unwrap_or_else(|_| "amqp://app_user:app_password@localhost:5674/%2f".to_string()),
            session_duration_hours: parse_or("SESSION_DURATION_HOURS", 24),
            registration_token_duration_days: parse_or("REGISTRATION_TOKEN_DURATION_DAYS", 7),
            worker_prefetch: parse_or("WORKER_PREFETCH", 4),
            worker_max_attempts: parse_or("WORKER_MAX_ATTEMPTS", 5),
            auto_migrate: parse_bool("AUTO_MIGRATE", true),
            registration_enabled: parse_bool("REGISTRATION_ENABLED", false),
        }
    }
}

fn parse_or<T: std::str::FromStr>(key: &str, default: T) -> T {
    env::var(key).ok().and_then(|v| v.parse().ok()).unwrap_or(default)
}

fn parse_bool(key: &str, default: bool) -> bool {
    env::var(key)
        .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
        .unwrap_or(default)
}

pub async fn create_db_connection(database_url: &str) -> Result<DatabaseConnection, sea_orm::DbErr> {
    sea_orm::Database::connect(database_url).await
}