rainier-container 1.0.0

Rainier's IoC container, service providers, application lifecycle and facade machinery.
Documentation
//! Facades — static proxies onto container-resolved services.
//!
//! Laravel's facades work because PHP can intercept an unknown static call and
//! forward it to an object pulled from the container. Rust has no such hook, so
//! a Rainier facade is a zero-sized type with inherent methods that each begin
//! by resolving the underlying service:
//!
//! ```ignore
//! pub struct Queue;
//! impl Facade for Queue { type Accessor = QueueManager; }
//!
//! impl Queue {
//!     pub async fn push(job: impl Job) -> Result<JobId> {
//!         Self::instance().push(job).await     // <- resolve, then delegate
//!     }
//! }
//! ```
//!
//! The convenience is the same and so is the cost: a facade reaches into
//! **global** state, which makes the dependency invisible at the call site.
//! Prefer taking the service as a constructor argument in anything you intend
//! to unit-test; reach for the facade in application code and route closures,
//! where the ergonomics win.
//!
//! ## Testing
//!
//! There is no separate `swap` mechanism, because there does not need to be:
//! facades resolve through the container on *every* call, so rebinding the
//! accessor swaps what every facade call sees from that point on.
//!
//! ```ignore
//! app.instance(MailManager::fake());   // every `Mail::…` call now hits the fake
//! ```

use std::any::type_name;
use std::sync::{Arc, RwLock};

use crate::application::Application;

/// The application backing every facade in this process.
static FACADE_APP: RwLock<Option<Arc<Application>>> = RwLock::new(None);

/// Install the application that facades resolve through.
///
/// Called once during bootstrap. Calling it again replaces the binding, which
/// is what lets a test harness stand up a fresh application per test.
pub fn set_facade_application(app: Arc<Application>) {
    *FACADE_APP.write().expect("facade application lock poisoned") = Some(app);
}

/// The application facades resolve through, if one is installed.
pub fn try_facade_application() -> Option<Arc<Application>> {
    FACADE_APP.read().expect("facade application lock poisoned").clone()
}

/// The application facades resolve through.
///
/// # Panics
///
/// If no application has been installed. That is a bootstrap bug — a facade
/// was used before (or without) [`set_facade_application`] — so it fails loudly
/// rather than returning an error every call site would have to unwrap.
pub fn facade_application() -> Arc<Application> {
    try_facade_application().expect(
        "no application is bound to the facades — call `set_facade_application` during bootstrap \
         (or use the service directly instead of the facade)",
    )
}

/// Forget the installed application. Mainly for tests that assert on the
/// unbound behaviour.
pub fn clear_facade_application() {
    *FACADE_APP.write().expect("facade application lock poisoned") = None;
}

/// A static proxy onto a container-resolved service.
///
/// Implementors are zero-sized marker types; all the behaviour lives in the
/// [`Accessor`](Facade::Accessor) they resolve.
pub trait Facade {
    /// The service this facade forwards to.
    type Accessor: Send + Sync + 'static;

    /// Resolve the underlying service.
    ///
    /// # Panics
    ///
    /// If no application is installed, or the accessor is not bound in it.
    /// Both are configuration bugs: a facade whose service was never registered
    /// can never work, so it says so rather than propagating an error into
    /// every caller.
    fn instance() -> Arc<Self::Accessor> {
        let app = facade_application();
        match app.resolve::<Self::Accessor>() {
            Ok(service) => service,
            Err(e) => panic!(
                "the `{}` facade could not resolve `{}`: {e}",
                type_name::<Self>(),
                type_name::<Self::Accessor>()
            ),
        }
    }

    /// Resolve the underlying service, or `None` if the application or the
    /// binding is missing. For code that must degrade rather than panic.
    fn try_instance() -> Option<Arc<Self::Accessor>> {
        try_facade_application()?.try_resolve::<Self::Accessor>()
    }
}

/// Declare a facade type and its [`Facade`] impl.
///
/// ```
/// # use rainier_container::{facade, Application, Facade};
/// # use std::sync::Arc;
/// pub struct Clock {
///     pub now: u64,
/// }
///
/// facade!(
///     /// Reads the application clock.
///     Time => Clock
/// );
///
/// # fn main() {
/// let app = Application::new(".");
/// app.instance(Clock { now: 1 });
/// rainier_container::set_facade_application(Arc::new(app));
///
/// assert_eq!(Time::instance().now, 1);
/// # rainier_container::clear_facade_application();
/// # }
/// ```
#[macro_export]
macro_rules! facade {
    ($(#[$meta:meta])* $name:ident => $accessor:ty) => {
        $(#[$meta])*
        #[doc = ""]
        #[doc = concat!("A [`Facade`](", stringify!($crate), "::Facade) over [`", stringify!($accessor), "`].")]
        #[derive(Debug, Clone, Copy, Default)]
        pub struct $name;

        impl $crate::Facade for $name {
            type Accessor = $accessor;
        }
    };
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Container;

    struct Clock(u64);
    struct Missing;

    struct Time;
    impl Facade for Time {
        type Accessor = Clock;
    }

    struct Nowhere;
    impl Facade for Nowhere {
        type Accessor = Missing;
    }

    // The facade application is process-global, so these tests must not run
    // concurrently with one another.
    static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());

    fn with_app(build: impl FnOnce(&Application)) -> std::sync::MutexGuard<'static, ()> {
        let guard = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
        let app = Application::new(".");
        build(&app);
        set_facade_application(Arc::new(app));
        guard
    }

    #[test]
    fn a_facade_resolves_through_the_container() {
        let _guard = with_app(|app| app.instance(Clock(5)));
        assert_eq!(Time::instance().0, 5);
        clear_facade_application();
    }

    #[test]
    fn rebinding_the_accessor_swaps_what_the_facade_sees() {
        let _guard = with_app(|app| app.instance(Clock(1)));
        assert_eq!(Time::instance().0, 1);

        // No `swap` API needed: the facade re-resolves on every call.
        facade_application().instance(Clock(2));
        assert_eq!(Time::instance().0, 2);
        clear_facade_application();
    }

    #[test]
    fn try_instance_is_none_for_an_unbound_accessor() {
        let _guard = with_app(|_| {});
        assert!(Nowhere::try_instance().is_none());
        clear_facade_application();
    }

    #[test]
    fn try_instance_is_none_with_no_application() {
        let _guard = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
        clear_facade_application();
        assert!(Time::try_instance().is_none());
    }

    #[test]
    #[should_panic(expected = "could not resolve")]
    fn instance_panics_for_an_unbound_accessor() {
        let _guard = with_app(|_| {});
        let _ = Nowhere::instance();
    }

    #[test]
    fn a_transient_binding_is_re_resolved_each_call() {
        let _guard = with_app(|app| {
            app.bind(|_: &Container| Ok(Clock(7)));
        });
        let a = Time::instance();
        let b = Time::instance();
        assert_eq!(a.0, b.0);
        assert!(!Arc::ptr_eq(&a, &b));
        clear_facade_application();
    }
}