Files
arr/crates/arr-daemon/src/main.rs
T
Miguel Palhas 23f06d429f
ci / web (pull_request) Successful in 41s
ci / rust (pull_request) Successful in 2m21s
e2e / e2e (pull_request) Successful in 2m22s
feat(daemon): grab pipeline for wanted movies
Closes the "wanted movie, no file" gap: search every indexer, cache each
candidate with its verdict and score, send the best eligible one to
Transmission with its label and both seeding limits, and record the Grab.

Restarting mid-flight cannot double-grab. A title with a live grab is not
a gap, selection is a total order over the candidate set, and the add is
keyed on the infohash, so a crash between the add and the insert heals on
the next tick instead of leaving a second torrent.

The policy row to arr-core mapping moves into arr-db, where both the
manual-search API and the daemon read it, instead of being copied.
2026-08-22 22:15:05 +01:00

198 lines
6.0 KiB
Rust

//! arr — reconcile loop and process entry point. See DESIGN.md §8.
mod config;
mod grab;
pub mod reconcile;
mod web;
use std::process::ExitCode;
use std::sync::Arc;
use arr_api::{AppState, Upstreams};
use arr_compat::CompatState;
use arr_db::Db;
use arr_meta::TmdbClient;
use config::Config;
use grab::{GrabAction, SeedingLimits};
use reconcile::{ReconcileLoop, Tick};
use tower_http::trace::TraceLayer;
/// Dump the `OpenAPI` document and exit, instead of serving. `just gen-client`
/// uses this so the TypeScript client can be regenerated without a port or a
/// single upstream being up.
const OPENAPI_FLAG: &str = "--openapi";
#[tokio::main]
async fn main() -> ExitCode {
if std::env::args().nth(1).as_deref() == Some(OPENAPI_FLAG) {
return dump_openapi();
}
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "info,tower_http=debug".into()),
)
.init();
match run().await {
Ok(()) => ExitCode::SUCCESS,
Err(err) => {
tracing::error!("{err}");
ExitCode::FAILURE
}
}
}
fn dump_openapi() -> ExitCode {
match arr_api::openapi().to_pretty_json() {
Ok(json) => {
println!("{json}");
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("arr: openapi: {err}");
ExitCode::FAILURE
}
}
}
#[derive(Debug, thiserror::Error)]
enum Error {
#[error("config: {0}")]
Config(#[from] config::ConfigError),
#[error("http client: {0}")]
HttpClient(#[from] reqwest::Error),
#[error("database: {0}")]
Database(#[from] sqlx::Error),
#[error("database migration: {0}")]
Migration(#[from] sqlx::migrate::MigrateError),
#[error("tmdb client: {0}")]
Tmdb(#[from] arr_meta::Error),
#[error("prowlarr client: {0}")]
Prowlarr(#[from] arr_indexer::Error),
#[error("transmission client: {0}")]
Transmission(#[from] arr_dl::Error),
#[error("bind {addr}: {source}")]
Bind {
addr: std::net::SocketAddr,
source: std::io::Error,
},
#[error("serve: {0}")]
Serve(std::io::Error),
#[error("reconcile task: {0}")]
ReconcileTask(#[from] tokio::task::JoinError),
}
async fn run() -> Result<(), Error> {
let config = Config::load()?;
let database = Db::connect(&config.database_path).await?;
database.migrate().await?;
let mut reconcile = ReconcileLoop::new(database.clone());
// Without a Prowlarr key nothing can be searched, so the grab lane stays
// unregistered rather than failing a tick every 30 seconds.
if let Some(key) = config.prowlarr_api_key.clone() {
let prowlarr = arr_indexer::ProwlarrClient::new(config.prowlarr_url.clone(), key)?;
let transmission = arr_dl::TransmissionClient::new(&config.transmission_url)?;
reconcile = reconcile.register(
Tick::Reconcile,
GrabAction::new(
prowlarr,
transmission,
config.download_dir.clone(),
SeedingLimits {
ratio: config.seed_ratio_limit,
idle_minutes: config.seed_idle_limit_minutes,
},
),
);
} else {
tracing::warn!("no Prowlarr API key: nothing will be grabbed");
}
// Jellyseerr's Radarr shim (DESIGN.md §9.4) reads the same database and
// needs its own TMDB client for `movie/lookup`.
let mut compat = CompatState::new(database.clone());
if let Some(key) = &config.tmdb_api_key {
let mut tmdb = TmdbClient::builder(key.clone());
if let Some(tmdb_url) = &config.tmdb_url {
tmdb = tmdb.base_url(tmdb_url.clone());
}
compat = compat.with_tmdb(Arc::new(tmdb.build()?));
}
let mut upstreams = Upstreams::new(config.prowlarr_url, config.transmission_url)
.with_prowlarr_api_key(config.prowlarr_api_key)
.with_tmdb_api_key(config.tmdb_api_key);
if let Some(tmdb_url) = config.tmdb_url {
upstreams = upstreams.with_tmdb_url(tmdb_url);
}
let state = AppState::new(upstreams)?.with_database(database);
let app = arr_api::router(state)
.merge(arr_compat::router(compat))
.fallback(web::serve)
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind(config.bind_addr)
.await
.map_err(|source| Error::Bind {
addr: config.bind_addr,
source,
})?;
tracing::info!(addr = %config.bind_addr, docs = arr_api::DOCS_PATH, "listening");
let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);
let mut reconcile_task = tokio::spawn(reconcile.run(shutdown_rx));
let signal_tx = shutdown_tx.clone();
let server = async move {
axum::serve(listener, app)
.with_graceful_shutdown(async move {
shutdown().await;
let _ = signal_tx.send(true);
})
.await
};
tokio::pin!(server);
tokio::select! {
result = &mut server => {
let _ = shutdown_tx.send(true);
reconcile_task.await?;
result.map_err(Error::Serve)
}
result = &mut reconcile_task => {
result?;
server.await.map_err(Error::Serve)
}
}
}
/// Stop accepting on Ctrl-C, or on the SIGTERM a service manager sends.
async fn shutdown() {
let interrupt = async {
let _ = tokio::signal::ctrl_c().await;
};
#[cfg(unix)]
let terminate = async {
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
Ok(mut signal) => {
signal.recv().await;
}
Err(err) => tracing::warn!("no SIGTERM handler: {err}"),
}
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
() = interrupt => {},
() = terminate => {},
}
tracing::info!("shutting down");
}