Skip to main content

capy_core/
services.rs

1use crate::{AppError, Result};
2use std::{
3    any::{type_name, Any, TypeId},
4    collections::HashMap,
5    sync::Arc,
6};
7
8/// Immutable, cheaply cloned application dependencies keyed by their Rust type.
9/// Each application factory owns its registry; there is no process-wide state.
10#[derive(Clone, Default)]
11pub struct Services(Arc<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>);
12
13impl std::fmt::Debug for Services {
14    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15        f.debug_struct("Services")
16            .field("count", &self.0.len())
17            .finish()
18    }
19}
20
21impl Services {
22    /// Create an empty registry.
23    pub fn new() -> Self {
24        Self::default()
25    }
26
27    /// Register or replace one dependency. Existing clones retain their snapshot.
28    pub fn insert<T: Send + Sync + 'static>(&mut self, service: T) {
29        Arc::make_mut(&mut self.0).insert(TypeId::of::<T>(), Arc::new(service));
30    }
31
32    /// Obtain a shared dependency, or an actionable missing-registration error.
33    pub fn get<T: Send + Sync + 'static>(&self) -> Result<Arc<T>> {
34        self.find::<T>().ok_or_else(|| {
35                AppError::Configuration(format!(
36                    "Application service {} is not registered; add App::service in the application factory.",
37                    type_name::<T>()
38                ))
39            })
40    }
41
42    /// Check for an optional dependency without creating a missing-service error.
43    pub fn find<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
44        self.0
45            .get(&TypeId::of::<T>())
46            .cloned()
47            .and_then(|service| service.downcast::<T>().ok())
48    }
49}
50
51/// Extract a typed registered service from an HTTP request.
52pub struct Service<T: Send + Sync + 'static>(pub Arc<T>);
53
54impl<T: Send + Sync + 'static> axum::extract::FromRequestParts<crate::AppContext> for Service<T> {
55    type Rejection = AppError;
56
57    async fn from_request_parts(
58        parts: &mut axum::http::request::Parts,
59        _state: &crate::AppContext,
60    ) -> Result<Self> {
61        let services = parts.extensions.get::<Services>().ok_or_else(|| {
62            AppError::Configuration("Application services are not installed on this router.".into())
63        })?;
64        services.get().map(Self)
65    }
66}