servlet 1.2.0

A small application runtime with an explicit operational contract
Documentation
//! Shared synchronization and bounded socket helpers.

use std::{
    net::{Ipv4Addr, SocketAddr},
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::Duration,
};

use servlet::{
    AppConfig, Error, Failure,
    io::{AsyncReadExt, AsyncWriteExt},
    net::TcpStream,
    time::timeout,
};

pub(super) fn config() -> AppConfig {
    let mut config = AppConfig::default();
    config.bind = SocketAddr::from((Ipv4Addr::LOCALHOST, 0));
    config.startup_timeout = Duration::from_secs(2);
    config.shutdown_timeout = Duration::from_millis(400);
    config.cleanup_reserve = Duration::from_millis(200);
    config.request_timeout = Duration::from_secs(2);
    config
}

pub(super) async fn request(address: SocketAddr, request: &str) -> String {
    timeout(Duration::from_secs(4), async {
        let mut stream = TcpStream::connect(address).await.unwrap();
        stream.write_all(request.as_bytes()).await.unwrap();
        let mut response = Vec::new();
        stream.read_to_end(&mut response).await.unwrap();
        String::from_utf8(response).unwrap()
    })
    .await
    .expect("HTTP exchange must terminate")
}

pub(super) async fn get(address: SocketAddr, path: &str) -> String {
    request(
        address,
        &format!("GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"),
    )
    .await
}

pub(super) fn failures(error: Error) -> Vec<Failure> {
    match error {
        Error::Lifecycle(failures) => failures,
        error => panic!("expected lifecycle failure, got {error}"),
    }
}

pub(super) struct OnDrop(pub Arc<AtomicBool>);

impl Drop for OnDrop {
    fn drop(&mut self) {
        self.0.store(true, Ordering::SeqCst);
    }
}