Stable 1.99 added the lint and CI denies warnings, which failed the build and skipped the deploy. Each flagged assert now uses the assert_eq! form clippy suggests. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
181 lines
6.1 KiB
Rust
181 lines
6.1 KiB
Rust
//! Removes arr torrents only after qBittorrent says their seeding obligation
|
|
//! is complete. The library/import state is deliberately not consulted (§7.3).
|
|
|
|
use std::collections::HashSet;
|
|
|
|
use arr_db::Db;
|
|
use arr_dl::QbitClient;
|
|
|
|
use crate::grab::label_for_root;
|
|
use crate::reconcile::{Action, ActionFuture, Outcome};
|
|
|
|
#[derive(Debug)]
|
|
pub struct ReaperAction {
|
|
qbit: QbitClient,
|
|
}
|
|
|
|
impl ReaperAction {
|
|
#[must_use]
|
|
pub fn new(qbit: QbitClient) -> Self {
|
|
Self { qbit }
|
|
}
|
|
|
|
async fn tick(&self, labels: &HashSet<String>) -> Result<Vec<Outcome>, arr_dl::Error> {
|
|
let torrents = self.qbit.list_torrents().await?;
|
|
let mut outcomes = Vec::new();
|
|
for torrent in torrents {
|
|
if !torrent.is_finished || !torrent.labels.iter().any(|label| labels.contains(label)) {
|
|
continue;
|
|
}
|
|
self.qbit.remove_torrent(&torrent.hash, true).await?;
|
|
outcomes.push(Outcome::new(
|
|
format!("torrent {} finished seeding", torrent.hash),
|
|
format!("removed torrent {} and its download data", torrent.name),
|
|
));
|
|
}
|
|
Ok(outcomes)
|
|
}
|
|
}
|
|
|
|
impl Action for ReaperAction {
|
|
fn name(&self) -> &'static str {
|
|
"torrent-reaper"
|
|
}
|
|
|
|
fn run<'a>(&'a self, database: &'a Db) -> ActionFuture<'a> {
|
|
Box::pin(async move {
|
|
let labels = sqlx::query_as::<_, (String, String)>("SELECT kind, audience FROM roots")
|
|
.fetch_all(database.pool())
|
|
.await
|
|
.map_err(|error| Box::new(error) as crate::reconcile::ActionError)?
|
|
.into_iter()
|
|
.map(|(kind, audience)| label_for_root(&kind, &audience))
|
|
.collect::<HashSet<_>>();
|
|
self.tick(&labels)
|
|
.await
|
|
.map_err(|error| Box::new(error) as crate::reconcile::ActionError)
|
|
})
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[allow(clippy::unwrap_used)]
|
|
mod tests {
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
use serde_json::{json, Value};
|
|
use wiremock::matchers::{method, path};
|
|
use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};
|
|
|
|
use super::*;
|
|
|
|
/// Records what was asked to be deleted, so a test can assert the reaper
|
|
/// touched one torrent and not its neighbours.
|
|
#[derive(Clone)]
|
|
struct Deletions(Arc<Mutex<Vec<String>>>);
|
|
|
|
impl Respond for Deletions {
|
|
fn respond(&self, request: &Request) -> ResponseTemplate {
|
|
let body = String::from_utf8_lossy(&request.body).into_owned();
|
|
self.0.lock().unwrap().push(body);
|
|
ResponseTemplate::new(200).set_body_string("")
|
|
}
|
|
}
|
|
|
|
/// A torrent qBittorrent stopped on the ratio limit arr set on it, which
|
|
/// is what "finished seeding" means to the reaper.
|
|
fn torrent(id: i64, label: &str, finished: bool) -> Value {
|
|
json!({
|
|
"hash": format!("hash-{id}"), "name": format!("torrent-{id}"),
|
|
"state": if finished { "stoppedUP" } else { "uploading" },
|
|
"progress": 1.0, "save_path": "/downloads", "tags": label,
|
|
"ratio": 2.0, "ratio_limit": 1.5,
|
|
"seeding_time": 10, "seeding_time_limit": -1,
|
|
"inactive_seeding_time_limit": -1, "last_activity": 0
|
|
})
|
|
}
|
|
|
|
async fn qbit(server: &MockServer, torrents: Value) -> Arc<Mutex<Vec<String>>> {
|
|
let deleted = Arc::new(Mutex::new(Vec::new()));
|
|
Mock::given(method("GET"))
|
|
.and(path("/api/v2/torrents/info"))
|
|
.respond_with(ResponseTemplate::new(200).set_body_json(torrents))
|
|
.mount(server)
|
|
.await;
|
|
Mock::given(method("POST"))
|
|
.and(path("/api/v2/torrents/delete"))
|
|
.respond_with(Deletions(Arc::clone(&deleted)))
|
|
.mount(server)
|
|
.await;
|
|
deleted
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn removes_only_finished_arr_torrents_with_data() {
|
|
let server = MockServer::start().await;
|
|
let deleted = qbit(
|
|
&server,
|
|
json!([
|
|
torrent(1, "movies-main", false),
|
|
torrent(2, "movies-main", true),
|
|
torrent(3, "radarr", true)
|
|
]),
|
|
)
|
|
.await;
|
|
let action = ReaperAction::new(QbitClient::new(&server.uri()).unwrap());
|
|
|
|
let labels = HashSet::from(["movies-main".to_owned(), "movies-kids".to_owned()]);
|
|
let outcomes = action.tick(&labels).await.unwrap();
|
|
|
|
assert_eq!(outcomes.len(), 1);
|
|
let deleted = deleted.lock().unwrap();
|
|
assert_eq!(deleted.len(), 1);
|
|
assert!(
|
|
deleted[0].contains("hashes=hash-2"),
|
|
"asked: {}",
|
|
deleted[0]
|
|
);
|
|
assert!(
|
|
deleted[0].contains("deleteFiles=true"),
|
|
"asked: {}",
|
|
deleted[0]
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn finished_torrent_does_not_need_a_grab_or_import_row() {
|
|
let server = MockServer::start().await;
|
|
let deleted = qbit(&server, json!([torrent(9, "movies-kids", true)])).await;
|
|
let action = ReaperAction::new(QbitClient::new(&server.uri()).unwrap());
|
|
|
|
let labels = HashSet::from(["movies-kids".to_owned()]);
|
|
action.tick(&labels).await.unwrap();
|
|
|
|
assert_eq!(deleted.lock().unwrap().len(), 1);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_torrent_stopped_by_hand_is_left_alone() {
|
|
let server = MockServer::start().await;
|
|
let deleted = qbit(
|
|
&server,
|
|
json!([{
|
|
"hash": "hash-4", "name": "paused by the operator", "state": "stoppedUP",
|
|
"progress": 1.0, "save_path": "/downloads", "tags": "movies-main",
|
|
"ratio": 0.2, "ratio_limit": 1.5,
|
|
"seeding_time": 10, "seeding_time_limit": -1,
|
|
"inactive_seeding_time_limit": -1, "last_activity": 0
|
|
}]),
|
|
)
|
|
.await;
|
|
let action = ReaperAction::new(QbitClient::new(&server.uri()).unwrap());
|
|
|
|
let labels = HashSet::from(["movies-main".to_owned()]);
|
|
assert_eq!(
|
|
action.tick(&labels).await.unwrap(),
|
|
[] as [crate::reconcile::Outcome; 0]
|
|
);
|
|
assert!(deleted.lock().unwrap().is_empty());
|
|
}
|
|
}
|