use crate::{
Error, Result,
app::Registration,
lifecycle::Shared,
task::{self, Worker},
};
use std::{future::Future, pin::Pin, sync::Arc, time::Duration};
#[derive(Clone, Copy, Debug)]
pub struct CheckPolicy {
pub interval: Duration,
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 ®istration.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(())
}