use super::failed::{not_kept, retry_and_report};
use crate::Result;
use crate::console::{Commands, Console, clap};
use crate::container::Inject;
use crate::queue::QueueManager;
use crate::queue::batch::BatchId;
use crate::queue::batch::store::{Prune, Store};
pub(super) fn register(commands: &mut Commands) {
commands.add::<RetryBatch>().add::<PruneBatches>();
}
#[derive(clap::Parser)]
#[command(name = "queue:retry-batch")]
struct RetryBatch {
#[arg(required = true)]
ids: Vec<String>,
}
#[crate::console::command]
impl RetryBatch {
async fn handle(self, manager: Inject<QueueManager>, console: &mut Console) -> Result<u8> {
let Some(failed) = manager.failed()? else {
return Err(not_kept());
};
let store = Store::open(&manager)?;
let mut failing = false;
for id in &self.ids {
let batch = match id.parse::<BatchId>() {
Ok(parsed) => store.find(parsed).await?,
Err(_) => None,
};
let Some(batch) = batch else {
console.error(format!("no batch has the ID `{id}`"));
failing = true;
continue;
};
if batch.is_cancelled() {
console.error(format!(
"batch `{id}` was cancelled, so its failed jobs can't be retried"
));
failing = true;
continue;
}
let jobs = store.failed_jobs(batch.id()).await?;
if jobs.is_empty() {
console.info(format!("Batch `{id}` has no failed jobs."));
continue;
}
for job_id in jobs {
match failed.find(job_id).await? {
Some(job) => failing |= !retry_and_report(&manager, &failed, &job, console).await,
None => {
console.error(format!("no failed job has the ID `{job_id}`"));
failing = true;
}
}
}
}
Ok(u8::from(failing))
}
}
#[derive(clap::Parser)]
#[command(name = "queue:prune-batches")]
struct PruneBatches {
#[arg(long, default_value_t = 24, value_name = "HOURS")]
hours: u32,
#[arg(long, value_name = "HOURS")]
unfinished: Option<u32>,
#[arg(long, value_name = "HOURS")]
cancelled: Option<u32>,
}
#[crate::console::command]
impl PruneBatches {
async fn handle(self, manager: Inject<QueueManager>, console: &mut Console) -> Result<()> {
let store = Store::open(&manager)?;
let pruned = [
(Prune::Finished, Some(self.hours), "finished"),
(Prune::Unfinished, self.unfinished, "unfinished"),
(Prune::Cancelled, self.cancelled, "cancelled"),
];
for (prune, hours, kind) in pruned {
let Some(hours) = hours else {
continue;
};
let deleted = store.prune(prune, super::hours_ago(hours)).await?;
match deleted {
0 => console.info(format!("No {kind} batches found.")),
1 => console.success(format!("1 {kind} batch deleted.")),
deleted => console.success(format!("{deleted} {kind} batches deleted.")),
}
}
Ok(())
}
}