servlet 1.2.0

A small application runtime with an explicit operational contract
Documentation
//! Owned loopback servers and managed-client fixtures with bounded joins.
use servlet::{
    App, AppConfig, Running,
    client::{Client, ClientConfig},
    ecosystem::tokio,
    io::{AsyncReadExt, AsyncWriteExt},
    net::{TcpListener, TcpStream},
    sync::oneshot,
    time::{Instant, timeout},
};
use std::{future::Future, net::SocketAddr, time::Duration};
pub(super) fn settings() -> AppConfig {
    let mut config = AppConfig::default();
    config.bind = "127.0.0.1:0".parse().unwrap();
    config.startup_timeout = Duration::from_secs(2);
    config.shutdown_timeout = Duration::from_millis(400);
    config.cleanup_reserve = Duration::from_millis(200);
    config
}
pub(super) fn deadline() -> Instant {
    Instant::now() + Duration::from_secs(3)
}
pub(super) async fn start(config: ClientConfig) -> (Running, Client) {
    let (send, receive) = oneshot::channel();
    let running = App::new("http-client")
        .config(settings())
        .setup(move |mut ctx| async move {
            let client = ctx.http_client("downstream", config)?;
            let _ = send.send(client);
            Ok(())
        })
        .start()
        .await
        .unwrap();
    (running, receive.await.unwrap())
}
pub(super) async fn stop(running: Running) {
    running.handle().shutdown();
    running.wait().await.unwrap();
}
pub(super) struct Server {
    pub address: SocketAddr,
    task: tokio::task::JoinHandle<()>,
}
impl Server {
    pub(super) async fn listen<Fut>(scenario: impl FnOnce(TcpListener) -> Fut) -> Self
    where
        Fut: Future<Output = ()> + Send + 'static,
    {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let task = tokio::spawn(scenario(listener));
        Self { address, task }
    }
    pub(super) fn origin(&self) -> String {
        format!("http://{}", self.address)
    }
    pub(super) async fn finish(mut self) {
        timeout(Duration::from_secs(5), &mut self.task)
            .await
            .unwrap()
            .unwrap();
    }
}
impl Drop for Server {
    fn drop(&mut self) {
        self.task.abort();
    }
}
pub(super) async fn server<F, Fut>(count: usize, handle: F) -> Server
where
    F: Fn(TcpStream) -> Fut + Send + 'static,
    Fut: Future<Output = ()> + Send,
{
    Server::listen(move |listener| async move {
        for _ in 0..count {
            let (socket, _) = listener.accept().await.unwrap();
            handle(socket).await;
        }
        assert!(
            timeout(Duration::from_millis(80), listener.accept())
                .await
                .is_err(),
            "unexpected retry/connection"
        );
    })
    .await
}
pub(super) async fn request(socket: &mut TcpStream) -> String {
    timeout(Duration::from_secs(3), async {
        let mut bytes = Vec::new();
        while !bytes.ends_with(b"\r\n\r\n") {
            bytes.push(socket.read_u8().await.unwrap());
            assert!(bytes.len() <= 20000);
        }
        String::from_utf8(bytes).unwrap()
    })
    .await
    .unwrap()
}
pub(super) async fn reply(socket: &mut TcpStream, body: &str) {
    socket
        .write_all(
            format!(
                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                body.len()
            )
            .as_bytes(),
        )
        .await
        .unwrap();
}