laravel-rust 0.1.0

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

use axum::Json;
use axum::body::Bytes;
use axum::extract::Multipart;
use axum::http::{HeaderMap, StatusCode};
use axum::response::IntoResponse;
use axum::routing::{post, put};
use laravel::Application;
use laravel::config::Env;
use laravel::http::Request;
use laravel::http::client::{self, Attachment, Error};
use laravel::testing::MakesHttpRequests;
use laravel::time::ToSpan;
use serde_json::{Value, json};

use crate::http_client::serve;
use crate::support::TempDir;

async fn describe(mut form: Multipart) -> Json<Value> {
    let mut fields = serde_json::Map::new();
    let mut files = Vec::new();
    while let Some(part) = form.next_field().await.unwrap() {
        let name = part.name().unwrap_or_default().to_owned();
        match part.file_name().map(str::to_owned) {
            Some(file_name) => {
                let content_type = part.content_type().map(str::to_owned);
                let contents = part.bytes().await.unwrap();
                files.push(json!({
                    "name": name,
                    "file_name": file_name,
                    "content_type": content_type,
                    "contents": String::from_utf8_lossy(&contents),
                }));
            }
            None => {
                fields.insert(name, Value::String(part.text().await.unwrap()));
            }
        }
    }

    Json(json!({ "fields": fields, "files": files }))
}

async fn raw(headers: HeaderMap, body: Bytes) -> Json<Value> {
    let header = |name: &str| headers.get(name).map(|value| value.to_str().unwrap().to_owned());

    Json(json!({
        "content_type": header("content-type"),
        "content_length": header("content-length"),
        "body": String::from_utf8_lossy(&body),
    }))
}

async fn server() -> String {
    let attempts = Arc::new(AtomicUsize::new(0));
    let router = axum::Router::new()
        .route("/upload", post(describe))
        .route("/raw", put(raw))
        .route(
            "/flaky",
            post(move |form: Multipart| {
                let attempt = attempts.fetch_add(1, Ordering::SeqCst);
                async move {
                    if attempt == 0 {
                        return StatusCode::SERVICE_UNAVAILABLE.into_response();
                    }
                    describe(form).await.into_response()
                }
            }),
        );

    serve(router).await
}

fn application() -> Application {
    Application::configure().replace_env(Env::default()).create()
}

#[tokio::test]
async fn attachments_are_sent_as_multipart_forms_with_their_fields() {
    let url = server().await;
    let directory = TempDir::with_files("http-uploads", &[("report.pdf", "%PDF report")]);
    let app = application();
    app.scope(async || {
        let received: Value = client::post(format!("{url}/upload"))
            .attach("photo", Attachment::from_data("png bytes", "taylor.png"))
            .attach("report", Attachment::from_path(directory.join("report.pdf")).named("q3.pdf"))
            .attach("blob", Attachment::from_data("webp bytes", "blob").mime("image/webp"))
            .form([("caption", "At Laracon")])
            .ensure_successful()
            .await
            .unwrap()
            .json()
            .unwrap();

        assert_eq!(received["fields"], json!({ "caption": "At Laracon" }));
        assert_eq!(
            received["files"],
            json!([
                { "name": "photo", "file_name": "taylor.png", "content_type": "image/png", "contents": "png bytes" },
                { "name": "report", "file_name": "q3.pdf", "content_type": "application/pdf", "contents": "%PDF report" },
                { "name": "blob", "file_name": "blob", "content_type": "image/webp", "contents": "webp bytes" },
            ])
        );
    })
    .await;
}

#[tokio::test]
async fn retries_send_attached_files_again() {
    let url = server().await;
    let directory = TempDir::with_files("http-upload-retries", &[("data.csv", "a,b\n1,2\n")]);
    let app = application();
    app.scope(async || {
        let received: Value = client::post(format!("{url}/flaky"))
            .attach("data", Attachment::from_path(directory.join("data.csv")))
            .retry(2, 0.seconds())
            .await
            .unwrap()
            .json()
            .unwrap();

        assert_eq!(received["files"][0]["contents"], "a,b\n1,2\n");
        assert_eq!(received["files"][0]["content_type"], "text/csv");
    })
    .await;
}

#[tokio::test]
async fn files_are_sent_as_raw_bodies_with_their_length() {
    let url = server().await;
    let directory = TempDir::with_files("http-raw-body", &[("backup.zip", "zip contents")]);
    let app = application();
    app.scope(async || {
        let received: Value = client::put(format!("{url}/raw"))
            .body_file(directory.join("backup.zip"), "application/zip")
            .await
            .unwrap()
            .json()
            .unwrap();

        assert_eq!(received["content_type"], "application/zip");
        assert_eq!(received["content_length"], "12");
        assert_eq!(received["body"], "zip contents");
    })
    .await;
}

#[tokio::test]
async fn relative_paths_are_in_the_base_path_and_fakes_see_the_files() {
    let directory = TempDir::with_files("http-upload-fakes", &[("storage/app/q3.pdf", "%PDF")]);
    let base_path = directory.to_path_buf();
    let app = Application::configure()
        .replace_env(Env::default())
        .with_config(move |config, _| config.app.base_path = base_path)
        .create();
    app.scope(async || {
        let http = client::fake();

        client::post("https://example.com/reports")
            .attach("report", Attachment::from_path("storage/app/q3.pdf"))
            .form([("quarter", "3")])
            .await
            .unwrap();
        client::put("https://example.com/raw")
            .body_file("storage/app/q3.pdf", "application/pdf")
            .await
            .unwrap();

        let sent = http.sent();
        assert!(sent[0].has_file("report", "q3.pdf"));
        assert_eq!(sent[0].files()[0].contents(), b"%PDF");
        assert_eq!(sent[0].files()[0].content_type(), "application/pdf");
        assert_eq!(sent[0].data()["quarter"], "3");
        assert_eq!(sent[1].body(), b"%PDF");
        assert!(sent[1].has_header("content-type", "application/pdf"));
    })
    .await;
}

#[tokio::test]
async fn unreadable_files_line_breaks_in_file_names_and_attachments_on_raw_bodies_are_invalid() {
    let app = application();
    app.scope(async || {
        let _http = client::fake();

        let error = client::post("https://example.com")
            .attach("report", Attachment::from_path("/missing/q3.pdf"))
            .await
            .unwrap_err();
        assert!(
            matches!(&error, Error::Invalid(invalid) if invalid.to_string().contains("`/missing/q3.pdf` can't be read")),
            "{error}"
        );
        let cause = std::error::Error::source(&error).and_then(|source| source.downcast_ref::<std::io::Error>());
        assert_eq!(cause.map(std::io::Error::kind), Some(std::io::ErrorKind::NotFound));

        let error = client::post("https://example.com")
            .attach("photo", Attachment::from_data("<svg/>", "a.png\r\nContent-Type: text/html"))
            .await
            .unwrap_err();
        assert!(
            matches!(&error, Error::Invalid(invalid) if invalid.to_string().contains("the file name of the `photo` attachment")),
            "{error}"
        );

        let error = client::post("https://example.com")
            .json(json!({ "a": 1 }))
            .attach("photo", Attachment::from_data("png", "a.png"))
            .await
            .unwrap_err();
        assert!(
            matches!(&error, Error::Invalid(invalid) if invalid.to_string().contains("can't be attached to a JSON or raw body")),
            "{error}"
        );
    })
    .await;
}

#[derive(serde::Deserialize, laravel::validation::Validate)]
#[validate(anyone)]
struct Photo {
    #[validate(required)]
    photo: laravel::http::UploadedFile,
}

async fn forward(request: Request) -> laravel::Result<&'static str> {
    let form: Photo = request.validate().await?;
    client::post("https://storage.example.com/photos")
        .attach("photo", &form.photo)
        .ensure_successful()
        .await?;

    Ok("stored")
}

#[tokio::test]
async fn received_uploads_can_be_forwarded() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_routing(|routing, _| {
            routing.routes(|routes| {
                routes.post("/photos", forward);
            });
        })
        .create();
    app.scope(async || {
        let http = client::fake();

        app.post("/photos")
            .attach("photo", Attachment::from_data("png bytes", "taylor.png"))
            .await
            .assert_ok()
            .assert_see("stored");

        http.assert_sent(|request| {
            request.has_file("photo", "taylor.png")
                && request.files()[0].contents() == b"png bytes"
                && request.files()[0].content_type() == "image/png"
        });

        let png: &[u8] = &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0];
        app.post("/photos")
            .attach("photo", Attachment::from_data(png, "photo.txt"))
            .await
            .assert_ok();
        let sent = http.sent();
        let file = &sent[1].files()[0];
        assert_eq!(
            (file.file_name(), file.content_type()),
            ("photo.txt", "image/png"),
            "types come from bytes"
        );
    })
    .await;
}