From 57170b01b42531000686f1b6e96736b300ca8d4c Mon Sep 17 00:00:00 2001 From: Miguel Palhas Date: Sat, 22 Aug 2026 19:30:59 +0100 Subject: [PATCH] feat: bootstrap config loading from env and file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Env overrides an optional TOML file, which overrides sensible defaults. Secrets (API keys) are read from the environment only — the file schema has no fields for them. Closes #3 --- Cargo.lock | 282 +++++++++++++++++++++++++++++ Cargo.toml | 1 + crates/arr-daemon/Cargo.toml | 6 + crates/arr-daemon/src/config.rs | 310 ++++++++++++++++++++++++++++++++ crates/arr-daemon/src/main.rs | 17 +- 5 files changed, 614 insertions(+), 2 deletions(-) create mode 100644 crates/arr-daemon/src/config.rs diff --git a/Cargo.lock b/Cargo.lock index 5452d24..ce7b4a7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,12 @@ version = "0.1.0" [[package]] name = "arr-daemon" version = "0.1.0" +dependencies = [ + "serde", + "tempfile", + "thiserror", + "toml", +] [[package]] name = "arr-db" @@ -45,3 +51,279 @@ version = "0.1.0" [[package]] name = "arr-probe" version = "0.1.0" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] diff --git a/Cargo.toml b/Cargo.toml index 05e0b8c..a04b997 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -54,6 +54,7 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] } uuid = { version = "1", features = ["v4", "serde"] } # Test-only +tempfile = "3" wiremock = "0.6" [workspace.lints.rust] diff --git a/crates/arr-daemon/Cargo.toml b/crates/arr-daemon/Cargo.toml index 00161de..98665ed 100644 --- a/crates/arr-daemon/Cargo.toml +++ b/crates/arr-daemon/Cargo.toml @@ -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 diff --git a/crates/arr-daemon/src/config.rs b/crates/arr-daemon/src/config.rs new file mode 100644 index 0000000..afceee6 --- /dev/null +++ b/crates/arr-daemon/src/config.rs @@ -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, + #[serde(default)] + database_path: Option, + #[serde(default)] + media_root: Option, + #[serde(default)] + prowlarr_url: Option, + #[serde(default)] + transmission_url: Option, + #[serde(default)] + jellyfin_url: Option, + #[serde(default)] + ntfy_url: Option, +} + +impl ConfigFile { + fn load(path: &Path) -> Result { + 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, + pub bind_addr: Option, + pub database_path: Option, + pub media_root: Option, + pub prowlarr_url: Option, + pub prowlarr_api_key: Option, + pub transmission_url: Option, + pub tmdb_api_key: Option, + pub jellyfin_url: Option, + pub jellyfin_api_key: Option, + pub ntfy_url: Option, +} + +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, + pub transmission_url: String, + pub tmdb_api_key: Option, + pub jellyfin_url: String, + pub jellyfin_api_key: Option, + 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::resolve(EnvOverrides::from_env()) + } + + fn resolve(env: EnvOverrides) -> Result { + 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 { + 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:?}"), + } + } +} diff --git a/crates/arr-daemon/src/main.rs b/crates/arr-daemon/src/main.rs index f9ef7f5..c7b5fdf 100644 --- a/crates/arr-daemon/src/main.rs +++ b/crates/arr-daemon/src/main.rs @@ -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 + } + } } -- 2.47.3