footing 0.1.22

Feature-gated foundations for Rust backend services
Documentation
//! Async resource probes and ordered diagnostic registry.

use std::{fmt, future::Future, sync::Arc, time::Duration};

use async_trait::async_trait;

use crate::result::BoxError;

use super::{
    error::ResourceRegistryError,
    model::{
        DEFAULT_RESOURCE_PROBE_TIMEOUT, ResourceDescriptor, ResourceDiagnostic,
        ResourceDiagnosticsReport, normalize_diagnostics_service_name,
    },
};

/// A resource probe registered with a [`ResourceRegistry`].
#[async_trait]
pub trait ResourceProbe: Send + Sync + 'static {
    /// Validated metadata, immutable for the lifetime of this probe.
    fn descriptor(&self) -> &ResourceDescriptor;

    /// Runs the probe.
    async fn probe(&self) -> Result<ResourceDiagnostic, BoxError>;
}

/// Builds a static probe from a descriptor, constructor, and summary.
#[must_use]
pub fn static_resource_probe(
    descriptor: ResourceDescriptor,
    diagnostic: fn(ResourceDescriptor, String) -> ResourceDiagnostic,
    summary: impl Into<String>,
) -> Arc<dyn ResourceProbe> {
    let summary = summary.into();
    resource_probe(descriptor, move |descriptor| {
        let summary = summary.clone();
        async move { Ok(diagnostic(descriptor, summary)) }
    })
}

/// Builds a probe from a descriptor and an async closure.
///
/// This is the usual choice for application diagnostics because the closure can
/// capture config, clients, or preloaded state without requiring one-off probe
/// structs.
#[must_use]
pub fn resource_probe<F, Fut>(descriptor: ResourceDescriptor, probe: F) -> Arc<dyn ResourceProbe>
where
    F: Fn(ResourceDescriptor) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<ResourceDiagnostic, BoxError>> + Send + 'static,
{
    Arc::new(FnResourceProbe { descriptor, probe })
}

/// Ordered registry of resources probed for startup/readiness.
#[derive(Clone)]
pub struct ResourceRegistry {
    service_name: String,
    probes: Vec<Arc<dyn ResourceProbe>>,
    probe_timeout: Duration,
}

impl ResourceRegistry {
    /// Creates an empty registry.
    pub fn new(service_name: impl Into<String>) -> Result<Self, ResourceRegistryError> {
        Ok(Self {
            service_name: normalize_diagnostics_service_name(service_name)?,
            probes: Vec::new(),
            probe_timeout: DEFAULT_RESOURCE_PROBE_TIMEOUT,
        })
    }

    /// Configures a nonzero per-probe timeout within the runtime timer range.
    pub fn with_probe_timeout(
        mut self,
        probe_timeout: Duration,
    ) -> Result<Self, ResourceRegistryError> {
        if probe_timeout.is_zero()
            || tokio::time::Instant::now()
                .checked_add(probe_timeout)
                .is_none()
        {
            return Err(ResourceRegistryError::InvalidProbeTimeout);
        }
        self.probe_timeout = probe_timeout;
        Ok(self)
    }

    /// Registers one probe.
    pub fn with_probe(
        mut self,
        probe: Arc<dyn ResourceProbe>,
    ) -> Result<Self, ResourceRegistryError> {
        self.push_probe(probe)?;
        Ok(self)
    }

    /// Registers one probe by mutable reference.
    pub fn push_probe(
        &mut self,
        probe: Arc<dyn ResourceProbe>,
    ) -> Result<(), ResourceRegistryError> {
        if self.probes.len() >= super::model::MAX_RESOURCE_REPORT_RESOURCES {
            return Err(ResourceRegistryError::TooManyResources {
                max: super::model::MAX_RESOURCE_REPORT_RESOURCES,
            });
        }
        let index = self.probes.len();
        let descriptor = probe.descriptor();
        if let Some(first_index) = self
            .probes
            .iter()
            .position(|registered| registered.descriptor().id() == descriptor.id())
        {
            return Err(ResourceRegistryError::DuplicateResourceId {
                id: descriptor.id().to_owned(),
                first_index,
                second_index: index,
            });
        }
        self.probes.push(probe);
        Ok(())
    }

    /// Returns the validated service name.
    #[must_use]
    pub fn service_name(&self) -> &str {
        &self.service_name
    }

    /// Returns registered probes in execution order.
    #[must_use]
    pub fn probes(&self) -> &[Arc<dyn ResourceProbe>] {
        &self.probes
    }

    /// Returns the maximum duration of each individual probe.
    #[must_use]
    pub const fn probe_timeout(&self) -> Duration {
        self.probe_timeout
    }

    /// Runs every probe and returns a report, including probe failures and timeouts.
    pub async fn run(&self) -> ResourceDiagnosticsReport {
        let mut diagnostics = Vec::with_capacity(self.probes.len());
        for probe in &self.probes {
            let descriptor = probe.descriptor();
            match tokio::time::timeout(self.probe_timeout, probe.probe()).await {
                Ok(Ok(mut diagnostic)) => {
                    if diagnostic.resource() != descriptor {
                        diagnostic.replace_resource(descriptor.clone());
                    }
                    diagnostics.push(diagnostic);
                }
                Ok(Err(source)) => {
                    tracing::warn!(
                        target: "footing::diagnostics",
                        error_code = "resource_probe_failed",
                        resource_id = %descriptor.id(),
                        "resource diagnostics probe failed"
                    );
                    drop(source);
                    diagnostics.push(ResourceDiagnostic::unhealthy(
                        descriptor.clone(),
                        "resource probe failed",
                    ));
                }
                Err(_) => {
                    tracing::warn!(
                        target: "footing::diagnostics",
                        error_code = "resource_probe_timed_out",
                        resource_id = %descriptor.id(),
                        "resource diagnostics probe timed out"
                    );
                    diagnostics.push(ResourceDiagnostic::unhealthy(
                        descriptor.clone(),
                        "resource probe timed out",
                    ));
                }
            }
        }

        ResourceDiagnosticsReport::from_validated(self.service_name.clone(), diagnostics)
    }
}

impl fmt::Debug for ResourceRegistry {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ResourceRegistry")
            .field("service_name", &self.service_name)
            .field("probes", &self.probes.len())
            .field("probe_timeout", &self.probe_timeout)
            .finish()
    }
}

struct FnResourceProbe<F> {
    descriptor: ResourceDescriptor,
    probe: F,
}

#[async_trait]
impl<F, Fut> ResourceProbe for FnResourceProbe<F>
where
    F: Fn(ResourceDescriptor) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<ResourceDiagnostic, BoxError>> + Send + 'static,
{
    fn descriptor(&self) -> &ResourceDescriptor {
        &self.descriptor
    }

    async fn probe(&self) -> Result<ResourceDiagnostic, BoxError> {
        (self.probe)(self.descriptor.clone()).await
    }
}