servlet 1.2.0

A small application runtime with an explicit operational contract
Documentation
//! A one-byte transport cannot accidentally buffer a complete problem response.
use super::drive;
use crate::{AppConfig, lifecycle::Shared, web::HttpState};
use axum::{
    Router,
    extract::Request,
    routing::{get, post},
};
use http_body_util::BodyExt;
use std::{sync::Arc, time::Duration};
use tokio::{
    io::{AsyncReadExt, AsyncWriteExt, duplex},
    sync::Notify,
    time::{Instant, advance, timeout},
};

#[tokio::test(start_paused = true)]
async fn backpressured_normal_size_and_timeout_responses_obey_selected_deadline() {
    for (path, length, cutoff_ms, terminal) in [
        ("/", 0, 1000, "completed"),
        ("/", 1025, 1000, "failed"),
        ("/hang", 0, 1250, "timed_out"),
    ] {
        let shared = Shared::new("backpressure".into());
        shared.begin_running();
        let config = AppConfig {
            request_timeout: Duration::from_secs(1),
            body_idle_timeout: Duration::from_secs(10),
            request_body_limit: 1024,
            max_in_flight: 1,
            ..AppConfig::default()
        };
        let router = Router::new()
            .route("/", get(|| async { "hello" }))
            .route("/hang", get(std::future::pending::<&'static str>));
        let state = Arc::new(HttpState::new(router, shared.clone(), &config));
        let (mut client, server) = duplex(1);
        let connection = tokio::spawn(drive(server, "127.0.0.1:1".parse().unwrap(), state));
        let started = Instant::now();
        client.write_all(format!("GET {path} HTTP/1.1\r\nHost: test\r\nContent-Length: {length}\r\nConnection: close\r\n\r\n").as_bytes()).await.unwrap();
        // Observing exactly one byte ensures dispatch happened and the tiny
        // outbound buffer is blocked. No remaining bytes are read until cutoff.
        let mut byte = [0];
        client.read_exact(&mut byte).await.unwrap();
        assert_eq!(byte[0], b'H');
        let cutoff = started + Duration::from_millis(cutoff_ms);
        advance(cutoff - Instant::now() - Duration::from_millis(1)).await;
        tokio::task::yield_now().await;
        assert!(
            !connection.is_finished(),
            "must retain transport until the selected cutoff"
        );
        advance(Duration::from_millis(1)).await;
        connection.await.unwrap().unwrap();
        assert_eq!(Instant::now(), cutoff);
        let metrics = shared.metrics.render();
        assert!(
            metrics.contains("servlet_exchanges_active 0\n"),
            "{metrics}"
        );
        assert!(
            metrics.contains("servlet_exchanges_finished_total 1\n"),
            "{metrics}"
        );
        assert!(
            metrics.contains(&format!(
                "servlet_exchanges_outcomes_total{{outcome=\"{terminal}\"}} 1\n"
            )),
            "{metrics}"
        );
        assert!(
            metrics.contains("servlet_transport_errors_total 1\n"),
            "{metrics}"
        );
    }
}

#[tokio::test(start_paused = true)]
async fn buffered_response_timeout_does_not_mark_a_later_handler_timed_out() {
    let shared = Shared::new("pipelined".into());
    shared.begin_running();
    let config = AppConfig {
        request_timeout: Duration::from_millis(250),
        body_idle_timeout: Duration::from_secs(10),
        ..AppConfig::default()
    };
    let entered = Arc::new(Notify::new());
    let next = entered.clone();
    let router = Router::new()
        .route(
            "/first",
            post(|request: Request| async move {
                tokio::spawn(async move {
                    request.into_body().collect().await.unwrap();
                });
                "first response"
            }),
        )
        .route(
            "/second",
            get(move || async move {
                next.notify_one();
                std::future::pending::<&'static str>().await
            }),
        );
    let state = Arc::new(HttpState::new(router, shared.clone(), &config));
    let (mut client, server) = duplex(1);
    let connection = tokio::spawn(drive(server, "127.0.0.1:1".parse().unwrap(), state));
    let started = Instant::now();
    client
        .write_all(b"POST /first HTTP/1.1\r\nHost: test\r\nContent-Length: 1\r\n\r\n")
        .await
        .unwrap();
    let mut byte = [0];
    client.read_exact(&mut byte).await.unwrap();
    assert_eq!(byte[0], b'H');

    // Completing the POST body lets Hyper dispatch the next request while
    // the first response still has buffered bytes waiting for the socket.
    advance(Duration::from_millis(100)).await;
    client
        .write_all(b"xGET /second HTTP/1.1\r\nHost: test\r\n\r\n")
        .await
        .unwrap();
    timeout(Duration::from_millis(100), entered.notified())
        .await
        .expect("second handler must start while the first response is blocked");
    advance(Duration::from_millis(150)).await;
    connection.await.unwrap().unwrap();
    assert_eq!(Instant::now(), started + config.request_timeout);

    let metrics = shared.metrics.render();
    for (outcome, count) in [("completed", 1), ("cancelled", 1), ("timed_out", 0)] {
        assert!(
            metrics.contains(&format!(
                "servlet_exchanges_outcomes_total{{outcome=\"{outcome}\"}} {count}\n"
            )),
            "{metrics}"
        );
    }
    assert!(
        metrics.contains("servlet_transport_errors_total 1\n"),
        "{metrics}"
    );
}

#[tokio::test(start_paused = true)]
async fn streaming_socket_backpressure_uses_its_own_absolute_and_idle_cutoffs() {
    use crate::web::{StreamPolicy, StreamingGroup};

    let config = AppConfig {
        request_timeout: Duration::from_secs(1),
        body_idle_timeout: Duration::from_secs(10),
        ..AppConfig::default()
    };
    for (path, lifetime, idle, expected) in [
        ("/normal", 5, 8, 1),
        ("/stream", 5, 8, 5),
        ("/stream", 9, 3, 3),
    ] {
        let shared = Shared::new("stream-backpressure".into());
        shared.begin_running();
        let policy = StreamPolicy {
            max_in_flight: 1,
            max_duration: Duration::from_secs(lifetime),
            idle_timeout: Duration::from_secs(idle),
        };
        let router = Router::new()
            .route("/stream", get(|| async { "stream" }))
            .route("/normal", get(|| async { "normal" }));
        let state = Arc::new(
            HttpState::new(router, shared.clone(), &config)
                .with_streaming(vec![StreamingGroup::new("/stream", policy).unwrap()]),
        );
        let (mut client, server) = duplex(1);
        let connection = tokio::spawn(drive(server, "127.0.0.1:1".parse().unwrap(), state));
        let began = Instant::now();
        client
            .write_all(format!("GET {path} HTTP/1.1\r\nHost: test\r\n\r\n").as_bytes())
            .await
            .unwrap();
        assert_eq!(client.read_u8().await.unwrap(), b'H');
        tokio::task::yield_now().await;
        let cutoff = began + Duration::from_secs(expected);
        advance(cutoff - Instant::now() - Duration::from_millis(1)).await;
        tokio::task::yield_now().await;
        assert!(
            !connection.is_finished(),
            "{path} stopped before its cutoff"
        );
        advance(Duration::from_millis(1)).await;
        connection.await.unwrap().unwrap();
        assert_eq!(
            Instant::now(),
            cutoff,
            "{path} used the wrong transfer budget"
        );
    }
}