servlet 1.2.0

A small application runtime with an explicit operational contract
Documentation
//! Dedicated route budgets share the application's listener and shutdown.

use super::support::{config, failures, get};
use http_body::{Body as HttpBody, Frame};
use servlet::{
    App, FailureKind,
    ecosystem::tokio,
    io::{AsyncReadExt, AsyncWriteExt},
    net::TcpStream,
    sync::Notify,
    time::timeout,
    web::{Body, Bytes, RequestDeadline, Router, StreamPolicy, routing},
};
use std::{
    net::SocketAddr,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
    time::Duration,
};

const POLICY: StreamPolicy = StreamPolicy {
    max_in_flight: 1,
    max_duration: Duration::from_secs(20),
    idle_timeout: Duration::from_secs(10),
};

#[tokio::test]
async fn streaming_capacity_is_isolated_at_the_subtree_boundary() {
    let mut settings = config();
    settings.max_in_flight = 1;
    settings.max_connections = 3;
    let dropped = Arc::new(Notify::new());
    let app = App::new("stream-admission")
        .config(settings)
        .streaming_routes("/stream", POLICY, routes(dropped.clone()))
        .streaming_routes(
            "/events",
            POLICY,
            Router::new().route("/", routing::get(|| async { "other group" })),
        )
        .get("/streaming", || async { "ordinary" });
    let running = app.start().await.unwrap();
    let address = running.local_addr().unwrap();

    let peer = open_stream(address).await;
    let overloaded = get(address, "/stream/probe").await;
    assert!(overloaded.starts_with("HTTP/1.1 503"), "{overloaded}");
    let normal = get(address, "/streaming?path=/stream/probe").await;
    assert!(normal.starts_with("HTTP/1.1 200"), "{normal}");
    assert!(normal.ends_with("ordinary"));
    assert!(get(address, "/events").await.ends_with("other group"));

    drop(peer);
    timeout(Duration::from_secs(1), dropped.notified())
        .await
        .unwrap();
    let recovered = get(address, "/stream/probe").await;
    assert!(recovered.starts_with("HTTP/1.1 200"), "{recovered}");
    assert!(recovered.ends_with("available"));
    running.handle().shutdown();
    running.wait().await.unwrap();
}

#[tokio::test]
async fn a_stream_still_uses_the_process_connection_cap() {
    let mut settings = config();
    settings.max_connections = 1;
    let running = App::new("stream-connection-cap")
        .config(settings)
        .streaming_routes("/stream", POLICY, routes(Arc::new(Notify::new())))
        .get("/", || async { "ordinary" })
        .start()
        .await
        .unwrap();
    let address = running.local_addr().unwrap();
    let first = open_stream(address).await;
    let mut rejected = TcpStream::connect(address).await.unwrap();
    let _ = rejected
        .write_all(b"GET / HTTP/1.1\r\nHost: test\r\n\r\n")
        .await;
    let mut bytes = Vec::new();
    let _ = timeout(Duration::from_secs(1), rejected.read_to_end(&mut bytes))
        .await
        .unwrap();
    assert!(bytes.is_empty());
    drop(first);
    running.handle().shutdown();
    running.wait().await.unwrap();
}

#[tokio::test]
async fn open_streams_drain_within_the_normal_shutdown_budget() {
    let dropped = Arc::new(Notify::new());
    let running = App::new("stream-drain")
        .config(config())
        .streaming_routes("/stream", POLICY, routes(dropped.clone()))
        .start()
        .await
        .unwrap();
    let _peer = open_stream(running.local_addr().unwrap()).await;
    running.handle().shutdown();

    let error = timeout(Duration::from_secs(2), running.wait())
        .await
        .unwrap()
        .expect_err("the unfinished stream must count against the drain budget");
    assert!(
        failures(error)
            .iter()
            .any(|item| item.kind == FailureKind::DrainTimeout)
    );
    timeout(Duration::from_millis(20), dropped.notified())
        .await
        .expect("aborting the connection drops the response body");
}

#[tokio::test]
async fn an_idle_response_body_uses_the_stream_groups_idle_cutoff() {
    let mut settings = config();
    settings.body_idle_timeout = Duration::from_secs(5);
    let policy = StreamPolicy {
        idle_timeout: Duration::from_millis(75),
        ..POLICY
    };
    let dropped = Arc::new(Notify::new());
    let running = App::new("stream-body-idle")
        .config(settings)
        .streaming_routes("/stream", policy, routes(dropped.clone()))
        .start()
        .await
        .unwrap();
    let _peer = open_stream(running.local_addr().unwrap()).await;
    timeout(Duration::from_secs(1), dropped.notified())
        .await
        .expect("the response body must use the group's idle timeout");
    running.handle().shutdown();
    running.wait().await.unwrap();
}

#[tokio::test]
async fn invalid_streaming_groups_fail_startup() {
    let zero = StreamPolicy {
        max_in_flight: 0,
        ..POLICY
    };
    for (prefix, policy) in [("/", POLICY), ("/{dynamic}", POLICY), ("/stream", zero)] {
        let result = App::new("invalid-stream")
            .config(config())
            .streaming_routes(prefix, policy, Router::new())
            .start()
            .await;
        assert!(result.is_err(), "invalid stream policy allowed startup");
    }
    let overlap = App::new("overlapping-streams")
        .config(config())
        .streaming_routes("/stream", POLICY, Router::new())
        .streaming_routes("/stream/inner", POLICY, Router::new())
        .start()
        .await;
    assert!(overlap.is_err());
}

fn routes(dropped: Arc<Notify>) -> Router {
    Router::new()
        .route(
            "/",
            routing::get(move |deadline: RequestDeadline| {
                let dropped = dropped.clone();
                async move {
                    assert!(deadline.remaining() > Duration::from_secs(2));
                    Body::new(Parked {
                        dropped,
                        sent: false,
                    })
                }
            }),
        )
        .route("/probe", routing::get(|| async { "available" }))
}

async fn open_stream(address: SocketAddr) -> TcpStream {
    timeout(Duration::from_secs(1), async {
        let mut peer = TcpStream::connect(address).await.unwrap();
        peer.write_all(b"GET /stream HTTP/1.1\r\nHost: test\r\n\r\n")
            .await
            .unwrap();
        let mut headers = Vec::new();
        while !headers.ends_with(b"\r\n\r\n") {
            headers.push(peer.read_u8().await.unwrap());
            assert!(headers.len() < 1024);
        }
        assert!(headers.starts_with(b"HTTP/1.1 200"));
        peer
    })
    .await
    .unwrap()
}

struct Parked {
    dropped: Arc<Notify>,
    sent: bool,
}

impl HttpBody for Parked {
    type Data = Bytes;
    type Error = std::convert::Infallible;

    fn poll_frame(
        mut self: Pin<&mut Self>,
        _: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Bytes>, Self::Error>>> {
        if self.sent {
            Poll::Pending
        } else {
            self.sent = true;
            Poll::Ready(Some(Ok(Frame::data(Bytes::from_static(b"opened")))))
        }
    }
}

impl Drop for Parked {
    fn drop(&mut self) {
        self.dropped.notify_one();
    }
}