servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! Deferred dependency checks share startup, cached health, and rollback ownership.

use super::support::{config, failures, get};
use servlet::{
    App, FailureKind,
    ecosystem::tokio,
    health::CheckPolicy,
    time::{Instant, sleep, timeout},
};
use std::{
    sync::{
        Arc,
        atomic::{AtomicBool, AtomicUsize, Ordering},
    },
    time::Duration,
};

#[tokio::test]
async fn managed_checks_withdraw_and_restore_cached_readiness() {
    let healthy = Arc::new(AtomicBool::new(true));
    let calls = Arc::new(AtomicUsize::new(0));
    let input = healthy.clone();
    let attempts = calls.clone();
    let mut settings = config();
    settings.admin_bind = Some(settings.bind);
    let running = App::new("managed-health")
        .config(settings)
        .setup(move |mut ctx| async move {
            ctx.readiness(
                "database",
                CheckPolicy {
                    interval: Duration::from_millis(20),
                    timeout: Duration::from_millis(10),
                },
                move || {
                    attempts.fetch_add(1, Ordering::SeqCst);
                    let healthy = input.load(Ordering::SeqCst);
                    async move {
                        if healthy {
                            Ok(())
                        } else {
                            Err("unavailable".into())
                        }
                    }
                },
            )?;
            Ok(())
        })
        .start()
        .await
        .unwrap();
    let handle = running.handle();
    let admin = handle.admin_addr().unwrap();
    assert!(handle.is_ready());
    for desired in [false, true] {
        healthy.store(desired, Ordering::SeqCst);
        timeout(Duration::from_secs(1), async {
            while handle.is_ready() != desired {
                sleep(Duration::from_millis(2)).await;
            }
        })
        .await
        .unwrap();
        let status = if desired { 200 } else { 503 };
        assert!(
            get(admin, "/ready")
                .await
                .starts_with(&format!("HTTP/1.1 {status}"))
        );
        assert!(get(admin, "/live").await.starts_with("HTTP/1.1 200"));
    }
    assert!(calls.load(Ordering::SeqCst) >= 3);
    handle.shutdown();
    running.wait().await.unwrap();
}

#[tokio::test(start_paused = true)]
async fn startup_accepts_first_success_while_cached_readiness_stays_unhealthy() {
    let early_attempts = Arc::new(AtomicUsize::new(0));
    let observe_early = early_attempts.clone();
    let mut settings = config();
    settings.admin_bind = Some(settings.bind);
    let running = App::new("staggered-readiness")
        .config(settings)
        .readiness(
            "early",
            CheckPolicy {
                interval: Duration::from_millis(10),
                timeout: Duration::from_millis(100),
            },
            move || {
                let healthy = observe_early.fetch_add(1, Ordering::SeqCst) == 0;
                async move {
                    if healthy {
                        Ok(())
                    } else {
                        Err("early check failed".into())
                    }
                }
            },
        )
        .readiness(
            "late",
            CheckPolicy {
                timeout: Duration::from_millis(100),
                ..CheckPolicy::default()
            },
            || async {
                sleep(Duration::from_millis(30)).await;
                Ok(())
            },
        )
        .get("/", || async { "running" })
        .start()
        .await
        .unwrap();

    let handle = running.handle();
    assert!(early_attempts.load(Ordering::SeqCst) >= 2);
    assert!(!handle.is_ready());
    let admin = handle.admin_addr().unwrap();
    assert!(get(admin, "/ready").await.starts_with("HTTP/1.1 503"));
    assert!(get(admin, "/live").await.starts_with("HTTP/1.1 200"));
    assert!(
        get(running.local_addr().unwrap(), "/")
            .await
            .starts_with("HTTP/1.1 200")
    );
    handle.shutdown();
    running.wait().await.unwrap();
}

#[tokio::test]
async fn combined_registration_conflicts_roll_back_without_running_checks() {
    for collision in ["check", "worker", "limit"] {
        let closed = Arc::new(AtomicBool::new(false));
        let observe = closed.clone();
        let calls = Arc::new(AtomicUsize::new(0));
        let attempts = calls.clone();
        let mut app = App::new("conflicting-health").config(config());
        if collision == "worker" {
            app = app.worker("readiness:database", |_| async { panic!("must not start") });
        } else {
            app = app.readiness("database", CheckPolicy::default(), || async { Ok(()) });
        }
        let error = app
            .setup(move |mut ctx| async move {
                ctx.cleanup("pool", move || async move {
                    observe.store(true, Ordering::SeqCst);
                    Ok(())
                })?;
                let count = if collision == "limit" { 64 } else { 1 };
                for index in 0..count {
                    let name = if collision == "limit" {
                        format!("additional-{index}")
                    } else {
                        "database".into()
                    };
                    let attempts = attempts.clone();
                    ctx.readiness(name, CheckPolicy::default(), move || {
                        attempts.fetch_add(1, Ordering::SeqCst);
                        async { Ok(()) }
                    })?;
                }
                Ok(())
            })
            .start()
            .await
            .err()
            .unwrap();
        assert!(closed.load(Ordering::SeqCst));
        assert_eq!(calls.load(Ordering::SeqCst), 0);
        assert!(
            failures(error)
                .iter()
                .any(|failure| failure.component == "setup")
        );
    }
}

#[tokio::test(start_paused = true)]
async fn initial_managed_check_uses_remaining_startup_budget_and_rolls_back() {
    let closed = Arc::new(AtomicBool::new(false));
    let observe = closed.clone();
    let began = Instant::now();
    let error = App::new("managed-initial-failure")
        .config(config())
        .setup(move |mut ctx| async move {
            ctx.cleanup("pool", move || async move {
                observe.store(true, Ordering::SeqCst);
                Ok(())
            })?;
            sleep(Duration::from_millis(1500)).await;
            ctx.readiness("database", CheckPolicy::default(), || async {
                std::future::pending().await
            })?;
            Ok(())
        })
        .start()
        .await
        .err()
        .unwrap();
    assert_eq!(Instant::now() - began, config().startup_timeout);
    assert!(closed.load(Ordering::SeqCst));
    assert!(
        failures(error)
            .iter()
            .any(|failure| failure.component == "readiness:database"
                && failure.kind == FailureKind::StartupTimeout)
    );
}