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 std::any::type_name;
use std::fmt;
use std::future::Future;
use std::sync::Arc;

use futures_util::future::BoxFuture;

use super::Attempt;
use crate::Result;
use crate::errors::panic;

/// Code that runs around a job's `handle`, such as a check that decides whether the job runs
/// now.
///
/// A job lists its middleware in a `middleware` method on its [`#[job]`](macro@super::job)
/// `impl` block, and the worker creates a fresh set for each attempt. A middleware runs the rest
/// of the job with [`Next::run`]. It may run code before and after that call, skip the rest of
/// the job by not calling it, or release, delete, or fail the job through the [`Attempt`]:
///
/// ```
/// use laravel::queue::{Attempt, Middleware, Next};
/// use laravel::time::ToSpan;
/// # struct Maintenance;
/// # impl Maintenance { fn is_down() -> bool { false } }
///
/// pub struct WaitForMaintenance;
///
/// impl Middleware for WaitForMaintenance {
///     async fn handle(self, attempt: &Attempt, next: Next) -> laravel::Result<()> {
///         if Maintenance::is_down() {
///             attempt.release(5.minutes());
///             return Ok(());
///         }
///
///         next.run().await
///     }
/// }
/// ```
///
/// A middleware that skips `handle` without releasing, deleting, or failing the job lets the
/// attempt succeed. The job's `timeout` covers its middleware and `handle` together, and
/// middleware don't wrap the job's `failed` hook. A job's middleware are part of its type, so a
/// change to them also applies to jobs that are already queued.
///
/// Most middleware are shorter to write as an async function marked with
/// [`#[middleware]`](macro@super::middleware). That function's parameters after `next` become
/// the struct's fields.
pub trait Middleware: Send + 'static {
    /// Handle the attempt, usually by running the rest of the job with `next`.
    ///
    /// An error fails the attempt, as an error from `handle` does.
    fn handle(self, attempt: &Attempt, next: Next) -> impl Future<Output = Result<()>> + Send;
}

/// The rest of a job's middleware, and its `handle`.
pub struct Next(BoxFuture<'static, Result<()>>);

impl Next {
    /// Run the rest of the job.
    ///
    /// Code after this call runs however the rest of the job ends.
    ///
    /// # Errors
    ///
    /// Returns the error from the remaining middleware or from `handle`. A panic in either one
    /// becomes an error too.
    pub async fn run(self) -> Result<()> {
        panic::catch(self.0).await
    }
}

impl fmt::Debug for Next {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Next")
    }
}

/// An ordered list of job middleware, where the first middleware runs first and wraps the rest.
///
/// A job's `middleware` method usually returns one middleware or a tuple of middleware. Build a
/// group to share a list between jobs, or to decide which middleware to add at run time.
#[derive(Default)]
pub struct MiddlewareGroup {
    entries: Vec<Entry>,
}

struct Entry {
    name: &'static str,
    middleware: Box<dyn Erased>,
}

impl MiddlewareGroup {
    /// Create an empty group.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add middleware to the end of the group, so that it runs after the middleware already in it.
    #[must_use]
    pub fn with(mut self, middleware: impl IntoMiddleware) -> Self {
        self.entries.extend(middleware.into_group().entries);
        self
    }

    pub(crate) async fn run(self, attempt: Arc<Attempt>, handle: BoxFuture<'static, Result<()>>) -> Result<()> {
        let mut next = Next(handle);
        for entry in self.entries.into_iter().rev() {
            next = Next(entry.middleware.handle(Arc::clone(&attempt), next));
        }

        next.run().await
    }
}

impl fmt::Debug for MiddlewareGroup {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list()
            .entries(self.entries.iter().map(|entry| entry.name))
            .finish()
    }
}

trait Erased: Send {
    fn handle(self: Box<Self>, attempt: Arc<Attempt>, next: Next) -> BoxFuture<'static, Result<()>>;
}

impl<M: Middleware> Erased for M {
    fn handle(self: Box<Self>, attempt: Arc<Attempt>, next: Next) -> BoxFuture<'static, Result<()>> {
        Box::pin(async move { Middleware::handle(*self, &attempt, next).await })
    }
}

/// A type that a job's `middleware` method may return.
///
/// The supported types are a [`Middleware`], a [`MiddlewareGroup`], an `Option` of either, and a
/// tuple of these.
#[diagnostic::on_unimplemented(
    message = "`{Self}` isn't job middleware",
    label = "return a middleware, a tuple of middleware, an `Option` or a `MiddlewareGroup`",
    note = "job middleware implement `laravel::queue::Middleware`, or are functions marked with `#[laravel::queue::middleware]`"
)]
pub trait IntoMiddleware {
    /// Convert the value into a middleware group.
    fn into_group(self) -> MiddlewareGroup;
}

impl<M: Middleware> IntoMiddleware for M {
    fn into_group(self) -> MiddlewareGroup {
        MiddlewareGroup {
            entries: vec![Entry {
                name: type_name::<M>(),
                middleware: Box::new(self),
            }],
        }
    }
}

impl IntoMiddleware for MiddlewareGroup {
    fn into_group(self) -> MiddlewareGroup {
        self
    }
}

impl<T: IntoMiddleware> IntoMiddleware for Option<T> {
    fn into_group(self) -> MiddlewareGroup {
        self.map(IntoMiddleware::into_group).unwrap_or_default()
    }
}

macro_rules! tuple_middleware {
    ($($name:ident),+) => {
        impl<$($name: IntoMiddleware),+> IntoMiddleware for ($($name,)+) {
            #[expect(non_snake_case, reason = "the bindings reuse the type parameters' names")]
            fn into_group(self) -> MiddlewareGroup {
                let ($($name,)+) = self;
                MiddlewareGroup::new()$(.with($name))+
            }
        }
    };
}

tuple_middleware!(A);
tuple_middleware!(A, B);
tuple_middleware!(A, B, C);
tuple_middleware!(A, B, C, D);
tuple_middleware!(A, B, C, D, E);
tuple_middleware!(A, B, C, D, E, F);
tuple_middleware!(A, B, C, D, E, F, G);
tuple_middleware!(A, B, C, D, E, F, G, H);
tuple_middleware!(A, B, C, D, E, F, G, H, I);
tuple_middleware!(A, B, C, D, E, F, G, H, I, K);
tuple_middleware!(A, B, C, D, E, F, G, H, I, K, L);
tuple_middleware!(A, B, C, D, E, F, G, H, I, K, L, M);