From fdd7f824fd1244226ca86f525f8439744676688f Mon Sep 17 00:00:00 2001 From: HampusM Date: Sat, 24 Sep 2022 17:31:16 +0200 Subject: feat: add bind async default factories to async DI container --- src/async_di_container.rs | 139 +++++++++++++++++++++++++++++-------- src/castable_factory/mod.rs | 2 + src/castable_factory/threadsafe.rs | 4 +- src/interfaces/factory.rs | 9 +++ src/lib.rs | 5 ++ src/provider/async.rs | 37 +++++++--- 6 files changed, 155 insertions(+), 41 deletions(-) (limited to 'src') diff --git a/src/async_di_container.rs b/src/async_di_container.rs index d90cc0b..894b707 100644 --- a/src/async_di_container.rs +++ b/src/async_di_container.rs @@ -69,6 +69,7 @@ use crate::errors::async_di_container::{ AsyncBindingWhenConfiguratorError, AsyncDIContainerError, }; +use crate::future::BoxFuture; use crate::interfaces::async_injectable::AsyncInjectable; use crate::libs::intertrait::cast::error::CastError; use crate::libs::intertrait::cast::{CastArc, CastBox}; @@ -274,6 +275,8 @@ where > + Send + Sync, { + use crate::provider::r#async::AsyncFactoryVariant; + let mut bindings_lock = self.di_container.bindings.lock().await; if bindings_lock.has::(None) { @@ -289,7 +292,7 @@ where None, Box::new(crate::provider::r#async::AsyncFactoryProvider::new( crate::ptr::ThreadsafeFactoryPtr::new(factory_impl), - false, + AsyncFactoryVariant::Normal, )), ); @@ -313,7 +316,8 @@ where where Args: 'static, Return: 'static + ?Sized, - Interface: Fn>, + Interface: + Fn> + Send + Sync, FactoryFunc: Fn< (Arc,), Output = Box< @@ -324,6 +328,8 @@ where > + Send + Sync, { + use crate::provider::r#async::AsyncFactoryVariant; + let mut bindings_lock = self.di_container.bindings.lock().await; if bindings_lock.has::(None) { @@ -339,7 +345,7 @@ where None, Box::new(crate::provider::r#async::AsyncFactoryProvider::new( crate::ptr::ThreadsafeFactoryPtr::new(factory_impl), - false, + AsyncFactoryVariant::Normal, )), ); @@ -369,6 +375,58 @@ where > + Send + Sync, { + use crate::provider::r#async::AsyncFactoryVariant; + + let mut bindings_lock = self.di_container.bindings.lock().await; + + if bindings_lock.has::(None) { + return Err(AsyncBindingBuilderError::BindingAlreadyExists(type_name::< + Interface, + >( + ))); + } + + let factory_impl = ThreadsafeCastableFactory::new(factory_func); + + bindings_lock.set::( + None, + Box::new(crate::provider::r#async::AsyncFactoryProvider::new( + crate::ptr::ThreadsafeFactoryPtr::new(factory_impl), + AsyncFactoryVariant::Default, + )), + ); + + Ok(AsyncBindingWhenConfigurator::new(self.di_container.clone())) + } + + /// Creates a binding of factory type `Interface` to a async factory inside of the + /// associated [`AsyncDIContainer`]. + /// + /// *This function is only available if Syrette is built with the "factory" and + /// "async" features.* + /// + /// # Errors + /// Will return Err if the associated [`AsyncDIContainer`] already have a binding for + /// the interface. + #[cfg(all(feature = "factory", feature = "async"))] + pub async fn to_async_default_factory( + &self, + factory_func: &'static FactoryFunc, + ) -> Result, AsyncBindingBuilderError> + where + Return: 'static + ?Sized, + FactoryFunc: Fn< + (Arc,), + Output = Box< + (dyn Fn<(), Output = crate::future::BoxFuture<'static, Return>> + + Send + + Sync), + >, + > + Send + + Sync, + { + use crate::provider::r#async::AsyncFactoryVariant; + let mut bindings_lock = self.di_container.bindings.lock().await; if bindings_lock.has::(None) { @@ -384,7 +442,7 @@ where None, Box::new(crate::provider::r#async::AsyncFactoryProvider::new( crate::ptr::ThreadsafeFactoryPtr::new(factory_impl), - true, + AsyncFactoryVariant::AsyncDefault, )), ); @@ -464,10 +522,10 @@ impl AsyncDIContainer .get_binding_providable::(name, dependency_history) .await?; - self.handle_binding_providable(binding_providable) + self.handle_binding_providable(binding_providable).await } - fn handle_binding_providable( + async fn handle_binding_providable( self: &Arc, binding_providable: AsyncProvidable, ) -> Result, AsyncDIContainerError> @@ -507,11 +565,10 @@ impl AsyncDIContainer } #[cfg(feature = "factory")] AsyncProvidable::Factory(factory_binding) => { + use crate::interfaces::factory::IThreadsafeFactory; + let factory = factory_binding - .cast::,), - Interface, - >>() + .cast::,), Interface>>() .map_err(|err| match err { CastError::NotArcCastable(_) => { AsyncDIContainerError::InterfaceNotAsync( @@ -531,33 +588,59 @@ impl AsyncDIContainer )) } #[cfg(feature = "factory")] - AsyncProvidable::DefaultFactory(default_factory_binding) => { - use crate::interfaces::factory::IFactory; + AsyncProvidable::DefaultFactory(binding) => { + use crate::interfaces::factory::IThreadsafeFactory; - let default_factory = default_factory_binding - .cast::,), dyn Fn<(), Output = TransientPtr> + Send + Sync, - >>() - .map_err(|err| match err { - CastError::NotArcCastable(_) => { - AsyncDIContainerError::InterfaceNotAsync( - type_name::(), - ) - } - CastError::CastFailed { from: _, to: _ } => { - AsyncDIContainerError::CastFailed { - interface: type_name::(), - binding_kind: "default factory", - } - } - })?; + >, + >(binding, "default factory")?; Ok(SomeThreadsafePtr::Transient(default_factory(self.clone())())) } + #[cfg(feature = "factory")] + AsyncProvidable::AsyncDefaultFactory(binding) => { + use crate::interfaces::factory::IThreadsafeFactory; + + let async_default_factory = Self::cast_factory_binding::< + dyn IThreadsafeFactory< + (Arc,), + dyn Fn<(), Output = BoxFuture<'static, TransientPtr>> + + Send + + Sync, + >, + >( + binding, "async default factory" + )?; + + Ok(SomeThreadsafePtr::Transient( + async_default_factory(self.clone())().await, + )) + } } } + #[cfg(feature = "factory")] + fn cast_factory_binding( + factory_binding: Arc, + binding_kind: &'static str, + ) -> Result, AsyncDIContainerError> + { + factory_binding.cast::().map_err(|err| match err { + CastError::NotArcCastable(_) => { + AsyncDIContainerError::InterfaceNotAsync(type_name::()) + } + CastError::CastFailed { from: _, to: _ } => { + AsyncDIContainerError::CastFailed { + interface: type_name::(), + binding_kind, + } + } + }) + } + async fn get_binding_providable( self: &Arc, name: Option<&'static str>, diff --git a/src/castable_factory/mod.rs b/src/castable_factory/mod.rs index 530cc82..e81b842 100644 --- a/src/castable_factory/mod.rs +++ b/src/castable_factory/mod.rs @@ -1,2 +1,4 @@ pub mod blocking; + +#[cfg(feature = "async")] pub mod threadsafe; diff --git a/src/castable_factory/threadsafe.rs b/src/castable_factory/threadsafe.rs index 7be055c..b91dceb 100644 --- a/src/castable_factory/threadsafe.rs +++ b/src/castable_factory/threadsafe.rs @@ -1,6 +1,6 @@ #![allow(clippy::module_name_repetitions)] use crate::interfaces::any_factory::{AnyFactory, AnyThreadsafeFactory}; -use crate::interfaces::factory::IFactory; +use crate::interfaces::factory::IThreadsafeFactory; use crate::ptr::TransientPtr; pub struct ThreadsafeCastableFactory @@ -26,7 +26,7 @@ where } } -impl IFactory +impl IThreadsafeFactory for ThreadsafeCastableFactory where Args: 'static, diff --git a/src/interfaces/factory.rs b/src/interfaces/factory.rs index b09db36..de1fca9 100644 --- a/src/interfaces/factory.rs +++ b/src/interfaces/factory.rs @@ -9,3 +9,12 @@ where ReturnInterface: 'static + ?Sized, { } + +/// Interface for a threadsafe factory. +#[cfg(feature = "async")] +pub trait IThreadsafeFactory: + Fn> + crate::libs::intertrait::CastFromSync +where + ReturnInterface: 'static + ?Sized, +{ +} diff --git a/src/lib.rs b/src/lib.rs index 247f907..082a93d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -125,4 +125,9 @@ macro_rules! async_closure { Box::pin(async move { $($inner)* }) }) }; + (|| { $($inner: stmt);* }) => { + Box::new(|| { + Box::pin(async move { $($inner)* }) + }) + }; } diff --git a/src/provider/async.rs b/src/provider/async.rs index df96b27..c9a5273 100644 --- a/src/provider/async.rs +++ b/src/provider/async.rs @@ -26,6 +26,12 @@ pub enum AsyncProvidable dyn crate::interfaces::any_factory::AnyThreadsafeFactory, >, ), + #[cfg(feature = "factory")] + AsyncDefaultFactory( + crate::ptr::ThreadsafeFactoryPtr< + dyn crate::interfaces::any_factory::AnyThreadsafeFactory, + >, + ), } #[async_trait] @@ -150,13 +156,21 @@ where } } +#[derive(Clone, Copy)] +pub enum AsyncFactoryVariant +{ + Normal, + Default, + AsyncDefault, +} + #[cfg(feature = "factory")] pub struct AsyncFactoryProvider { factory: crate::ptr::ThreadsafeFactoryPtr< dyn crate::interfaces::any_factory::AnyThreadsafeFactory, >, - is_default_factory: bool, + variant: AsyncFactoryVariant, } #[cfg(feature = "factory")] @@ -166,13 +180,10 @@ impl AsyncFactoryProvider factory: crate::ptr::ThreadsafeFactoryPtr< dyn crate::interfaces::any_factory::AnyThreadsafeFactory, >, - is_default_factory: bool, + variant: AsyncFactoryVariant, ) -> Self { - Self { - factory, - is_default_factory, - } + Self { factory, variant } } } @@ -186,10 +197,14 @@ impl IAsyncProvider for AsyncFactoryProvider _dependency_history: Vec<&'static str>, ) -> Result { - Ok(if self.is_default_factory { - AsyncProvidable::DefaultFactory(self.factory.clone()) - } else { - AsyncProvidable::Factory(self.factory.clone()) + Ok(match self.variant { + AsyncFactoryVariant::Normal => AsyncProvidable::Factory(self.factory.clone()), + AsyncFactoryVariant::Default => { + AsyncProvidable::DefaultFactory(self.factory.clone()) + } + AsyncFactoryVariant::AsyncDefault => { + AsyncProvidable::AsyncDefaultFactory(self.factory.clone()) + } }) } @@ -206,7 +221,7 @@ impl Clone for AsyncFactoryProvider { Self { factory: self.factory.clone(), - is_default_factory: self.is_default_factory.clone(), + variant: self.variant, } } } -- cgit v1.2.3-18-g5258