capy-framework 0.10.0

An opinionated full-stack Rust web framework with strong conventions and sensible defaults.
Documentation
//! Direct application-binary lifecycle evidence. Unix signal tests run on Linux/macOS.
#![cfg(unix)]

use capy_framework::{self as capy, prelude::*};
use std::{
    fs,
    io::{Read, Write},
    net::{TcpListener, TcpStream},
    process::{Child, Command, Stdio},
    thread,
    time::{Duration, Instant},
};

#[test]
fn server_child() {
    let Ok(root) = std::env::var("CAPY_LIFECYCLE_ROOT") else {
        return;
    };
    let runtime = tokio::runtime::Runtime::new().unwrap();
    runtime.block_on(async {
        let mut config = AppConfig::default();
        config.database.url = "sqlite::memory:".into();
        config.server.port = Some(
            std::env::var("CAPY_LIFECYCLE_PORT")
                .unwrap()
                .parse()
                .unwrap(),
        );
        config.server.shutdown_timeout_seconds = 1;
        config.http.request_timeout_seconds = 0;
        let routes = Routes::new().get("/health", capy::health).get(
            "/work/{mode}",
            move |Path(mode): Path<String>| {
                let root = root.clone();
                async move {
                    fs::write(std::path::Path::new(&root).join("started"), "started").unwrap();
                    if mode == "stalled" {
                        std::future::pending::<()>().await;
                    }
                    tokio::time::sleep(Duration::from_millis(250)).await;
                    "completed"
                }
            },
        );
        App::new()
            .config(config)
            .routes(routes)
            .run_command("serve")
            .await
            .unwrap();
    });
}

struct OwnedChild(Child);
impl Drop for OwnedChild {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

fn request(port: u16, path: &str) -> TcpStream {
    let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
    stream
        .set_read_timeout(Some(Duration::from_secs(5)))
        .unwrap();
    write!(
        stream,
        "GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"
    )
    .unwrap();
    stream
}

#[test]
fn sigint_and_sigterm_drain_successful_work_and_bound_stalled_work() {
    for signal in ["-INT", "-TERM"] {
        for mode in ["idle", "finishing", "stalled"] {
            let root = tempfile::tempdir().unwrap();
            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
            let port = listener.local_addr().unwrap().port();
            drop(listener);
            let output = fs::File::create(root.path().join("server.log")).unwrap();
            let mut child = OwnedChild(
                Command::new(std::env::current_exe().unwrap())
                    .args(["--exact", "server_child", "--nocapture"])
                    .env("CAPY_LIFECYCLE_ROOT", root.path())
                    .env("CAPY_LIFECYCLE_PORT", port.to_string())
                    .env("RUST_LOG", "info")
                    .stdout(Stdio::from(output.try_clone().unwrap()))
                    .stderr(Stdio::from(output))
                    .spawn()
                    .unwrap(),
            );
            let ready_deadline = Instant::now() + Duration::from_secs(10);
            loop {
                assert!(Instant::now() < ready_deadline, "server failed to start");
                assert!(
                    child.0.try_wait().unwrap().is_none(),
                    "child exited before ready"
                );
                if TcpStream::connect(("127.0.0.1", port)).is_ok() {
                    break;
                }
                thread::sleep(Duration::from_millis(10));
            }
            let mut stream = if mode == "idle" {
                let mut health = request(port, "/health");
                let mut body = String::new();
                health.read_to_string(&mut body).unwrap();
                assert!(body.contains("200 OK"));
                None
            } else {
                Some(request(port, &format!("/work/{mode}")))
            };
            if mode != "idle" {
                while !root.path().join("started").is_file() {
                    assert!(Instant::now() < ready_deadline);
                    thread::sleep(Duration::from_millis(10));
                }
            }
            let started = Instant::now();
            assert!(Command::new("kill")
                .args([signal, &child.0.id().to_string()])
                .status()
                .unwrap()
                .success());
            let status = loop {
                if let Some(status) = child.0.try_wait().unwrap() {
                    break status;
                }
                assert!(
                    started.elapsed() < Duration::from_secs(4),
                    "{signal} {mode}: shutdown exceeded bound"
                );
                thread::sleep(Duration::from_millis(10));
            };
            let log = fs::read_to_string(root.path().join("server.log")).unwrap();
            assert!(status.success(), "{signal} {mode}: {log}");
            for message in [
                "shutdown requested",
                "waiting for active requests",
                "server stopped",
            ] {
                assert!(log.contains(message), "{signal} {mode}: {log}");
            }
            assert_eq!(
                log.contains("shutdown deadline reached"),
                mode == "stalled",
                "{log}"
            );
            if mode == "stalled" {
                assert!(started.elapsed() >= Duration::from_millis(900));
            }
            if let Some(stream) = &mut stream {
                let mut body = String::new();
                let _ = stream.read_to_string(&mut body);
                if mode == "finishing" {
                    assert!(
                        body.contains("200 OK") && body.ends_with("completed"),
                        "{body}"
                    );
                } else {
                    assert!(!body.contains("200 OK"));
                }
            }
            assert!(TcpStream::connect(("127.0.0.1", port)).is_err());
        }
    }
}