capy-core 0.10.0

Typed configuration, application context, and errors for the Capy web framework.
Documentation
use crate::{AppError, Result};
use std::{
    any::{type_name, Any, TypeId},
    collections::HashMap,
    sync::Arc,
};

/// Immutable, cheaply cloned application dependencies keyed by their Rust type.
/// Each application factory owns its registry; there is no process-wide state.
#[derive(Clone, Default)]
pub struct Services(Arc<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>);

impl std::fmt::Debug for Services {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Services")
            .field("count", &self.0.len())
            .finish()
    }
}

impl Services {
    /// Create an empty registry.
    pub fn new() -> Self {
        Self::default()
    }

    /// Register or replace one dependency. Existing clones retain their snapshot.
    pub fn insert<T: Send + Sync + 'static>(&mut self, service: T) {
        Arc::make_mut(&mut self.0).insert(TypeId::of::<T>(), Arc::new(service));
    }

    /// Obtain a shared dependency, or an actionable missing-registration error.
    pub fn get<T: Send + Sync + 'static>(&self) -> Result<Arc<T>> {
        self.find::<T>().ok_or_else(|| {
                AppError::Configuration(format!(
                    "Application service {} is not registered; add App::service in the application factory.",
                    type_name::<T>()
                ))
            })
    }

    /// Check for an optional dependency without creating a missing-service error.
    pub fn find<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
        self.0
            .get(&TypeId::of::<T>())
            .cloned()
            .and_then(|service| service.downcast::<T>().ok())
    }
}

/// Extract a typed registered service from an HTTP request.
pub struct Service<T: Send + Sync + 'static>(pub Arc<T>);

impl<T: Send + Sync + 'static> axum::extract::FromRequestParts<crate::AppContext> for Service<T> {
    type Rejection = AppError;

    async fn from_request_parts(
        parts: &mut axum::http::request::Parts,
        _state: &crate::AppContext,
    ) -> Result<Self> {
        let services = parts.extensions.get::<Services>().ok_or_else(|| {
            AppError::Configuration("Application services are not installed on this router.".into())
        })?;
        services.get().map(Self)
    }
}