servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! Deterministic stale-snapshot interleaving of connection polling and timeout.
use super::{drive, expired, transfer_timeout};
use crate::{AppConfig, lifecycle::Shared, web::HttpState};
use axum::{
    Router,
    body::{Body, Bytes},
    extract::Request,
    routing::{get, post},
};
use http_body::{Body as HttpBody, Frame};
use http_body_util::BodyExt;
use std::{
    convert::Infallible,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
    time::Duration,
};
use tokio::{
    io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader, DuplexStream, duplex},
    sync::{Notify, watch},
    time::{Instant, advance, timeout},
};

#[tokio::test(start_paused = true)]
async fn polling_a_new_exchange_invalidates_an_already_ready_old_timer() {
    for replacement in [None, Some(Instant::now() + Duration::from_secs(10))] {
        let old = Instant::now();
        let (sender, deadlines) = watch::channel(Some(old));
        let snapshot = *deadlines.borrow();
        // Connection polling starts B but its handler is pending. The old timer
        // also becomes ready in this same poll of select, exactly the reviewed race.
        let connection = std::future::poll_fn(|_| {
            sender.send_replace(replacement);
            Poll::<()>::Pending
        });
        tokio::select! {
            biased;
            () = connection => panic!("handler remains pending"),
            () = transfer_timeout(snapshot) => assert!(expired(*deadlines.borrow()).is_none()),
        }
    }
    assert!(expired(Some(Instant::now())).is_some());
}

#[tokio::test(start_paused = true)]
async fn previous_transfer_deadline_does_not_close_idle_or_partial_headers() {
    for (method, partial_headers) in [("GET", false), ("GET", true), ("HEAD", true)] {
        let shared = Shared::new("keep-alive".into());
        shared.begin_running();
        let config = AppConfig {
            request_timeout: Duration::from_millis(250),
            header_timeout: Duration::from_secs(2),
            ..AppConfig::default()
        };
        let router = Router::new().route("/", get(|| async { "hello" }));
        let state = Arc::new(HttpState::new(router, shared.clone(), &config));
        let (client, server) = duplex(4096);
        let mut client = BufReader::new(client);
        let connection = tokio::spawn(drive(server, "127.0.0.1:1".parse().unwrap(), state));

        client
            .write_all(format!("{method} / HTTP/1.1\r\nHost: test\r\n\r\n").as_bytes())
            .await
            .unwrap();
        read_response(&mut client, method == "GET").await;
        advance(Duration::from_millis(150)).await;
        if partial_headers {
            client.write_all(b"GET / HTTP/1.1\r\nHost: ").await.unwrap();
        }
        advance(Duration::from_millis(200)).await;
        tokio::task::yield_now().await;
        assert!(
            !connection.is_finished(),
            "{method}, partial headers: {partial_headers}"
        );
        assert!(
            shared
                .metrics
                .render()
                .contains("servlet_transport_errors_total 0\n"),
            "a completed response cannot time out on an idle socket",
        );
        let headers = if partial_headers {
            &b"test\r\nConnection: close\r\n\r\n"[..]
        } else {
            &b"GET / HTTP/1.1\r\nHost: test\r\nConnection: close\r\n\r\n"[..]
        };
        client.write_all(headers).await.unwrap();
        read_response(&mut client, true).await;
        connection.await.unwrap().unwrap();
        let metrics = shared.metrics.render();
        assert!(
            metrics.contains("servlet_transport_errors_total 0\n"),
            "{metrics}"
        );
    }
}

#[tokio::test(start_paused = true)]
async fn flushed_response_cannot_shorten_the_next_buffered_response_deadline() {
    let shared = Shared::new("pipelined-deadlines".into());
    shared.begin_running();
    let config = AppConfig {
        request_timeout: Duration::from_millis(250),
        body_idle_timeout: Duration::from_secs(10),
        ..AppConfig::default()
    };
    let second_started = Arc::new(Notify::new());
    let router = Router::new()
        .route(
            "/first",
            post(|request: Request| async move {
                tokio::spawn(async move {
                    request.into_body().collect().await.unwrap();
                });
                "hello"
            }),
        )
        .route(
            "/second",
            get({
                let second_started = second_started.clone();
                move || async move {
                    second_started.notify_one();
                    "x".repeat(4096)
                }
            }),
        );
    let state = Arc::new(HttpState::new(router, shared, &config));
    let (client, server) = duplex(1);
    let mut client = BufReader::new(client);
    let connection = tokio::spawn(drive(server, "127.0.0.1:1".parse().unwrap(), state));

    let first_admitted = Instant::now();
    client
        .write_all(b"POST /first HTTP/1.1\r\nHost: test\r\nContent-Length: 1\r\n\r\n")
        .await
        .unwrap();
    assert_eq!(client.fill_buf().await.unwrap(), b"H");

    // Hyper can dispatch B once A's request body ends, even though A's
    // response is still blocked on the one-byte socket.
    advance(Duration::from_millis(100)).await;
    let second_admitted = Instant::now();
    client
        .write_all(b"xGET /second HTTP/1.1\r\nHost: test\r\n\r\n")
        .await
        .unwrap();
    timeout(Duration::from_millis(1), second_started.notified())
        .await
        .expect("second handler must run while the first output is blocked");
    assert_eq!(Instant::now(), second_admitted);

    // Let B spend part of its absolute budget waiting for A, then consume
    // all of A and observe the start of B before stalling the socket again.
    let flush_wait = Duration::from_millis(50);
    advance(flush_wait).await;
    read_response(&mut client, true).await;
    assert_eq!(client.fill_buf().await.unwrap(), b"H");
    assert_eq!(Instant::now(), second_admitted + flush_wait);

    let first_deadline = first_admitted + config.request_timeout;
    advance(first_deadline - Instant::now() + Duration::from_millis(1)).await;
    tokio::task::yield_now().await;
    assert!(
        !connection.is_finished(),
        "the first deadline cannot close B"
    );

    let second_deadline = second_admitted + config.request_timeout;
    advance(second_deadline - Instant::now()).await;
    connection.await.unwrap().unwrap();
    assert_eq!(Instant::now(), second_deadline);
}

#[tokio::test(start_paused = true)]
async fn pipelined_response_body_idle_begins_when_transfer_starts() {
    for stalled in [false, true] {
        let shared = Shared::new("pipelined-body-idle".into());
        shared.begin_running();
        let config = AppConfig {
            request_timeout: Duration::from_millis(250),
            body_idle_timeout: Duration::from_millis(50),
            ..AppConfig::default()
        };
        let second_ready = Arc::new(Notify::new());
        let router = Router::new()
            .route(
                "/first",
                post(|request: Request| async move {
                    tokio::spawn(async move {
                        request.into_body().collect().await.unwrap();
                    });
                    "hello"
                }),
            )
            .route(
                "/second",
                get({
                    let ready = second_ready.clone();
                    move || async move {
                        ready.notify_one();
                        if stalled {
                            Body::new(PendingBody)
                        } else {
                            Body::from("x".repeat(4096))
                        }
                    }
                }),
            );
        let state = Arc::new(HttpState::new(router, shared.clone(), &config));
        let (client, server) = duplex(1);
        let mut client = BufReader::new(client);
        let connection = tokio::spawn(drive(server, "127.0.0.1:1".parse().unwrap(), state));

        client
            .write_all(b"POST /first HTTP/1.1\r\nHost: test\r\nContent-Length: 1\r\n\r\n")
            .await
            .unwrap();
        assert_eq!(client.fill_buf().await.unwrap(), b"H");
        advance(Duration::from_millis(10)).await;
        let second_admitted = Instant::now();
        client
            .write_all(b"xGET /second HTTP/1.1\r\nHost: test\r\nConnection: close\r\n\r\n")
            .await
            .unwrap();
        timeout(Duration::from_millis(1), second_ready.notified())
            .await
            .expect("second handler must finish while the first output is blocked");
        assert_eq!(Instant::now(), second_admitted);

        // A keeps making socket progress, while B waits longer than its body idle budget.
        let mut prefix = String::new();
        for expected in b"HTTP/" {
            advance(Duration::from_millis(20)).await;
            let byte = client.read_u8().await.unwrap();
            assert_eq!(byte, *expected);
            prefix.push(char::from(byte));
        }
        let second_active = second_admitted + Duration::from_millis(100);
        assert_eq!(Instant::now(), second_active);
        read_response_headers(&mut client, prefix).await;
        let mut first_body = [0; 5];
        client.read_exact(&mut first_body).await.unwrap();
        assert_eq!(&first_body, b"hello");
        read_response_headers(&mut client, String::new()).await;
        assert_eq!(Instant::now(), second_active);

        if stalled {
            advance(config.body_idle_timeout - Duration::from_millis(1)).await;
            tokio::task::yield_now().await;
            assert!(!connection.is_finished(), "B still has idle budget");
            advance(Duration::from_millis(1)).await;
            connection.await.unwrap().unwrap();
            assert_eq!(Instant::now(), second_active + config.body_idle_timeout);
        } else {
            let mut second_body = vec![0; 4096];
            client.read_exact(&mut second_body).await.unwrap();
            assert_eq!(second_body, vec![b'x'; 4096]);
            connection.await.unwrap().unwrap();
            assert_eq!(Instant::now(), second_active);
        }
        let metrics = shared.metrics.render();
        let timeouts = usize::from(stalled);
        assert!(
            metrics.contains(&format!(
                "servlet_exchanges_outcomes_total{{outcome=\"timed_out\"}} {timeouts}\n"
            )),
            "{metrics}"
        );
        assert!(
            metrics.contains(&format!("servlet_transport_errors_total {timeouts}\n")),
            "{metrics}"
        );
    }
}

struct PendingBody;
impl HttpBody for PendingBody {
    type Data = Bytes;
    type Error = Infallible;

    fn poll_frame(
        self: Pin<&mut Self>,
        _: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Bytes>, Self::Error>>> {
        Poll::Pending
    }
}

async fn read_response(client: &mut BufReader<DuplexStream>, expect_body: bool) {
    read_response_headers(client, String::new()).await;
    if expect_body {
        let mut body = [0; 5];
        client.read_exact(&mut body).await.unwrap();
        assert_eq!(&body, b"hello");
    }
}

async fn read_response_headers(client: &mut BufReader<DuplexStream>, mut line: String) {
    client.read_line(&mut line).await.unwrap();
    assert!(line.starts_with("HTTP/1.1 200 "), "{line}");
    loop {
        line.clear();
        assert_ne!(client.read_line(&mut line).await.unwrap(), 0);
        if line == "\r\n" {
            break;
        }
    }
}