laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
use laravel::Application;
use laravel::config::Env;
use laravel::container::Inject;
use laravel::queue::Queueable;
use laravel::queue::{Attempt, IntoMiddleware, Middleware, MiddlewareGroup, Next, job, middleware};
use laravel::testing::RunsJobs;
use laravel::time::ToSpan;
use serde::{Deserialize, Serialize};

use crate::queue::Records;

#[derive(Debug, thiserror::Error)]
#[error("the middleware refused")]
pub(crate) struct Refused;

#[derive(Debug, thiserror::Error)]
#[error("the handler broke")]
pub(crate) struct Broke;

#[middleware]
pub(crate) async fn record(records: Inject<Records>, next: Next, label: &'static str) -> laravel::Result<()> {
    records.push(format!("{label} before"));
    let result = next.run().await;
    records.push(match &result {
        Ok(()) => format!("{label} after"),
        Err(error) => format!("{label} after: {error}"),
    });

    result
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum Decision {
    Run,
    Skip,
    Release,
    Delete,
    Fail,
    Error,
    Panic,
    ReleaseOnError,
}

pub(crate) struct Decide(Decision);

impl Middleware for Decide {
    async fn handle(self, attempt: &Attempt, next: Next) -> laravel::Result<()> {
        match self.0 {
            Decision::Run => next.run().await,
            Decision::Skip => Ok(()),
            Decision::Release => {
                attempt.release(30.seconds());
                Ok(())
            }
            Decision::Delete => {
                attempt.delete();
                Ok(())
            }
            Decision::Fail => {
                attempt.fail(Refused);
                Ok(())
            }
            Decision::Error => Err(Refused.into()),
            Decision::Panic => panic!("the middleware panicked"),
            Decision::ReleaseOnError => {
                if next.run().await.is_err() {
                    attempt.release(1.minutes());
                }
                Ok(())
            }
        }
    }
}

#[derive(Queueable)]
pub(crate) struct Guarded {
    pub(crate) decision: Decision,
    pub(crate) handle: String,
}

impl Guarded {
    pub(crate) fn new(decision: Decision) -> Self {
        Self {
            decision,
            handle: "ok".into(),
        }
    }

    fn then(mut self, handle: &str) -> Self {
        self.handle = handle.into();
        self
    }
}

#[job(tries = 3, backoff = 10.seconds())]
impl Guarded {
    fn middleware(&self) -> impl IntoMiddleware {
        (record("outer"), Decide(self.decision), record("inner"))
    }

    async fn handle(self, records: Inject<Records>) -> laravel::Result<()> {
        records.push("handled");
        match self.handle.as_str() {
            "error" => Err(Broke.into()),
            "panic" => panic!("the handler panicked"),
            _ => Ok(()),
        }
    }

    async fn failed(self, error: &laravel::Error, records: Inject<Records>) {
        records.push(format!("failed hook: {error}"));
    }
}

pub(crate) const WRAPPED: [&str; 5] = ["outer before", "inner before", "handled", "inner after", "outer after"];

fn application(connection: &'static str) -> Application {
    Application::configure()
        .replace_env(Env::default())
        .with_config(move |config, _| {
            config.queue.default = connection.into();
        })
        .with_services(|services| {
            services.instance(Records::default());
        })
        .create()
}

async fn take(app: &Application) -> Vec<String> {
    let records = app.resolve::<Records>().await;
    let all = records.all();
    records.clear();

    all
}

#[tokio::test]
async fn optional_middleware_and_groups_wrap_handle_in_order() {
    #[derive(Queueable)]
    struct Grouped;

    #[job]
    impl Grouped {
        fn middleware(&self) -> impl IntoMiddleware {
            (
                Some(record("outer")),
                None::<Decide>,
                MiddlewareGroup::new().with(record("inner")),
            )
        }

        async fn handle(self, records: Inject<Records>) {
            records.push("handled");
        }
    }

    let app = application("discard");
    app.job(Grouped).await.assert_succeeded();

    assert_eq!(take(&app).await, WRAPPED);
}

#[tokio::test]
async fn middleware_wrap_handle_in_order_on_the_sync_connection_dispatch_sync_and_test_attempts() {
    let app = application("sync");

    app.scope(async || Guarded::new(Decision::Run).dispatch().await)
        .await
        .unwrap();
    assert_eq!(take(&app).await, WRAPPED, "the sync connection");

    app.scope(async || Guarded::new(Decision::Run).dispatch_sync().await)
        .await
        .unwrap();
    assert_eq!(take(&app).await, WRAPPED, "dispatch_sync");

    app.job(Guarded::new(Decision::Run)).await.assert_succeeded();
    assert_eq!(take(&app).await, WRAPPED, "a test attempt");
}

#[tokio::test]
async fn middleware_decide_how_an_attempt_ends() {
    let app = application("discard");
    let skipped = ["outer before", "outer after"];

    app.job(Guarded::new(Decision::Skip)).await.assert_succeeded();
    assert_eq!(take(&app).await, skipped, "skipping `handle` succeeds");

    app.job(Guarded::new(Decision::Release))
        .await
        .assert_released_after(30.seconds());
    app.job(Guarded::new(Decision::Delete)).await.assert_deleted();
    app.job(Guarded::new(Decision::Fail))
        .await
        .assert_failed_with::<Refused>();
    app.job(Guarded::new(Decision::Error))
        .await
        .assert_failed_with::<Refused>();
    assert_eq!(
        take(&app).await,
        [
            "outer before",
            "outer after",
            "outer before",
            "outer after",
            "outer before",
            "outer after",
            "outer before",
            "outer after: the middleware refused",
        ]
    );

    app.job(Guarded::new(Decision::Panic)).await.assert_failed();
    let records = take(&app).await;
    assert!(
        records.len() == 2
            && records[1].starts_with("outer after: ")
            && records[1].ends_with("the middleware panicked"),
        "a panic in a middleware reaches the ones around it as an error: {records:?}"
    );

    app.job(Guarded::new(Decision::ReleaseOnError).then("error"))
        .await
        .assert_released_after(1.minutes());
    assert_eq!(
        take(&app).await,
        [
            "outer before",
            "inner before",
            "handled",
            "inner after: the handler broke",
            "outer after"
        ],
        "a middleware sees the handler's error, and can turn it into a release"
    );

    app.job(Guarded::new(Decision::Run).then("panic")).await.assert_failed();
    let records = take(&app).await;
    assert_eq!(records[..3], ["outer before", "inner before", "handled"]);
    assert!(
        records[3].starts_with("inner after: ") && records[3].ends_with("the handler panicked"),
        "a panic in `handle` reaches the middleware as an error: {records:?}"
    );
    assert!(records[4].starts_with("outer after: "), "{records:?}");
}

#[tokio::test]
async fn the_sync_connection_applies_middleware_decisions_once() {
    let app = application("sync");

    app.scope(async || Guarded::new(Decision::Release).dispatch().await)
        .await
        .unwrap();
    app.scope(async || Guarded::new(Decision::Delete).dispatch_sync().await)
        .await
        .unwrap();
    assert_eq!(
        take(&app).await,
        ["outer before", "outer after", "outer before", "outer after"]
    );

    let error = app
        .scope(async || Guarded::new(Decision::Fail).dispatch().await)
        .await
        .unwrap_err();
    assert!(error.is::<Refused>(), "{error}");
    assert_eq!(
        take(&app).await,
        ["outer before", "outer after", "failed hook: the middleware refused"]
    );
}

#[tokio::test]
async fn a_middlewares_missing_service_fails_the_job_naming_it() {
    struct Limiter;

    #[middleware]
    async fn limit(_limiter: Inject<Limiter>, next: Next) -> laravel::Result<()> {
        next.run().await
    }

    #[derive(Queueable)]
    struct Limited;

    #[job]
    impl Limited {
        fn middleware(&self) -> limit {
            limit
        }

        async fn handle(self, records: Inject<Records>) {
            records.push("handled");
        }
    }

    let app = application("discard");
    let result = app.job(Limited).await;
    let error = result.assert_failed().error().unwrap().to_string();
    assert!(
        error.contains("injecting `integration::queue_middleware::Limited` failed"),
        "{error}"
    );
    assert!(take(&app).await.is_empty());
}

#[tokio::test]
async fn a_panic_choosing_middleware_fails_the_job() {
    #[derive(Queueable)]
    struct Unchosen;

    #[job]
    impl Unchosen {
        fn middleware(&self) -> impl IntoMiddleware {
            panic!("no middleware for you");
            #[expect(unreachable_code, reason = "the type of the panicking branch")]
            record("never")
        }

        async fn handle(self, records: Inject<Records>) {
            records.push("handled");
        }

        async fn failed(self, error: &laravel::Error, records: Inject<Records>) {
            records.push(format!("failed hook: {error}"));
        }
    }

    let app = application("sync");
    let error = app.scope(async || Unchosen.dispatch().await).await.unwrap_err();
    assert!(error.to_string().contains("no middleware for you"), "{error}");
    let records = take(&app).await;
    assert!(
        records.len() == 1 && records[0].starts_with("failed hook: ") && records[0].ends_with("no middleware for you"),
        "{records:?}"
    );

    app.job(Unchosen).await.assert_failed();
}