tango-core 0.3.0

The tango schema, entities, migrations, and search contract
Documentation
//! Environment and database selection, shared by every crate.
//!
//! This is the half of configuration that the harvester, the API and a
//! downstream project all need: find the `.env`, and turn a profile name into a
//! connection string. The harvester-specific settings - where yt-dlp lives and
//! whether a YouTube Data API key is configured - live in
//! `tango-harvest::config`, so a crate that only reads the database never has to
//! know they exist.

use anyhow::{Result, anyhow};
use std::path::PathBuf;

/// A resolved database connection, and the profile it came from.
///
/// The profile is carried only for logging: the finished URL is the only thing
/// a caller needs.
pub struct DbConfig {
    db_url: String,
    profile: Option<String>,
}

impl DbConfig {
    /// `profile` selects a database by name; see [`resolve_db_url`].
    pub fn load(profile: Option<&str>) -> Result<Self> {
        load_env();

        let (db_url, profile) = resolve_db_url(profile)?;
        Ok(Self { db_url, profile })
    }

    /// Loads the profile from an environment variable, then resolves it.
    ///
    /// The CLI takes a `--profile` argument; a server has no command line worth
    /// parsing for this, so `tango-api` reads `TANGO_PROFILE` through here. One
    /// resolver, two front doors.
    pub fn from_env_var(profile_var: &str) -> Result<Self> {
        let profile = profile_from_env(profile_var);
        Self::load(profile.as_deref())
    }

    /// A connection string supplied by the caller, not by the environment.
    ///
    /// The two front doors above assume what this project's own binaries have:
    /// a `.env`, or environment variables, and nothing else. A downstream
    /// project that stitches tango into a larger server usually does not work
    /// that way - its configuration comes from its own file, its flags, or a
    /// secret manager - and the only ways to reuse a URL through the other
    /// constructors would be to write it into the process environment first
    /// (`unsafe { std::env::set_var(...) }` since edition 2024) or to re-derive
    /// the connection options by hand. This is the way in.
    ///
    /// Nothing is read here: no `.env` is loaded and no variable is consulted,
    /// so a caller that uses this cannot accidentally end up on a database it
    /// did not name. `profile_name` is `None`, because there is no profile - the
    /// URL is the whole answer.
    pub fn from_url(url: impl Into<String>) -> Self {
        Self {
            db_url: url.into(),
            profile: None,
        }
    }

    pub fn postgres_connection_string(&self) -> &str {
        &self.db_url
    }

    /// The profile in use, for a startup line. None is the default database.
    pub fn profile_name(&self) -> Option<&str> {
        self.profile.as_deref()
    }
}

/// The first `.env` at or above the working directory, if there is one.
///
/// Public because `bootstrap` needs to know whether the file exists before it
/// decides to write one, and walking up twice would be two definitions of where
/// configuration lives.
pub fn env_file() -> Option<PathBuf> {
    let mut dir = std::env::current_dir().ok()?;
    loop {
        let path = dir.join(".env");
        if path.is_file() {
            return Some(path);
        }
        dir = dir.parent()?.to_path_buf();
    }
}

/// Loads the first `.env` found walking up from the working directory.
///
/// `dotenvy::dotenv()` reads only the current directory. That is enough when a
/// binary runs from the project root, which is the documented way to run it,
/// but not from a subdirectory - and `tango-api/` lives in one and shares this
/// file. So every binary walks up, and one `.env` configures all of them.
///
/// Returns the file that was loaded, so a caller that wants to log it can.
/// Nothing found is not an error: every setting can also come from the real
/// environment, and the error that follows is about a missing `DB_URL`, which is
/// more useful than "no .env here".
pub fn load_env() -> Option<PathBuf> {
    let path = env_file();

    match &path {
        Some(path) => {
            let _ = dotenvy::from_path(path);
        }
        None => {
            let _ = dotenvy::dotenv();
        }
    }

    path
}

/// The profile named by an environment variable, trimmed and empty-as-none.
///
/// Kept here rather than in the API so `TANGO_PROFILE` and the CLI's
/// `--profile` cannot disagree about what an empty value means.
pub fn profile_from_env(var: &str) -> Option<String> {
    std::env::var(var)
        .ok()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
}

/// The environment key a profile reads: `staging` means `DB_URL_STAGING`.
///
/// A name rather than a config file. Uppercased and stripped of dashes so a
/// profile with a hyphen in it - `my-test`, the kind a branch name produces -
/// is still a valid shell variable, and the CLI and the API cannot drift into
/// deriving two different keys from the same word.
fn profile_key(name: &str) -> String {
    format!("DB_URL_{}", name.to_uppercase().replace('-', "_"))
}

/// Resolves the connection string, and which profile it came from.
///
/// `DB_URL`, and nothing else. A profile is a name for a database resolved by
/// convention rather than a config file: `--profile staging` reads
/// `DB_URL_STAGING`, uppercased.
///
/// A convention rather than a `tango-rs.yaml` on purpose. The only thing that
/// differs between environments is the connection string, so a config file
/// would hold a list of environment-variable names - which is what this is,
/// without a file to keep in sync. If profiles ever need more than a URL (a
/// table prefix, say), that is when a file starts earning its place.
///
/// Deliberately *not* a push mechanism. A profile here chooses which database a
/// command talks to; it does not copy anything between them. To put data in a
/// second environment, harvest once and point the same code at it - or use
/// `pg_dump`, which is the right tool and needs nothing from this project.
///
/// The individual `DB_USERNAME` / `DB_PASSWORD` / `DB_HOST` / `DB_NAME` /
/// `DB_PORT` / `DB_SSLMODE` settings are gone. They assembled a URL out of parts
/// that a managed provider - which is what most people here are using - cannot
/// be configured with, because it needs `?sslmode=require` on the end and there
/// was nowhere to put it except the URL itself. Two ways to say the same thing
/// meant two things to document, and a URL is what every provider hands you.
fn resolve_db_url(profile: Option<&str>) -> Result<(String, Option<String>)> {
    if let Some(name) = profile {
        let key = profile_key(name);
        return match std::env::var(&key) {
            Ok(url) if !url.trim().is_empty() => Ok((url, Some(name.to_string()))),
            _ => Err(anyhow!(
                "profile {name:?} needs {key} in the environment. \
                 A profile is a name for a database: set {key} to its connection string, \
                 or drop --profile to use DB_URL."
            )),
        };
    }

    match std::env::var("DB_URL") {
        Ok(url) if !url.trim().is_empty() => Ok((url, None)),
        // Named as one setting, because that is what is missing. Listing the
        // five that used to work would be telling someone to set things that no
        // longer do anything.
        _ => Err(anyhow!(
            "DB_URL is not set. It is the whole connection string, e.g. \
             postgresql://user:password@host:5432/database?sslmode=require — \
             which is what your provider gives you."
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn from_url_needs_nothing_from_the_environment() {
        let url = "postgresql://user:pw@example.invalid:5432/thing?sslmode=require";
        let config = DbConfig::from_url(url);

        assert_eq!(config.postgres_connection_string(), url);
        // No profile, because no profile selected it: the URL is the answer.
        assert_eq!(config.profile_name(), None);
    }

    #[test]
    fn from_url_accepts_anything_that_becomes_a_string() {
        assert_eq!(
            DbConfig::from_url(String::from("postgres://a/b")).postgres_connection_string(),
            "postgres://a/b"
        );
    }

    /// The profile convention, tested where it is defined rather than through a
    /// binary: `--profile staging` and `TANGO_PROFILE=staging` must resolve to
    /// the same key, and a profile name is not an arbitrary string.
    #[test]
    fn a_profile_name_is_a_variable_name() {
        assert_eq!(profile_key("staging"), "DB_URL_STAGING");
        assert_eq!(profile_key("my-test"), "DB_URL_MY_TEST");
        assert_eq!(profile_key("Dev"), "DB_URL_DEV");
    }
}