tango_core/config.rs
1//! Environment and database selection, shared by every crate.
2//!
3//! This is the half of configuration that the harvester, the API and a
4//! downstream project all need: find the `.env`, and turn a profile name into a
5//! connection string. The harvester-specific settings - where yt-dlp lives and
6//! whether a YouTube Data API key is configured - live in
7//! `tango-harvest::config`, so a crate that only reads the database never has to
8//! know they exist.
9
10use anyhow::{Result, anyhow};
11use std::path::PathBuf;
12
13/// A resolved database connection, and the profile it came from.
14///
15/// The profile is carried only for logging: the finished URL is the only thing
16/// a caller needs.
17pub struct DbConfig {
18 db_url: String,
19 profile: Option<String>,
20}
21
22impl DbConfig {
23 /// `profile` selects a database by name; see [`resolve_db_url`].
24 pub fn load(profile: Option<&str>) -> Result<Self> {
25 load_env();
26
27 let (db_url, profile) = resolve_db_url(profile)?;
28 Ok(Self { db_url, profile })
29 }
30
31 /// Loads the profile from an environment variable, then resolves it.
32 ///
33 /// The CLI takes a `--profile` argument; a server has no command line worth
34 /// parsing for this, so `tango-api` reads `TANGO_PROFILE` through here. One
35 /// resolver, two front doors.
36 pub fn from_env_var(profile_var: &str) -> Result<Self> {
37 let profile = profile_from_env(profile_var);
38 Self::load(profile.as_deref())
39 }
40
41 /// A connection string supplied by the caller, not by the environment.
42 ///
43 /// The two front doors above assume what this project's own binaries have:
44 /// a `.env`, or environment variables, and nothing else. A downstream
45 /// project that stitches tango into a larger server usually does not work
46 /// that way - its configuration comes from its own file, its flags, or a
47 /// secret manager - and the only ways to reuse a URL through the other
48 /// constructors would be to write it into the process environment first
49 /// (`unsafe { std::env::set_var(...) }` since edition 2024) or to re-derive
50 /// the connection options by hand. This is the way in.
51 ///
52 /// Nothing is read here: no `.env` is loaded and no variable is consulted,
53 /// so a caller that uses this cannot accidentally end up on a database it
54 /// did not name. `profile_name` is `None`, because there is no profile - the
55 /// URL is the whole answer.
56 pub fn from_url(url: impl Into<String>) -> Self {
57 Self {
58 db_url: url.into(),
59 profile: None,
60 }
61 }
62
63 pub fn postgres_connection_string(&self) -> &str {
64 &self.db_url
65 }
66
67 /// The profile in use, for a startup line. None is the default database.
68 pub fn profile_name(&self) -> Option<&str> {
69 self.profile.as_deref()
70 }
71}
72
73/// The first `.env` at or above the working directory, if there is one.
74///
75/// Public because `bootstrap` needs to know whether the file exists before it
76/// decides to write one, and walking up twice would be two definitions of where
77/// configuration lives.
78pub fn env_file() -> Option<PathBuf> {
79 let mut dir = std::env::current_dir().ok()?;
80 loop {
81 let path = dir.join(".env");
82 if path.is_file() {
83 return Some(path);
84 }
85 dir = dir.parent()?.to_path_buf();
86 }
87}
88
89/// Loads the first `.env` found walking up from the working directory.
90///
91/// `dotenvy::dotenv()` reads only the current directory. That is enough when a
92/// binary runs from the project root, which is the documented way to run it,
93/// but not from a subdirectory - and `tango-api/` lives in one and shares this
94/// file. So every binary walks up, and one `.env` configures all of them.
95///
96/// Returns the file that was loaded, so a caller that wants to log it can.
97/// Nothing found is not an error: every setting can also come from the real
98/// environment, and the error that follows is about a missing `DB_URL`, which is
99/// more useful than "no .env here".
100pub fn load_env() -> Option<PathBuf> {
101 let path = env_file();
102
103 match &path {
104 Some(path) => {
105 let _ = dotenvy::from_path(path);
106 }
107 None => {
108 let _ = dotenvy::dotenv();
109 }
110 }
111
112 path
113}
114
115/// The profile named by an environment variable, trimmed and empty-as-none.
116///
117/// Kept here rather than in the API so `TANGO_PROFILE` and the CLI's
118/// `--profile` cannot disagree about what an empty value means.
119pub fn profile_from_env(var: &str) -> Option<String> {
120 std::env::var(var)
121 .ok()
122 .map(|value| value.trim().to_string())
123 .filter(|value| !value.is_empty())
124}
125
126/// The environment key a profile reads: `staging` means `DB_URL_STAGING`.
127///
128/// A name rather than a config file. Uppercased and stripped of dashes so a
129/// profile with a hyphen in it - `my-test`, the kind a branch name produces -
130/// is still a valid shell variable, and the CLI and the API cannot drift into
131/// deriving two different keys from the same word.
132fn profile_key(name: &str) -> String {
133 format!("DB_URL_{}", name.to_uppercase().replace('-', "_"))
134}
135
136/// Resolves the connection string, and which profile it came from.
137///
138/// `DB_URL`, and nothing else. A profile is a name for a database resolved by
139/// convention rather than a config file: `--profile staging` reads
140/// `DB_URL_STAGING`, uppercased.
141///
142/// A convention rather than a `tango-rs.yaml` on purpose. The only thing that
143/// differs between environments is the connection string, so a config file
144/// would hold a list of environment-variable names - which is what this is,
145/// without a file to keep in sync. If profiles ever need more than a URL (a
146/// table prefix, say), that is when a file starts earning its place.
147///
148/// Deliberately *not* a push mechanism. A profile here chooses which database a
149/// command talks to; it does not copy anything between them. To put data in a
150/// second environment, harvest once and point the same code at it - or use
151/// `pg_dump`, which is the right tool and needs nothing from this project.
152///
153/// The individual `DB_USERNAME` / `DB_PASSWORD` / `DB_HOST` / `DB_NAME` /
154/// `DB_PORT` / `DB_SSLMODE` settings are gone. They assembled a URL out of parts
155/// that a managed provider - which is what most people here are using - cannot
156/// be configured with, because it needs `?sslmode=require` on the end and there
157/// was nowhere to put it except the URL itself. Two ways to say the same thing
158/// meant two things to document, and a URL is what every provider hands you.
159fn resolve_db_url(profile: Option<&str>) -> Result<(String, Option<String>)> {
160 if let Some(name) = profile {
161 let key = profile_key(name);
162 return match std::env::var(&key) {
163 Ok(url) if !url.trim().is_empty() => Ok((url, Some(name.to_string()))),
164 _ => Err(anyhow!(
165 "profile {name:?} needs {key} in the environment. \
166 A profile is a name for a database: set {key} to its connection string, \
167 or drop --profile to use DB_URL."
168 )),
169 };
170 }
171
172 match std::env::var("DB_URL") {
173 Ok(url) if !url.trim().is_empty() => Ok((url, None)),
174 // Named as one setting, because that is what is missing. Listing the
175 // five that used to work would be telling someone to set things that no
176 // longer do anything.
177 _ => Err(anyhow!(
178 "DB_URL is not set. It is the whole connection string, e.g. \
179 postgresql://user:password@host:5432/database?sslmode=require — \
180 which is what your provider gives you."
181 )),
182 }
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188
189 #[test]
190 fn from_url_needs_nothing_from_the_environment() {
191 let url = "postgresql://user:pw@example.invalid:5432/thing?sslmode=require";
192 let config = DbConfig::from_url(url);
193
194 assert_eq!(config.postgres_connection_string(), url);
195 // No profile, because no profile selected it: the URL is the answer.
196 assert_eq!(config.profile_name(), None);
197 }
198
199 #[test]
200 fn from_url_accepts_anything_that_becomes_a_string() {
201 assert_eq!(
202 DbConfig::from_url(String::from("postgres://a/b")).postgres_connection_string(),
203 "postgres://a/b"
204 );
205 }
206
207 /// The profile convention, tested where it is defined rather than through a
208 /// binary: `--profile staging` and `TANGO_PROFILE=staging` must resolve to
209 /// the same key, and a profile name is not an arbitrary string.
210 #[test]
211 fn a_profile_name_is_a_variable_name() {
212 assert_eq!(profile_key("staging"), "DB_URL_STAGING");
213 assert_eq!(profile_key("my-test"), "DB_URL_MY_TEST");
214 assert_eq!(profile_key("Dev"), "DB_URL_DEV");
215 }
216}