laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
//! The service container, which builds the application's services and shares
//! them with the code that needs them.
//!
//! Your application holds long-lived values, such as API clients and connection
//! pools, that handlers shouldn't build on every request. Register each one once,
//! and the container builds it the first time something asks for it:
//!
//! - Put [`#[singleton]`](singleton) or [`#[bind]`](bind) on an async function, which becomes
//!   the factory of the service it returns, or on a struct, which the container builds from its
//!   `#[inject]` fields. The application discovers both without any registration.
//! - Call [`instance`](Registrar::instance), [`singleton`](Registrar::singleton), or
//!   [`bind`](Registrar::bind) on the [`Registrar`] that a service provider or `with_services`
//!   callback receives.
//! - To use a service, a handler takes an [`Inject`] argument. Other code calls [`resolve`], and
//!   factories and boot hooks resolve services through the [`Container`] they receive.
//!
//! The container builds a singleton once and shares it, and builds a transient service on every
//! resolution. A resolution fails when the service isn't registered, when it depends on itself,
//! or when its factory fails. After a failure, the next resolution builds the service again.
//!
//! A factory may spawn a task with [`task::spawn`](crate::task::spawn). If that task resolves the
//! factory's own service before the factory returns, the resolution fails with the same error as
//! a service that depends on itself, because the factory may be waiting for the task.
//!
//! ```
//! use laravel::config::Section;
//! use laravel::container::{Inject, singleton};
//!
//! #[derive(Clone, Section)]
//! pub struct StripeConfig {
//!     #[env("STRIPE_KEY", required)]
//!     pub key: String,
//! }
//!
//! pub struct Stripe {
//!     key: String,
//! }
//!
//! impl Stripe {
//!     pub async fn charge(&self, cents: u64) -> laravel::Result<()> {
//!         // ...
//!         Ok(())
//!     }
//! }
//!
//! #[singleton]
//! async fn stripe(config: Section<StripeConfig>) -> laravel::Result<Stripe> {
//!     Ok(Stripe { key: config.key.clone() })
//! }
//!
//! pub async fn store(stripe: Inject<Stripe>) -> laravel::Result<&'static str> {
//!     stripe.charge(2_000).await?;
//!
//!     Ok("Paid")
//! }
//! ```
//!
//! See the [service container guide](https://github.com/laravel/rust-framework/blob/0.x/docs/container.md).

mod registrar;

pub(crate) use laravel_core::container::*;
#[doc(hidden)]
pub use laravel_core::container::{__Dependency, __Injectable, Requirement};
#[doc(inline)]
pub use laravel_core::container::{Callback, CallbackResult, Container, Inject, bind, resolve, singleton};

pub use self::registrar::Registrar;
#[doc(hidden)]
pub use self::registrar::{__Registration, __Service};

#[cfg(test)]
mod tests {
    use std::any::type_name;

    use super::*;
    use crate::foundation::{ServiceProvider, StartupError};

    struct Discovered(&'static str);

    inventory::submit! {
        __Registration {
            crate_name: "app",
            name: || "app::discovered",
            register: |app| { app.__service(|_| async { Ok(Discovered("discovered")) }, false); },
        }
    }

    #[tokio::test]
    async fn app_services_are_discovered_after_providers_and_before_application_callbacks() {
        struct Package;
        impl ServiceProvider for Package {
            fn register(&self, app: &mut Registrar) {
                app.instance(Discovered("provider"));
            }
        }
        let discovered = crate::Application::configure()
            .replace_env(crate::config::Env::default())
            .with_providers(|providers| {
                providers.add(Package);
            })
            .create();
        assert_eq!(discovered.resolve::<Discovered>().await.0, "discovered");

        let replaced = crate::Application::configure()
            .replace_env(crate::config::Env::default())
            .with_services(|app| {
                app.instance(Discovered("application"));
            })
            .create();
        assert_eq!(replaced.resolve::<Discovered>().await.0, "application");
    }

    struct Contested;
    trait Contract: Send + Sync {}
    impl Contract for Contested {}

    inventory::submit! {
        __Registration {
            crate_name: "conflicting_package",
            name: || "conflicting_package::first",
            register: |app| { app.__service(|_| async { Ok(Contested) }, false).__contract::<dyn Contract>(|service| service); },
        }
    }
    inventory::submit! {
        __Registration {
            crate_name: "conflicting_package",
            name: || "conflicting_package::second",
            register: |app| { app.__service(|_| async { Ok(Contested) }, false); },
        }
    }
    inventory::submit! {
        __Registration {
            crate_name: "other_package",
            name: || "other_package::replacement",
            register: |app| { app.__service(|_| async { Ok(Contested) }, false); },
        }
    }

    #[test]
    fn two_discovered_services_of_one_type_in_a_crate_stop_the_application() {
        struct Conflicting;
        impl ServiceProvider for Conflicting {
            fn register(&self, app: &mut Registrar) {
                app.discover("other_package")
                    .discover("conflicting_package")
                    .discover("conflicting_package");
            }
        }
        let error = crate::Application::configure()
            .replace_env(crate::config::Env::default())
            .with_providers(|providers| {
                providers.add(Conflicting);
            })
            .try_create()
            .unwrap_err();

        assert_eq!(
            error,
            StartupError::Services(vec![format!(
                "`{}` is registered by both `conflicting_package::first` and `conflicting_package::second`",
                type_name::<Contested>()
            )])
        );
    }
}