servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! Real HTTP behavior, router compatibility, limits, and embedded isolation.

use std::{sync::Arc, time::Duration};

use servlet::{
    App,
    ecosystem::tokio,
    sync::Semaphore,
    web::{Bytes, Path, Router, State, routing},
};

use super::support::{config, get, request};

#[tokio::test]
async fn hello_state_post_and_ordinary_routers_share_the_serving_path() {
    let router: Router<String> =
        Router::new().route("/router", routing::get(|| async { "router" }));
    let running = App::new("routes")
        .config(config())
        .get(
            "/hello/{name}",
            |State(greeting): State<String>, Path(name): Path<String>| async move {
                format!("{greeting}, {name}!")
            },
        )
        .post("/echo", |body: Bytes| async move { body })
        .http(router)
        .state("Hello".to_owned())
        .start()
        .await
        .unwrap();
    let address = running.local_addr().unwrap();
    assert!(
        get(address, "/hello/Servlet")
            .await
            .ends_with("Hello, Servlet!")
    );
    assert!(get(address, "/router").await.ends_with("router"));
    assert!(request(address, "POST /echo HTTP/1.1\r\nHost: localhost\r\nContent-Length: 4\r\nConnection: close\r\n\r\necho").await.ends_with("echo"));
    running.handle().shutdown();
    running.wait().await.unwrap();
}

#[tokio::test]
async fn embedded_applications_have_independent_listeners_and_shutdown() {
    let first = App::new("first")
        .config(config())
        .get("/", || async { "first" })
        .start()
        .await
        .unwrap();
    let second = App::new("second")
        .config(config())
        .get("/", || async { "second" })
        .start()
        .await
        .unwrap();
    assert_ne!(first.local_addr(), second.local_addr());
    first.handle().shutdown();
    first.wait().await.unwrap();
    assert!(
        get(second.local_addr().unwrap(), "/")
            .await
            .ends_with("second")
    );
    second.handle().shutdown();
    second.wait().await.unwrap();
}

#[tokio::test]
async fn admission_is_global_and_rejects_overload_without_a_request_queue() {
    let entered = Arc::new(Semaphore::new(0));
    let release = Arc::new(Semaphore::new(0));
    let worker_entered = entered.clone();
    let worker_release = release.clone();
    let mut settings = config();
    settings.max_in_flight = 1;
    let running = App::new("overload")
        .config(settings)
        .get("/slow", move || {
            let entered = worker_entered.clone();
            let release = worker_release.clone();
            async move {
                entered.add_permits(1);
                release.acquire().await.unwrap().forget();
                "done"
            }
        })
        .get("/fast", || async { "fast" })
        .start()
        .await
        .unwrap();
    let address = running.local_addr().unwrap();
    let first = tokio::spawn(async move { get(address, "/slow").await });
    entered.acquire().await.unwrap().forget();
    assert!(get(address, "/fast").await.starts_with("HTTP/1.1 503"));
    release.add_permits(1);
    assert!(first.await.unwrap().ends_with("done"));
    assert!(get(address, "/fast").await.ends_with("fast"));
    running.handle().shutdown();
    running.wait().await.unwrap();
}

#[tokio::test]
async fn body_limit_applies_to_length_and_chunked_requests() {
    let mut settings = config();
    settings.request_body_limit = 4;
    let running = App::new("body-limit")
        .config(settings)
        .post("/", |body: Bytes| async move { body })
        .start()
        .await
        .unwrap();
    let address = running.local_addr().unwrap();
    let oversized = request(
        address,
        "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 5\r\nConnection: close\r\n\r\n12345",
    )
    .await;
    assert!(oversized.starts_with("HTTP/1.1 413"));
    let chunked = request(address, "POST / HTTP/1.1\r\nHost: localhost\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n5\r\n12345\r\n0\r\n\r\n").await;
    assert!(chunked.starts_with("HTTP/1.1 413"));
    running.handle().shutdown();
    running.wait().await.unwrap();
}

#[tokio::test]
async fn a_handler_deadline_returns_504_before_headers() {
    let mut settings = config();
    settings.request_timeout = Duration::from_millis(30);
    let running = App::new("request-timeout")
        .config(settings)
        .get("/", || async {
            std::future::pending::<&'static str>().await
        })
        .start()
        .await
        .unwrap();
    assert!(
        get(running.local_addr().unwrap(), "/")
            .await
            .starts_with("HTTP/1.1 504")
    );
    running.handle().shutdown();
    running.wait().await.unwrap();
}