laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
use std::sync::atomic::{AtomicUsize, Ordering};

use laravel::Application;
use laravel::config::Env;
use laravel::config::session::Driver;
use laravel::container::Registrar;
use laravel::context::Context;
use laravel::crypt::{Cipher, Encrypter};
use laravel::foundation::ServiceProvider;
use laravel::http::Json;
use laravel::routing::Router;
use laravel::testing::MakesHttpRequests;
use serde_json::{Value, json};

#[derive(Default)]
struct Teams {
    lookups: AtomicUsize,
}

impl Teams {
    async fn name(&self, id: u64) -> String {
        self.lookups.fetch_add(1, Ordering::SeqCst);
        tokio::task::yield_now().await;
        format!("Team {id}")
    }
}

struct TeamsProvider;

impl ServiceProvider for TeamsProvider {
    fn register(&self, app: &mut Registrar) {
        app.instance(Teams::default());
    }
}

async fn current_team() -> String {
    laravel::once(|| async { laravel::resolve::<Teams>().await.unwrap().name(1).await }).await
}

async fn team(id: u64) -> String {
    laravel::once_for(id, |id| async move {
        laravel::resolve::<Teams>().await.unwrap().name(id).await
    })
    .await
}

async fn lookups() -> usize {
    laravel::resolve::<Teams>()
        .await
        .unwrap()
        .lookups
        .load(Ordering::SeqCst)
}

async fn teams() -> Json<Value> {
    let before = lookups().await;
    let (first, second) = tokio::join!(current_team(), current_team());
    let others = [team(2).await, team(3).await, team(2).await];

    Json(json!({
        "teams": [first, second, current_team().await],
        "others": others,
        "lookups": lookups().await - before,
    }))
}

async fn spawned() -> laravel::Result<String> {
    let context = Context::current().expect("handling a request");

    let url = tokio::spawn(context.scope(async { laravel::url::route(teams, ()) }))
        .await
        .expect("the task ran")?;

    Ok(url)
}

fn app() -> Application {
    app_with(Env::from_process())
}

fn app_with(env: Env) -> Application {
    Application::configure()
        .replace_env(env)
        .with_config(|config, _| {
            config.app.key = Some(Encrypter::generate_key(Cipher::Aes256Cbc));
            config.session.driver = Driver::Memory;
        })
        .with_providers(|providers| {
            providers.add(TeamsProvider);
        })
        .with_routing(|routing, _| {
            routing.web(|route: &mut Router| {
                route.get("/teams", teams);
                route.get("/spawned", spawned);
                route.get("/unscoped", || async {
                    tokio::spawn(async { laravel::url::to("/") }).await.unwrap()
                });
            });
        })
        .create()
}

#[tokio::test]
async fn once_computes_a_value_once_per_request_and_key() {
    app().get("/teams").await.assert_json(json!({
        "teams": ["Team 1", "Team 1", "Team 1"],
        "others": ["Team 2", "Team 3", "Team 2"],
        "lookups": 3,
    }));
}

#[tokio::test]
async fn once_computes_again_for_the_next_request() {
    let app = app();

    app.get("/teams").await.assert_json_path("lookups", 3);
    app.get("/teams").await.assert_json_path("lookups", 3);
}

#[tokio::test]
async fn spawned_tasks_take_the_context_along() {
    app().get("/spawned").await.assert_see("http://localhost/teams");
}

#[tokio::test]
async fn spawned_tasks_have_no_context_by_default() {
    app().get("/unscoped").await.assert_internal_server_error();
}

fn scoped_app() -> Application {
    app_with(Env::from_iter([("APP_URL", "https://example.com")]))
}

#[tokio::test]
async fn helpers_work_in_an_application_scope() {
    let (team, url) = scoped_app()
        .scope(async || (current_team().await, laravel::url::route(teams, ()).expect("a route")))
        .await;

    assert_eq!(team, "Team 1");
    assert_eq!(url, "https://example.com/teams");
}

#[tokio::test]
async fn once_computes_a_value_once_per_scope() {
    let app = scoped_app();

    let saved = app
        .scope(async || {
            let before = lookups().await;
            let (first, second) = tokio::join!(current_team(), current_team());
            assert_eq!((first.as_str(), second.as_str()), ("Team 1", "Team 1"));
            current_team().await;

            lookups().await - before
        })
        .await;
    let next = app.scope(async || (current_team().await, lookups().await)).await;

    assert_eq!(saved, 1);
    assert_eq!(next, ("Team 1".to_owned(), 2));
}

#[test]
#[should_panic(expected = "`laravel::url::to()` can only be used inside the application")]
fn helpers_need_the_application() {
    let _ = laravel::url::to("/");
}

#[tokio::test]
async fn urls_pass_through_and_lose_trailing_slashes() {
    let app = Application::configure()
        .replace_env(Env::from_iter([("APP_URL", "https://example.com")]))
        .create();

    let urls = app
        .scope(async || {
            [
                laravel::url::to("/"),
                laravel::url::to("/users/"),
                laravel::url::to("users?page=2"),
                laravel::url::to("https://laravel.com/docs"),
                laravel::url::to("mailto:taylor@laravel.com"),
                laravel::url::to("#top"),
            ]
        })
        .await;

    assert_eq!(
        urls,
        [
            "https://example.com",
            "https://example.com/users",
            "https://example.com/users?page=2",
            "https://laravel.com/docs",
            "mailto:taylor@laravel.com",
            "#top",
        ]
    );
}