servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! A selected component owns startup, with independent application and admin listeners.

use super::support::{config, get};
use servlet::{
    App, Components, Role,
    ecosystem::tokio,
    health::CheckPolicy,
    sync::{Notify, oneshot},
    time::{sleep, timeout},
    web::State,
};
use std::{
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::Duration,
};

#[tokio::test]
async fn selected_component_starts_only_the_requested_role() {
    for (role, has_api, has_workers) in [
        (Role::All, true, true),
        (Role::Api, true, false),
        (Role::Worker, false, true),
    ] {
        let mut settings = config();
        settings.admin_bind = Some(settings.bind);
        let worker_started = Arc::new(AtomicBool::new(false));
        let started = worker_started.clone();
        let service_started = Arc::new(AtomicBool::new(false));
        let started_service = service_started.clone();
        let resource_closed = Arc::new(AtomicBool::new(false));
        let closed = resource_closed.clone();
        let app = Components::new()
            .component("mcp", |_| {
                panic!("an unselected component must not be assembled")
            })
            .component("sync", move |selected_role| {
                assert_eq!(selected_role, role);
                App::new("component-test")
                    .config(settings)
                    .get(
                        "/application",
                        |State(message): State<&'static str>| async move { message },
                    )
                    .service("inventory", |ctx| async move {
                        started_service.store(true, Ordering::SeqCst);
                        ctx.ready();
                        ctx.shutdown().cancelled().await;
                        Ok(())
                    })
                    .worker("replicate", |ctx| async move {
                        started.store(true, Ordering::SeqCst);
                        ctx.ready();
                        ctx.shutdown().cancelled().await;
                        Ok(())
                    })
                    .setup(move |mut ctx| async move {
                        assert_eq!(ctx.component_name(), Some("sync"));
                        assert_eq!(ctx.role(), role);
                        ctx.cleanup("selected-resource", move || async move {
                            closed.store(true, Ordering::SeqCst);
                            Ok(())
                        })?;
                        Ok("selected component")
                    })
            })
            .select("sync", role)
            .unwrap();

        let running = app.start().await.unwrap();
        let handle = running.handle();
        let admin = handle.admin_addr().unwrap();
        assert!(handle.is_ready());
        assert!(service_started.load(Ordering::SeqCst));
        assert_eq!(worker_started.load(Ordering::SeqCst), has_workers);
        assert_eq!(running.local_addr().is_some(), has_api);
        if let Some(address) = running.local_addr() {
            assert_ne!(address, admin);
            assert!(
                get(address, "/application")
                    .await
                    .ends_with("selected component")
            );
        }
        assert!(get(admin, "/live").await.starts_with("HTTP/1.1 200"));
        assert!(get(admin, "/ready").await.starts_with("HTTP/1.1 200"));
        assert!(
            get(admin, "/metrics")
                .await
                .contains("servlet_exchanges_active")
        );
        assert!(get(admin, "/application").await.starts_with("HTTP/1.1 404"));

        handle.shutdown();
        running.wait().await.unwrap();
        assert!(resource_closed.load(Ordering::SeqCst));
    }
}

#[tokio::test]
async fn api_role_keeps_builder_and_setup_dependency_checks() {
    for pending in ["builder", "setup"] {
        let dependency = |name| {
            let healthy = Arc::new(AtomicBool::new(name != pending));
            let checked = Arc::new(Notify::new());
            let health = healthy.clone();
            let attempt = checked.clone();
            let check = move || {
                let healthy = health.load(Ordering::SeqCst);
                attempt.notify_one();
                async move {
                    if healthy {
                        Ok(())
                    } else {
                        Err("dependency unavailable".into())
                    }
                }
            };
            (healthy, checked, check)
        };
        let (builder_healthy, builder_checked, builder_check) = dependency("builder");
        let (setup_healthy, setup_checked, setup_check) = dependency("setup");
        let policy = CheckPolicy {
            interval: Duration::from_millis(10),
            timeout: Duration::from_millis(100),
        };
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let admin = listener.local_addr().unwrap();
        drop(listener);
        let mut settings = config();
        settings.admin_bind = Some(admin);
        let starting = tokio::spawn(
            App::new("standalone-api")
                .config(settings)
                .with_role(Role::Api)
                .get("/application", async || "running")
                .worker("inactive", |_| async {
                    panic!("API role must skip application workers")
                })
                .readiness("builder", policy, builder_check)
                .setup(move |mut ctx| async move {
                    ctx.readiness("setup", policy, setup_check)?;
                    Ok(())
                })
                .start(),
        );

        timeout(Duration::from_secs(1), async {
            tokio::join!(builder_checked.notified(), setup_checked.notified());
        })
        .await
        .expect("both dependency checks must run before startup completes");
        assert!(get(admin, "/ready").await.starts_with("HTTP/1.1 503"));
        assert!(!starting.is_finished(), "startup must wait for {pending}");

        builder_healthy.store(true, Ordering::SeqCst);
        setup_healthy.store(true, Ordering::SeqCst);
        let running = starting.await.unwrap().unwrap();
        let handle = running.handle();
        assert!(get(admin, "/ready").await.starts_with("HTTP/1.1 200"));
        assert!(
            get(running.local_addr().unwrap(), "/application")
                .await
                .ends_with("running")
        );

        for (name, healthy) in [("builder", builder_healthy), ("setup", setup_healthy)] {
            for (desired, status) in [(false, "HTTP/1.1 503"), (true, "HTTP/1.1 200")] {
                healthy.store(desired, Ordering::SeqCst);
                timeout(Duration::from_secs(1), async {
                    while handle.is_ready() != desired {
                        sleep(Duration::from_millis(2)).await;
                    }
                })
                .await
                .unwrap_or_else(|_| panic!("readiness must track the {name} dependency"));
                assert!(get(admin, "/ready").await.starts_with(status));
                assert!(get(admin, "/live").await.starts_with("HTTP/1.1 200"));
            }
        }

        handle.shutdown();
        running.wait().await.unwrap();
    }
}

#[tokio::test]
async fn direct_worker_role_serves_admin_probes_on_the_inactive_application_port() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    drop(listener);

    let mut settings = config();
    settings.bind = address;
    settings.admin_bind = Some(address);
    let (worker_started, started) = oneshot::channel();
    let (allow_ready, ready) = oneshot::channel();
    let starting = tokio::spawn(
        App::new("standalone-worker")
            .config(settings)
            .with_role(Role::Worker)
            .get("/application", async || "inactive")
            .setup(|ctx| async move {
                assert_eq!(ctx.role(), Role::Worker);
                assert_eq!(ctx.component_name(), None);
                Ok(())
            })
            .worker("gated", |ctx| async move {
                worker_started.send(()).unwrap();
                ready.await.unwrap();
                ctx.ready();
                ctx.shutdown().cancelled().await;
                Ok(())
            })
            .start(),
    );

    started.await.unwrap();
    assert!(get(address, "/live").await.starts_with("HTTP/1.1 200"));
    assert!(get(address, "/ready").await.starts_with("HTTP/1.1 503"));
    allow_ready.send(()).unwrap();
    let running = starting.await.unwrap().unwrap();
    let handle = running.handle();
    assert_eq!(running.local_addr(), None);
    assert_eq!(handle.admin_addr(), Some(address));
    assert!(get(address, "/ready").await.starts_with("HTTP/1.1 200"));
    handle.shutdown();
    running.wait().await.unwrap();
}

#[test]
fn invalid_component_selections_do_not_call_factories() {
    let factory = |_| -> App { panic!("invalid selection must never assemble a component") };

    assert!(
        Components::new()
            .component("api", factory)
            .select("missing", Role::All)
            .is_err()
    );
    assert!(
        Components::new()
            .component("api", factory)
            .component("api", factory)
            .select("api", Role::All)
            .is_err()
    );
    assert!(
        Components::new()
            .component(" ", factory)
            .component("api", factory)
            .select("api", Role::All)
            .is_err()
    );
}