servlet 1.0.0

A small application runtime with an explicit operational contract
Documentation
//! A later keep-alive exchange gets its own handler and transfer budget.
use super::support::config;
use servlet::{
    App,
    ecosystem::tokio,
    io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
    net::TcpStream,
    sync::{Notify, oneshot},
};
use std::{sync::Arc, time::Duration};

#[tokio::test]
async fn next_keepalive_request_outlives_the_previous_deadline() {
    let entered = Arc::new(Notify::new());
    let entered_handler = entered.clone();
    let (release, released) = oneshot::channel();
    let released = Arc::new(std::sync::Mutex::new(Some(released)));
    let mut settings = config();
    settings.request_timeout = Duration::from_millis(300);
    let running = App::new("keep-alive")
        .config(settings)
        .get("/first", || async { "one" })
        .get("/second", move || {
            let entered = entered_handler.clone();
            let released = released.lock().unwrap().take().unwrap();
            async move {
                entered.notify_one();
                released.await.unwrap();
                "two"
            }
        })
        .start()
        .await
        .unwrap();
    let mut stream = BufReader::new(
        TcpStream::connect(running.local_addr().unwrap())
            .await
            .unwrap(),
    );
    stream
        .write_all(b"GET /first HTTP/1.1\r\nHost: localhost\r\n\r\n")
        .await
        .unwrap();
    assert_eq!(response(&mut stream).await, b"one");
    tokio::time::sleep(Duration::from_millis(200)).await;
    stream
        .write_all(b"GET /second HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
        .await
        .unwrap();
    entered.notified().await;
    tokio::time::sleep(Duration::from_millis(150)).await;
    release.send(()).unwrap();
    assert_eq!(response(&mut stream).await, b"two");
    running.handle().shutdown();
    running.wait().await.unwrap();
}

async fn response(stream: &mut BufReader<TcpStream>) -> Vec<u8> {
    tokio::time::timeout(Duration::from_secs(2), async {
        let mut line = String::new();
        stream.read_line(&mut line).await.unwrap();
        assert!(line.starts_with("HTTP/1.1 200"), "{line}");
        let mut length = None;
        loop {
            line.clear();
            stream.read_line(&mut line).await.unwrap();
            if line == "\r\n" {
                break;
            }
            assert!(!line.is_empty());
            if let Some(value) = line.strip_prefix("content-length: ") {
                length = Some(value.trim().parse::<usize>().unwrap());
            }
        }
        let mut body = vec![0; length.unwrap()];
        stream.read_exact(&mut body).await.unwrap();
        body
    })
    .await
    .unwrap()
}