laravel-rust-queue 0.1.0

Internal crate of Laravel for Rust: jobs, the queue drivers, the worker, batches, and chains. Depend on `laravel-rust` instead
Documentation
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>();
}

/// Retry the failed jobs of batches.
#[derive(clap::Parser)]
#[command(name = "queue:retry-batch")]
struct RetryBatch {
    /// The IDs of the batches whose failed jobs to retry.
    #[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))
    }
}

/// Delete old batches.
#[derive(clap::Parser)]
#[command(name = "queue:prune-batches")]
struct PruneBatches {
    /// Delete finished batches that finished more than this many hours ago.
    #[arg(long, default_value_t = 24, value_name = "HOURS")]
    hours: u32,
    /// Also delete unfinished batches created more than this many hours ago.
    #[arg(long, value_name = "HOURS")]
    unfinished: Option<u32>,
    /// Also delete cancelled batches created more than this many hours ago.
    #[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(())
    }
}