Skip to main content

Middleware

Trait Middleware 

Source
pub trait Middleware: Send + 'static {
    // Required method
    fn handle(
        self,
        attempt: &Attempt,
        next: Next,
    ) -> impl Future<Output = Result<(), Error>> + Send;
}
Expand description

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] 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;

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]. That function’s parameters after next become the struct’s fields.

Required Methods§

Source

fn handle( self, attempt: &Attempt, next: Next, ) -> impl Future<Output = Result<(), Error>> + Send

Handle the attempt, usually by running the rest of the job with next.

An error fails the attempt, as an error from handle does.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§