Bootstrap configuration loading (#46)
ci / web (push) Successful in 14s
ci / rust (push) Successful in 39s
e2e / e2e (push) Successful in 1m15s

This commit was merged in pull request #46.
This commit is contained in:
2026-08-22 19:44:50 +01:00
parent 7b57c387fb
commit 1529e9fdca
4 changed files with 396 additions and 2 deletions
+6
View File
@@ -11,6 +11,12 @@ name = "arr"
path = "src/main.rs"
[dependencies]
serde.workspace = true
thiserror.workspace = true
toml.workspace = true
[dev-dependencies]
tempfile.workspace = true
[lints]
workspace = true
+310
View File
@@ -0,0 +1,310 @@
//! Bootstrap configuration. See DESIGN.md §10: only these settings come from
//! config/env; everything else lives in the database.
//!
//! Precedence per field: env > file > default. Every non-secret field has a
//! default, and the config file itself is optional, so an empty environment
//! and no file both resolve to a usable config. Secrets (API keys) are read
//! only from the environment: [`ConfigFile`] has no fields for them, and
//! `deny_unknown_fields` turns an accidental key in the file into a parse
//! error instead of silently ignoring it.
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use serde::Deserialize;
pub const ENV_CONFIG_FILE: &str = "ARR_CONFIG_FILE";
pub const ENV_BIND_ADDR: &str = "ARR_BIND_ADDR";
pub const ENV_DATABASE_PATH: &str = "ARR_DATABASE_PATH";
pub const ENV_MEDIA_ROOT: &str = "ARR_MEDIA_ROOT";
pub const ENV_PROWLARR_URL: &str = "ARR_PROWLARR_URL";
pub const ENV_PROWLARR_API_KEY: &str = "ARR_PROWLARR_API_KEY";
pub const ENV_TRANSMISSION_URL: &str = "ARR_TRANSMISSION_URL";
pub const ENV_TMDB_API_KEY: &str = "ARR_TMDB_API_KEY";
pub const ENV_JELLYFIN_URL: &str = "ARR_JELLYFIN_URL";
pub const ENV_JELLYFIN_API_KEY: &str = "ARR_JELLYFIN_API_KEY";
pub const ENV_NTFY_URL: &str = "ARR_NTFY_URL";
pub const DEFAULT_BIND_ADDR: &str = "0.0.0.0:7878";
pub const DEFAULT_DATABASE_PATH: &str = "arr.db";
pub const DEFAULT_MEDIA_ROOT: &str = "/mnt/media";
pub const DEFAULT_PROWLARR_URL: &str = "http://localhost:9696";
pub const DEFAULT_TRANSMISSION_URL: &str = "http://localhost:9091/transmission/rpc";
pub const DEFAULT_JELLYFIN_URL: &str = "http://localhost:8096";
pub const DEFAULT_NTFY_URL: &str = "http://localhost";
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
#[error("io: {0}")]
Io(#[from] std::io::Error),
#[error("toml decode: {0}")]
TomlDecode(#[from] toml::de::Error),
#[error("invalid {env} ({input:?}): {source}")]
InvalidBindAddr {
env: &'static str,
input: String,
source: std::net::AddrParseError,
},
}
/// On-disk representation. Non-secret fields only — see the module docs.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
struct ConfigFile {
#[serde(default)]
bind_addr: Option<SocketAddr>,
#[serde(default)]
database_path: Option<PathBuf>,
#[serde(default)]
media_root: Option<PathBuf>,
#[serde(default)]
prowlarr_url: Option<String>,
#[serde(default)]
transmission_url: Option<String>,
#[serde(default)]
jellyfin_url: Option<String>,
#[serde(default)]
ntfy_url: Option<String>,
}
impl ConfigFile {
fn load(path: &Path) -> Result<Self, ConfigError> {
if !path.exists() {
return Ok(Self::default());
}
let raw = std::fs::read_to_string(path)?;
Ok(toml::from_str(&raw)?)
}
}
/// Raw env var readout, so tests can inject values without mutating the
/// process environment (which races other tests in the same binary).
#[derive(Debug, Clone, Default)]
pub struct EnvOverrides {
pub config_file: Option<String>,
pub bind_addr: Option<String>,
pub database_path: Option<String>,
pub media_root: Option<String>,
pub prowlarr_url: Option<String>,
pub prowlarr_api_key: Option<String>,
pub transmission_url: Option<String>,
pub tmdb_api_key: Option<String>,
pub jellyfin_url: Option<String>,
pub jellyfin_api_key: Option<String>,
pub ntfy_url: Option<String>,
}
impl EnvOverrides {
pub fn from_env() -> Self {
Self {
config_file: std::env::var(ENV_CONFIG_FILE).ok(),
bind_addr: std::env::var(ENV_BIND_ADDR).ok(),
database_path: std::env::var(ENV_DATABASE_PATH).ok(),
media_root: std::env::var(ENV_MEDIA_ROOT).ok(),
prowlarr_url: std::env::var(ENV_PROWLARR_URL).ok(),
prowlarr_api_key: std::env::var(ENV_PROWLARR_API_KEY).ok(),
transmission_url: std::env::var(ENV_TRANSMISSION_URL).ok(),
tmdb_api_key: std::env::var(ENV_TMDB_API_KEY).ok(),
jellyfin_url: std::env::var(ENV_JELLYFIN_URL).ok(),
jellyfin_api_key: std::env::var(ENV_JELLYFIN_API_KEY).ok(),
ntfy_url: std::env::var(ENV_NTFY_URL).ok(),
}
}
}
/// Resolved bootstrap configuration. See DESIGN.md §10.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
pub bind_addr: SocketAddr,
pub database_path: PathBuf,
pub media_root: PathBuf,
pub prowlarr_url: String,
pub prowlarr_api_key: Option<String>,
pub transmission_url: String,
pub tmdb_api_key: Option<String>,
pub jellyfin_url: String,
pub jellyfin_api_key: Option<String>,
pub ntfy_url: String,
}
impl Config {
/// Load from the process environment, and an optional TOML file named by
/// `$ARR_CONFIG_FILE`. No file is not an error — every non-secret field
/// has a default.
pub fn load() -> Result<Self, ConfigError> {
Self::resolve(EnvOverrides::from_env())
}
fn resolve(env: EnvOverrides) -> Result<Self, ConfigError> {
let file = match &env.config_file {
Some(path) => ConfigFile::load(Path::new(path))?,
None => ConfigFile::default(),
};
let bind_addr = match &env.bind_addr {
Some(raw) => parse_bind_addr(raw, ENV_BIND_ADDR)?,
None => file
.bind_addr
.unwrap_or_else(|| DEFAULT_BIND_ADDR.parse().expect("valid default bind_addr")),
};
Ok(Self {
bind_addr,
database_path: env
.database_path
.map(PathBuf::from)
.or(file.database_path)
.unwrap_or_else(|| PathBuf::from(DEFAULT_DATABASE_PATH)),
media_root: env
.media_root
.map(PathBuf::from)
.or(file.media_root)
.unwrap_or_else(|| PathBuf::from(DEFAULT_MEDIA_ROOT)),
prowlarr_url: env
.prowlarr_url
.or(file.prowlarr_url)
.unwrap_or_else(|| DEFAULT_PROWLARR_URL.to_string()),
prowlarr_api_key: env.prowlarr_api_key,
transmission_url: env
.transmission_url
.or(file.transmission_url)
.unwrap_or_else(|| DEFAULT_TRANSMISSION_URL.to_string()),
tmdb_api_key: env.tmdb_api_key,
jellyfin_url: env
.jellyfin_url
.or(file.jellyfin_url)
.unwrap_or_else(|| DEFAULT_JELLYFIN_URL.to_string()),
jellyfin_api_key: env.jellyfin_api_key,
ntfy_url: env
.ntfy_url
.or(file.ntfy_url)
.unwrap_or_else(|| DEFAULT_NTFY_URL.to_string()),
})
}
}
fn parse_bind_addr(raw: &str, env: &'static str) -> Result<SocketAddr, ConfigError> {
raw.parse().map_err(|source| ConfigError::InvalidBindAddr {
env,
input: raw.to_string(),
source,
})
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn empty_environment_resolves_to_defaults() {
let config = Config::resolve(EnvOverrides::default()).unwrap();
assert_eq!(config.bind_addr, DEFAULT_BIND_ADDR.parse().unwrap());
assert_eq!(config.database_path, PathBuf::from(DEFAULT_DATABASE_PATH));
assert_eq!(config.media_root, PathBuf::from(DEFAULT_MEDIA_ROOT));
assert_eq!(config.prowlarr_url, DEFAULT_PROWLARR_URL);
assert_eq!(config.transmission_url, DEFAULT_TRANSMISSION_URL);
assert_eq!(config.jellyfin_url, DEFAULT_JELLYFIN_URL);
assert_eq!(config.ntfy_url, DEFAULT_NTFY_URL);
assert_eq!(config.prowlarr_api_key, None);
assert_eq!(config.tmdb_api_key, None);
assert_eq!(config.jellyfin_api_key, None);
}
#[test]
fn missing_config_file_is_not_an_error() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("does-not-exist.toml");
let env = EnvOverrides {
config_file: Some(path.to_string_lossy().into_owned()),
..EnvOverrides::default()
};
let config = Config::resolve(env).unwrap();
assert_eq!(config.bind_addr, DEFAULT_BIND_ADDR.parse().unwrap());
assert!(!path.exists(), "resolve must not create the file");
}
#[test]
fn config_file_overrides_defaults() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("arr.toml");
std::fs::write(
&path,
r#"
bind_addr = "127.0.0.1:1"
media_root = "/tank/media"
prowlarr_url = "http://prowlarr.internal:9696"
"#,
)
.unwrap();
let env = EnvOverrides {
config_file: Some(path.to_string_lossy().into_owned()),
..EnvOverrides::default()
};
let config = Config::resolve(env).unwrap();
assert_eq!(config.bind_addr, "127.0.0.1:1".parse().unwrap());
assert_eq!(config.media_root, PathBuf::from("/tank/media"));
assert_eq!(config.prowlarr_url, "http://prowlarr.internal:9696");
// Untouched fields still default.
assert_eq!(config.transmission_url, DEFAULT_TRANSMISSION_URL);
}
#[test]
fn env_overrides_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("arr.toml");
std::fs::write(&path, "bind_addr = \"127.0.0.1:1\"\n").unwrap();
let env = EnvOverrides {
config_file: Some(path.to_string_lossy().into_owned()),
bind_addr: Some("0.0.0.0:9999".into()),
..EnvOverrides::default()
};
let config = Config::resolve(env).unwrap();
assert_eq!(config.bind_addr, "0.0.0.0:9999".parse().unwrap());
}
#[test]
fn secrets_come_only_from_env() {
let env = EnvOverrides {
prowlarr_api_key: Some("secret-1".into()),
tmdb_api_key: Some("secret-2".into()),
jellyfin_api_key: Some("secret-3".into()),
..EnvOverrides::default()
};
let config = Config::resolve(env).unwrap();
assert_eq!(config.prowlarr_api_key.as_deref(), Some("secret-1"));
assert_eq!(config.tmdb_api_key.as_deref(), Some("secret-2"));
assert_eq!(config.jellyfin_api_key.as_deref(), Some("secret-3"));
}
#[test]
fn a_secret_in_the_config_file_is_a_parse_error() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("arr.toml");
std::fs::write(&path, "prowlarr_api_key = \"leaked\"\n").unwrap();
let env = EnvOverrides {
config_file: Some(path.to_string_lossy().into_owned()),
..EnvOverrides::default()
};
assert!(matches!(
Config::resolve(env),
Err(ConfigError::TomlDecode(_))
));
}
#[test]
fn invalid_env_bind_addr_returns_diagnostic() {
let env = EnvOverrides {
bind_addr: Some("not-an-addr".into()),
..EnvOverrides::default()
};
let err = Config::resolve(env).unwrap_err();
match err {
ConfigError::InvalidBindAddr { env, input, .. } => {
assert_eq!(env, ENV_BIND_ADDR);
assert_eq!(input, "not-an-addr");
}
other => panic!("expected InvalidBindAddr, got {other:?}"),
}
}
}
+15 -2
View File
@@ -1,5 +1,18 @@
//! arr — reconcile loop and process entry point. See DESIGN.md §8.
fn main() {
println!("arr");
mod config;
use std::process::ExitCode;
fn main() -> ExitCode {
match config::Config::load() {
Ok(config) => {
println!("arr starting, bind_addr={}", config.bind_addr);
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("arr: {err}");
ExitCode::FAILURE
}
}
}