-
Notifications
You must be signed in to change notification settings - Fork 0
feat/wrapp-config #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
abe0e0a
chore: moved common dependencies to root Cargo.toml workspace
Dimi-Provatas 20556f9
feat: Config
Dimi-Provatas be8f6ab
chore: moved all exteranl crates to workspace dependencies
Dimi-Provatas 22b8fb3
chore: better doc comment for wrapp-config/lib.rs
Dimi-Provatas 555998b
chore: comment out `maybe_add_config` function
Dimi-Provatas 4ac67fb
fix: rename ConfigProvider::initialize to ConfigProvider::new
Dimi-Provatas b0d849d
chore: move example to examples directory
Dimi-Provatas 8b8d5c6
feat: separate config related errors
Dimi-Provatas 15548b8
feat: docs for the Config wrapper type with a small example
Dimi-Provatas f033e50
refactor
Aderinom File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,15 @@ | ||
| [workspace] | ||
| resolver = "2" | ||
| members = ["examples/*", "features/*", "strategies/*", "wrapp"] | ||
|
|
||
| [workspace.dependencies] | ||
|
|
||
| # Project Modules | ||
| wrapp-di = { path = "./features/wrapp-di" } | ||
|
|
||
| # External Crates | ||
| futures = "0.3" | ||
| futures-channel = "0.3" | ||
| tracing = "0.1" | ||
| pin-project-lite = "0.2" | ||
| thiserror = "2.0" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| use wrapp_config::provider::ConfigProvider; | ||
|
|
||
| #[derive(Clone)] | ||
| struct AppConfig { | ||
| host: String, | ||
| port: u16, | ||
| app_name: String, | ||
| } | ||
|
|
||
| fn main() { | ||
| let app_config = AppConfig { | ||
| host: "localhost".to_string(), | ||
| port: 8080_u16, | ||
| app_name: "My Awesome App".to_string(), | ||
| }; | ||
|
|
||
| let mut config_provider = ConfigProvider::new(); | ||
| let config_provider = match config_provider.add_config(app_config.clone()) { | ||
| Ok(p) => p, | ||
| Err(e) => { | ||
| eprintln!("{e:?}"); | ||
| return; | ||
| } | ||
| }; | ||
|
|
||
| let retrieved_config = match config_provider.config::<AppConfig>() { | ||
| Some(c) => c, | ||
| None => { | ||
| eprintln!("Could not find config type"); | ||
| return; | ||
| } | ||
| }; | ||
|
|
||
| assert_eq!(app_config.host, retrieved_config.host); | ||
| assert_eq!(app_config.port, retrieved_config.port); | ||
| assert_eq!(app_config.app_name, retrieved_config.app_name); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| //! Config Errors | ||
|
|
||
| use wrapp_di::types::TypeInfo; | ||
|
|
||
|
|
||
| /// Errors when trying to register a config | ||
| #[derive(thiserror::Error, Debug, Clone)] | ||
| pub enum RegisterConfigError { | ||
| /// The required Config is already registered | ||
| #[error("The required Config type is already registered")] | ||
| AlreadyRegistered(TypeInfo), | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,14 +1,16 @@ | ||
| pub fn add(left: usize, right: usize) -> usize { | ||
| left + right | ||
| } | ||
| //! Wrapp Config provides a simple config injection mechanism for Wrapp DI. | ||
| //! | ||
| //! ### Overview | ||
| //! | ||
| //! - [`ConfigProvider`](crate::provider::ConfigProvider) - Registry of configs which can be injected into modules. | ||
| //! - [`Config<ConfigType>`](crate::resolver::Config) - [`Resolver`](wrapp_di::resolver::Resolver) type which allows for config injections in factories. | ||
| //! | ||
| //! | ||
| //! # Examples | ||
| //! ```rust | ||
| #![doc = include_str!("../examples/using-config-provider.rs")] | ||
| //! ``` | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn it_works() { | ||
| let result = add(2, 2); | ||
| assert_eq!(result, 4); | ||
| } | ||
| } | ||
| pub mod resolver; | ||
| pub mod errors; | ||
| pub mod provider; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| //! Config provider to register and retrieve configs based on type. | ||
|
|
||
| use std::{ | ||
| any::{Any, TypeId}, | ||
| collections::HashMap, | ||
| sync::Arc, | ||
| }; | ||
|
|
||
| use wrapp_di::types::TypeInfo; | ||
|
|
||
| use crate::errors::{RegisterConfigError}; | ||
|
|
||
| /// A provider to register all configs. | ||
| /// | ||
| /// Configs can be registered and retrieved based on type. | ||
| #[derive(Default)] | ||
| pub struct ConfigProvider { | ||
| configs: HashMap<TypeId, Arc<dyn Any + Send + Sync + 'static>>, | ||
| } | ||
|
|
||
| impl ConfigProvider { | ||
| /// Initializes an empty Config Provider | ||
| pub fn new() -> Self { | ||
| Self { | ||
| configs: HashMap::new(), | ||
| } | ||
| } | ||
|
|
||
| /// Retrieve a config with specified type. | ||
| pub fn config<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> { | ||
| let type_id = TypeId::of::<T>(); | ||
|
|
||
| let config = self.configs | ||
| .get(&type_id)?; | ||
|
|
||
| match config.clone().downcast::<T>() { | ||
| Ok(config) => Some(config), | ||
| Err(_) => { | ||
| debug_assert!(false, "Config Provider contained invalid type in slot for type: {:?}", TypeInfo::of::<T>()); | ||
| tracing::error!("Config Provider contained invalid type in slot for type: {:?}", TypeInfo::of::<T>()); | ||
| None | ||
| }, | ||
| } | ||
|
|
||
| } | ||
|
|
||
| /// Add a config to the registry. | ||
| pub fn add_config<T: Send + Sync + 'static>( | ||
| &mut self, | ||
| config: T, | ||
| ) -> Result<&mut Self, RegisterConfigError> { | ||
| let type_id = TypeId::of::<T>(); | ||
|
|
||
| if self.configs.contains_key(&type_id) { | ||
| return Err(RegisterConfigError::AlreadyRegistered(TypeInfo::of::<T>())); | ||
| } | ||
|
|
||
| self.configs.insert(type_id, Arc::new(config)); | ||
| Ok(self) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| //! Config resolver for Wrapp DI | ||
|
|
||
| use std::{any::type_name, ops::Deref, sync::Arc}; | ||
|
|
||
| use wrapp_di::{ | ||
| errors::{InjectError, RequireError}, | ||
| initiator::DiHandle, | ||
| resolver::Resolver, | ||
| types::{DependencyInfo, TypeInfo}, | ||
| }; | ||
|
|
||
| use crate::provider::ConfigProvider; | ||
|
|
||
| /// A wrapper type to allow for config injections | ||
| /// | ||
| /// This provides a simple way to retrieve configs from the config registry, | ||
| /// and inject them on a factory as a dependency | ||
| /// | ||
| /// # Example | ||
| /// ```ignore | ||
| /// # use wrapp_config::provider::ConfigProvider; | ||
| /// # use wrapp_config::resolver::Config; | ||
| /// #[derive(Clone)] | ||
| /// pub struct MyModuleConfig { | ||
| /// enabled: bool, | ||
| /// //... | ||
| /// } | ||
| /// | ||
| /// fn register_config() { | ||
| /// let config_provider = ConfigProvider::new(); | ||
| /// let my_module_config = MyModuleConfig { | ||
| /// enabled: true, | ||
| /// //... | ||
| /// }; | ||
| /// | ||
| /// config_provider.add_config(my_module_config).unwrap(); | ||
| /// } | ||
| /// | ||
| /// | ||
| /// #[wrapp::module] | ||
| /// pub struct MyModule; | ||
| /// impl MyModule { | ||
| /// #[wrapp::module(condition)] | ||
| /// pub fn enable(config: Config<MyModuleConfig>) -> bool { | ||
| /// config.enabled | ||
| /// } | ||
| /// } | ||
| /// | ||
| /// ``` | ||
| pub struct Config<T> { | ||
|
Dimi-Provatas marked this conversation as resolved.
|
||
| inner: Arc<T>, | ||
| } | ||
| impl<T> Deref for Config<T> { | ||
| type Target = T; | ||
|
|
||
| fn deref(&self) -> &Self::Target { | ||
| &self.inner | ||
| } | ||
| } | ||
| impl<T> Config<T> { | ||
| pub fn inner(&self) -> Arc<T> { | ||
| self.inner.clone() | ||
| } | ||
|
|
||
| pub fn into_inner(self) -> Arc<T> { | ||
| self.inner | ||
| } | ||
| } | ||
|
|
||
| impl<T: Send + Sync + 'static> Resolver for Config<T> { | ||
| async fn resolve(handle: &mut DiHandle) -> Result<Self, InjectError> | ||
| where | ||
| Self: Sized, | ||
| { | ||
| let config_name = type_name::<T>(); | ||
| let config_provider = handle.resolve::<Arc<ConfigProvider>>().await?; | ||
|
|
||
| let config: Arc<T> = config_provider | ||
| .config() | ||
| .ok_or_else(|| InjectError::RequireError(RequireError::TypeMissing(config_name)))?; | ||
|
|
||
| Ok(Config { inner: config }) | ||
| } | ||
|
|
||
| fn dependency_info() -> DependencyInfo { | ||
| DependencyInfo { | ||
| type_info: TypeInfo::of::<Config<T>>(), | ||
| optional: false, | ||
| lazy: false, | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.