Files
arr/crates/arr-daemon/src/config.rs
T
naps62-yolo 0585811a0c
ci / web (push) Successful in 43s
e2e / e2e (push) Successful in 54s
ci / rust (push) Failing after 2m0s
Per-tracker seeding rules and torrent reaper (#88)
2026-08-23 00:03:30 +01:00

485 lines
18 KiB
Rust

//! 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::collections::HashMap;
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_DOWNLOAD_DIR: &str = "ARR_DOWNLOAD_DIR";
pub const ENV_SEED_RATIO_LIMIT: &str = "ARR_SEED_RATIO_LIMIT";
pub const ENV_SEED_IDLE_LIMIT_MINUTES: &str = "ARR_SEED_IDLE_LIMIT_MINUTES";
pub const ENV_TMDB_API_KEY: &str = "ARR_TMDB_API_KEY";
pub const ENV_TMDB_URL: &str = "ARR_TMDB_URL";
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";
/// Transmission's own view of the download directory (DESIGN.md §3). It
/// shares the media dataset with the library so hardlinks work (§7.2).
pub const DEFAULT_DOWNLOAD_DIR: &str = "/mnt/media/transmission/complete";
/// Seeding obligation defaults (§7.3), applied to every torrent at add time
/// and enforced by Transmission. Per-tracker rules are issue #25.
pub const DEFAULT_SEED_RATIO_LIMIT: f64 = 1.0;
pub const DEFAULT_SEED_IDLE_LIMIT_MINUTES: u64 = 4320;
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,
},
#[error("invalid {env} ({input:?}): expected a number")]
InvalidNumber { env: &'static str, input: String },
#[error("invalid tracker_seeding key {0:?}: expected a Prowlarr indexer ID")]
InvalidTrackerId(String),
}
/// 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)]
download_dir: Option<PathBuf>,
#[serde(default)]
seed_ratio_limit: Option<f64>,
#[serde(default)]
seed_idle_limit_minutes: Option<u64>,
#[serde(default)]
tracker_seeding: HashMap<String, TrackerSeedingRule>,
#[serde(default)]
jellyfin_url: Option<String>,
#[serde(default)]
ntfy_url: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TrackerSeedingRule {
pub ratio: f64,
pub min_seed_time: u64,
}
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 download_dir: Option<String>,
pub seed_ratio_limit: Option<String>,
pub seed_idle_limit_minutes: Option<String>,
pub tmdb_api_key: Option<String>,
pub tmdb_url: 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(),
download_dir: std::env::var(ENV_DOWNLOAD_DIR).ok(),
seed_ratio_limit: std::env::var(ENV_SEED_RATIO_LIMIT).ok(),
seed_idle_limit_minutes: std::env::var(ENV_SEED_IDLE_LIMIT_MINUTES).ok(),
tmdb_api_key: std::env::var(ENV_TMDB_API_KEY).ok(),
tmdb_url: std::env::var(ENV_TMDB_URL).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)]
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,
/// Where Transmission puts completed downloads, in Transmission's own
/// namespace (§7.1).
pub download_dir: PathBuf,
pub seed_ratio_limit: f64,
pub seed_idle_limit_minutes: u64,
pub tracker_seeding: HashMap<i64, TrackerSeedingRule>,
pub tmdb_api_key: Option<String>,
/// E2E seam only, env-only. `None` means the client's built-in TMDB
/// address; DESIGN.md §10 keeps the real URL out of configuration.
pub tmdb_url: 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")),
};
let tracker_seeding = file
.tracker_seeding
.iter()
.map(|(id, &rule)| {
id.parse::<i64>()
.map(|id| (id, rule))
.map_err(|_| ConfigError::InvalidTrackerId(id.clone()))
})
.collect::<Result<HashMap<_, _>, _>>()?;
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()),
download_dir: env
.download_dir
.map(PathBuf::from)
.or(file.download_dir)
.unwrap_or_else(|| PathBuf::from(DEFAULT_DOWNLOAD_DIR)),
seed_ratio_limit: match &env.seed_ratio_limit {
Some(raw) => parse_number(raw, ENV_SEED_RATIO_LIMIT)?,
None => file.seed_ratio_limit.unwrap_or(DEFAULT_SEED_RATIO_LIMIT),
},
seed_idle_limit_minutes: match &env.seed_idle_limit_minutes {
Some(raw) => parse_number(raw, ENV_SEED_IDLE_LIMIT_MINUTES)?,
None => file
.seed_idle_limit_minutes
.unwrap_or(DEFAULT_SEED_IDLE_LIMIT_MINUTES),
},
tracker_seeding,
tmdb_api_key: env.tmdb_api_key,
tmdb_url: env.tmdb_url,
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_number<T: std::str::FromStr>(raw: &str, env: &'static str) -> Result<T, ConfigError> {
raw.parse().map_err(|_| ConfigError::InvalidNumber {
env,
input: raw.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.download_dir, PathBuf::from(DEFAULT_DOWNLOAD_DIR));
assert!((config.seed_ratio_limit - DEFAULT_SEED_RATIO_LIMIT).abs() < f64::EPSILON);
assert_eq!(
config.seed_idle_limit_minutes,
DEFAULT_SEED_IDLE_LIMIT_MINUTES
);
assert_eq!(config.jellyfin_url, DEFAULT_JELLYFIN_URL);
assert!(config.tracker_seeding.is_empty());
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 tmdb_url_is_an_env_only_seam() {
let config = Config::resolve(EnvOverrides::default()).unwrap();
assert_eq!(config.tmdb_url, None);
let env = EnvOverrides {
tmdb_url: Some("http://127.0.0.1:9/3".into()),
..EnvOverrides::default()
};
let config = Config::resolve(env).unwrap();
assert_eq!(config.tmdb_url.as_deref(), Some("http://127.0.0.1:9/3"));
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("arr.toml");
std::fs::write(&path, "tmdb_url = \"http://127.0.0.1:9/3\"\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 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(_))
));
}
/// §7.3: both seeding limits are set at add time, so both have to be
/// configurable without a rebuild.
#[test]
fn seeding_limits_come_from_file_or_env() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("arr.toml");
std::fs::write(
&path,
"seed_ratio_limit = 2.5\nseed_idle_limit_minutes = 120\n",
)
.unwrap();
let env = EnvOverrides {
config_file: Some(path.to_string_lossy().into_owned()),
..EnvOverrides::default()
};
let config = Config::resolve(env.clone()).unwrap();
assert!((config.seed_ratio_limit - 2.5).abs() < f64::EPSILON);
assert_eq!(config.seed_idle_limit_minutes, 120);
let config = Config::resolve(EnvOverrides {
seed_ratio_limit: Some("0.5".into()),
..env.clone()
})
.unwrap();
assert!((config.seed_ratio_limit - 0.5).abs() < f64::EPSILON);
let error = Config::resolve(EnvOverrides {
seed_idle_limit_minutes: Some("soon".into()),
..env
})
.unwrap_err();
assert!(matches!(
error,
ConfigError::InvalidNumber { env, .. } if env == ENV_SEED_IDLE_LIMIT_MINUTES
));
}
#[test]
fn tracker_seeding_rules_are_keyed_by_prowlarr_id() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("arr.toml");
std::fs::write(
&path,
"[tracker_seeding.3]\nratio = 2.5\nmin_seed_time = 120\n",
)
.unwrap();
let config = Config::resolve(EnvOverrides {
config_file: Some(path.to_string_lossy().into_owned()),
..EnvOverrides::default()
})
.unwrap();
assert_eq!(
config.tracker_seeding.get(&3),
Some(&TrackerSeedingRule {
ratio: 2.5,
min_seed_time: 120
})
);
}
#[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:?}"),
}
}
}