servlet 1.0.0

A small application runtime with an explicit operational contract
Documentation
//! All post-admission responses retain ownership through consumption or drop.
use super::{HttpState, TIMEOUT_WRITE_ALLOWANCE, TransferDeadline};
use crate::{AppConfig, lifecycle::Shared, telemetry::OutcomeSlot, web::RequestId};
use axum::{
    Router,
    body::Body,
    http::{Request, StatusCode},
    routing::get,
};
use http_body_util::BodyExt;
use std::time::Duration;
use tokio::time::Instant;

#[tokio::test(start_paused = true)]
async fn unavailable_request_id_has_a_bounded_uncorrelated_rejection() {
    let shared = Shared::new("request-id".into());
    let config = AppConfig::default();
    let state = HttpState::new(Router::new(), shared.clone(), &config);
    let response = state.request_id_unavailable();

    assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
    assert_eq!(response.headers()["connection"], "close");
    assert!(!response.headers().contains_key("x-request-id"));
    assert_eq!(
        response.extensions().get::<TransferDeadline>().unwrap().0,
        Instant::now() + config.body_idle_timeout
    );
    assert!(
        response
            .into_body()
            .collect()
            .await
            .unwrap()
            .to_bytes()
            .is_empty()
    );
    let metrics = shared.metrics.render();
    assert!(metrics.contains("servlet_runtime_rejections_total 1\n"));
    assert!(metrics.contains("servlet_exchanges_admitted_total 0\n"));
}

#[tokio::test(start_paused = true)]
async fn generated_responses_share_body_ownership_and_explicit_deadlines() {
    for (path, length, status, outcome) in [
        ("/", 0, StatusCode::OK, "completed"),
        ("/", 1025, StatusCode::PAYLOAD_TOO_LARGE, "failed"),
        ("/hang", 0, StatusCode::GATEWAY_TIMEOUT, "timed_out"),
    ] {
        for consume in [false, true] {
            let shared = Shared::new("finalization".into());
            shared.begin_running();
            let config = AppConfig {
                max_in_flight: 1,
                request_body_limit: 1024,
                request_timeout: Duration::from_secs(1),
                ..AppConfig::default()
            };
            let router = Router::new()
                .route("/", get(|| async { "hello" }))
                .route("/hang", get(std::future::pending::<&'static str>));
            let state = HttpState::new(router, shared.clone(), &config);
            let started = Instant::now();
            let request = Request::builder()
                .uri(path)
                .header("content-length", length)
                .body(Body::empty())
                .unwrap();
            let response = state
                .admit(request, &RequestId("test".into()), &OutcomeSlot::default())
                .await;
            assert_eq!(response.status(), status);
            let expected = started
                + config.request_timeout
                + if status == StatusCode::GATEWAY_TIMEOUT {
                    TIMEOUT_WRITE_ALLOWANCE
                } else {
                    Duration::ZERO
                };
            assert_eq!(
                response.extensions().get::<TransferDeadline>().unwrap().0,
                expected
            );
            assert_eq!(state.capacity.available_permits(), 0);
            let snapshot = shared.metrics.render();
            assert!(
                snapshot.contains("servlet_exchanges_active 1\n"),
                "{snapshot}"
            );
            assert!(
                snapshot.contains("servlet_exchanges_finished_total 0\n"),
                "{snapshot}"
            );
            if consume {
                response.into_body().collect().await.unwrap();
            } else {
                drop(response);
            }
            assert_eq!(state.capacity.available_permits(), 1);
            let terminal = if !consume && status == StatusCode::OK {
                "cancelled"
            } else {
                outcome
            };
            let snapshot = shared.metrics.render();
            assert!(
                snapshot.contains("servlet_exchanges_active 0\n"),
                "{snapshot}"
            );
            assert!(
                snapshot.contains("servlet_exchanges_finished_total 1\n"),
                "{snapshot}"
            );
            assert!(
                snapshot.contains(&format!(
                    "servlet_exchanges_outcomes_total{{outcome=\"{terminal}\"}} 1\n"
                )),
                "{snapshot}"
            );
        }
    }
}

#[tokio::test(start_paused = true)]
async fn middleware_handler_and_transfer_share_the_admission_deadline() {
    use crate::web::RequestDeadline;
    use axum::middleware::{self, Next};
    let shared = Shared::new("deadline".into());
    shared.begin_running();
    let config = AppConfig {
        request_timeout: Duration::from_secs(1),
        ..AppConfig::default()
    };
    let expected = Instant::now() + config.request_timeout;
    let router = Router::new()
        .route(
            "/",
            get(move |deadline: RequestDeadline| async move {
                assert_eq!(deadline.instant(), expected);
                assert_eq!(deadline.remaining(), Duration::from_millis(900));
                tokio::time::sleep(Duration::from_millis(200)).await;
                assert_eq!(deadline.remaining(), Duration::from_millis(700));
                "done"
            }),
        )
        .layer(middleware::from_fn(
            |request: Request<Body>, next: Next| async move {
                let deadline = *request.extensions().get::<RequestDeadline>().unwrap();
                assert_eq!(deadline.remaining(), Duration::from_secs(1));
                tokio::time::sleep(Duration::from_millis(100)).await;
                next.run(request).await
            },
        ));
    let state = HttpState::new(router, shared, &config);
    let response = state
        .admit(
            Request::new(Body::empty()),
            &RequestId("test".into()),
            &OutcomeSlot::default(),
        )
        .await;
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(
        response.extensions().get::<TransferDeadline>().unwrap().0,
        expected
    );
    assert_eq!(
        response.into_body().collect().await.unwrap().to_bytes(),
        "done"
    );
}