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;
pub trait Middleware: Send + 'static {
fn handle(self, attempt: &Attempt, next: Next) -> impl Future<Output = Result<()>> + Send;
}
pub struct Next(BoxFuture<'static, Result<()>>);
impl Next {
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")
}
}
#[derive(Default)]
pub struct MiddlewareGroup {
entries: Vec<Entry>,
}
struct Entry {
name: &'static str,
middleware: Box<dyn Erased>,
}
impl MiddlewareGroup {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[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 })
}
}
#[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 {
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);