2.5 KiB · text History 2264215
use sea_orm::DatabaseConnection;
use std::env;

/// Runtime configuration, sourced entirely from the environment so the same
/// binary works across local, container, and CI without a config file.
#[derive(Debug, Clone)]
pub struct Config {
    /// Display name shown in templates (title, nav brand, theme key).
    pub app_name: String,
    pub database_url: String,
    pub bind_address: String,
    pub session_duration_hours: i64,
    pub registration_token_duration_days: i64,
    /// Run pending migrations on startup.
    pub auto_migrate: bool,
    /// Allow `/register` without an invite link. Invite tokens are still
    /// required to actually create the account.
    pub registration_enabled: bool,
    /// Minimum trust level required to mint NEW tags (Discourse default: 3).
    /// Lower-tier users can still apply existing tags. Staff always can.
    pub min_trust_to_create_tag: i32,
}

impl Config {
    pub fn from_env() -> Self {
        Config {
            app_name: env::var("APP_NAME").unwrap_or_else(|_| "recourse".to_string()),
            database_url: env::var("DATABASE_URL").unwrap_or_else(|_| {
                // Host port 5439 (not 5432) — 5432 is commonly taken by other
                // local Postgres containers. Matches compose.yml's mapping.
                "postgres://recourse_user:recourse_password@localhost:5439/recourse".to_string()
            }),
            bind_address: env::var("BIND_ADDRESS").unwrap_or_else(|_| "0.0.0.0:3000".to_string()),
            session_duration_hours: env::var("SESSION_DURATION_HOURS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(24),
            registration_token_duration_days: env::var("REGISTRATION_TOKEN_DURATION_DAYS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(7),
            auto_migrate: env::var("AUTO_MIGRATE")
                .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
                .unwrap_or(true),
            registration_enabled: env::var("REGISTRATION_ENABLED")
                .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
                .unwrap_or(false),
            min_trust_to_create_tag: env::var("MIN_TRUST_TO_CREATE_TAG")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(3),
        }
    }
}

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