servlet 1.2.0

A small application runtime with an explicit operational contract
Documentation
//! Each registered check runs serially in one supervised task.
use crate::{
    Error, Result,
    app::Registration,
    lifecycle::Shared,
    task::{self, Worker},
};
use std::{future::Future, pin::Pin, sync::Arc, time::Duration};

/// Scheduling policy for a cached readiness check.
#[derive(Clone, Copy, Debug)]
pub struct CheckPolicy {
    /// Delay after one attempt completes before the next begins.
    pub interval: Duration,
    /// Maximum time for one attempt, including the first startup attempt.
    pub timeout: Duration,
}
impl Default for CheckPolicy {
    fn default() -> Self {
        Self {
            interval: Duration::from_secs(5),
            timeout: Duration::from_secs(1),
        }
    }
}
pub(crate) const MAX_CHECKS: usize = 64;
const WORKER_NAME_PREFIX: &str = "readiness:";

type CheckFuture = Pin<Box<dyn Future<Output = task::Result> + Send>>;
pub(crate) struct Check {
    pub name: String,
    policy: CheckPolicy,
    run: Box<dyn Fn() -> CheckFuture + Send>,
}
impl Check {
    pub(crate) fn new<F, Fut>(name: String, policy: CheckPolicy, check: F) -> Self
    where
        F: Fn() -> Fut + Send + 'static,
        Fut: Future<Output = task::Result> + Send + 'static,
    {
        Self {
            name,
            policy,
            run: Box::new(move || Box::pin(check())),
        }
    }

    pub(crate) fn validate(&self) -> Result<()> {
        if self.name.trim().is_empty()
            || self.name.len() > 128
            || [self.policy.interval, self.policy.timeout]
                .iter()
                .any(|duration| {
                    duration.is_zero() || std::time::Instant::now().checked_add(*duration).is_none()
                })
        {
            return Err(Error::Registration("readiness checks require nonempty names (up to 128 bytes) and positive representable budgets".into()));
        }
        Ok(())
    }
}
pub(crate) fn prepare(registration: &mut Registration, shared: &Arc<Shared>) -> Result<()> {
    let mut names = shared.health.names();
    if names.len() + registration.checks.len() > MAX_CHECKS {
        return Err(Error::Registration(
            "at most 64 readiness checks are supported".into(),
        ));
    }
    for check in &registration.checks {
        check.validate()?;
        if !names.insert(check.name.clone())
            || registration.workers.iter().any(|worker| {
                worker.name.strip_prefix(WORKER_NAME_PREFIX) == Some(check.name.as_str())
            })
        {
            return Err(Error::Registration(
                "readiness names and their generated worker names must be unique".into(),
            ));
        }
    }
    for check in registration.checks.drain(..) {
        shared.health.set(check.name.clone(), false);
        let state = shared.clone();
        registration.workers.push(Worker {
            name: format!("{WORKER_NAME_PREFIX}{}", check.name),
            runs_in_api: true,
            factory: Box::new(move |context| Box::pin(async move {
                let shutdown = context.shutdown();
                loop {
                    let result = tokio::select! {
                        () = shutdown.cancelled() => return Ok(()),
                        result = tokio::time::timeout(check.policy.timeout, (check.run)()) => result,
                    };
                    let healthy = matches!(result, Ok(Ok(())));
                    state.health.set(check.name.clone(), healthy);
                    if healthy { context.ready(); }
                    tokio::select! {
                        () = shutdown.cancelled() => return Ok(()),
                        () = tokio::time::sleep(check.policy.interval) => {}
                    }
                }
            })),
        });
    }
    Ok(())
}