1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
//! Packages that can be initialized by `salak`.
//!
//! ### Provide packages
//!
//! 1. toy_log
//! ```no_run
//! use salak::*;
//! use salak_factory::*;
//! use tracing::subscriber::set_global_default;
//! use tracing_subscriber::prelude::*;
//! use tracing_subscriber::registry;
//! let env = Salak::new()
//!     .with_default_args(auto_read_sys_args_param!())
//!     .build();
//! let layer = env.build::<LogConfig>().unwrap();
//! set_global_default(registry().with(layer));
//! ```
//! 2. redis
//! ```no_run
//! use salak::*;
//! use salak_factory::*;
//! let env = Salak::new()
//!     .with_default_args(auto_read_sys_args_param!())
//!     .build();
//! let redis_pool = env.build::<RedisConfig>().unwrap();
//! ```
//! 3. redis_cluster
//! ```no_run
//! use salak::*;
//! use salak_factory::*;
//! let env = Salak::new()
//!     .with_default_args(auto_read_sys_args_param!())
//!     .build();
//! let redis_cluster_pool = env.build::<RedisClusterConfig>().unwrap();
//! ```
//! 4. postgres
//! ```no_run
//! use salak::*;
//! use salak_factory::*;
//! let env = Salak::new()
//!     .with_default_args(auto_read_sys_args_param!())
//!     .build();
//! let pg_pool = env.build::<PostgresConfig>().unwrap();
//! ```

#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(
    anonymous_parameters,
    missing_copy_implementations,
    missing_debug_implementations,
    missing_docs,
    nonstandard_style,
    rust_2018_idioms,
    single_use_lifetimes,
    trivial_casts,
    trivial_numeric_casts,
    unreachable_pub,
    unused_extern_crates,
    unused_qualifications,
    variant_size_differences
)]

use salak::*;

#[cfg(feature = "enable_pool")]
#[cfg_attr(docsrs, doc(cfg(feature = "enable_pool")))]
mod pool;
#[cfg(feature = "enable_pool")]
#[cfg_attr(docsrs, doc(cfg(feature = "enable_pool")))]
pub use crate::pool::*;

#[cfg(feature = "enable_postgres")]
#[cfg_attr(docsrs, doc(cfg(feature = "enable_postgres")))]
mod postgres;
#[cfg(feature = "enable_postgres")]
#[cfg_attr(docsrs, doc(cfg(feature = "enable_postgres")))]
pub use crate::postgres::{PostgresConfig, PostgresConnectionManager, PostgresCustomizer};

#[cfg(feature = "enable_redis")]
#[cfg_attr(docsrs, doc(cfg(feature = "enable_redis")))]
mod redis;
#[cfg(feature = "enable_redis")]
#[cfg_attr(docsrs, doc(cfg(feature = "enable_redis")))]
pub use crate::redis::{RedisConfig, RedisConnectionManager};

#[cfg(feature = "enable_redis_cluster")]
#[cfg_attr(docsrs, doc(cfg(feature = "enable_redis_cluster")))]
mod redis_cluster;
#[cfg(feature = "enable_redis_cluster")]
#[cfg_attr(docsrs, doc(cfg(feature = "enable_redis_cluster")))]
pub use crate::redis_cluster::{RedisClusterConfig, RedisClusterConnectionManager};

#[cfg(feature = "enable_log")]
#[cfg_attr(docsrs, doc(cfg(feature = "enable_log")))]
mod toy_log;
#[cfg(feature = "enable_log")]
#[cfg_attr(docsrs, doc(cfg(feature = "enable_log")))]
pub use crate::toy_log::*;

/// Default namespace
pub const DEFAULT_NAMESPACE: &str = "primary";

/// Buildable component from [`Environment`].
pub trait Buildable: Sized + FromEnvironment {
    /// Target product.
    type Product;

    /// Customize when building.
    type Customizer: Default;

    /// Configuration prefix.
    fn prefix() -> &'static str;

    /// Build product.
    fn build(
        namespace: &str,
        env: &impl Environment,
        customize: Self::Customizer,
    ) -> Result<Self::Product, PropertyError> {
        let config = if namespace.is_empty() || namespace == DEFAULT_NAMESPACE {
            env.require(Self::prefix())
        } else {
            env.require(&format!("{}.{}", Self::prefix(), namespace))
        };
        Self::build_with_key(config?, env, customize)
    }

    /// Build with specified prefix.
    fn build_with_key(
        self,
        env: &impl Environment,
        customize: Self::Customizer,
    ) -> Result<Self::Product, PropertyError>;

    /// List All Keys
    fn list_keys(namespace: &str) -> Vec<(String, bool, Option<String>)> {
        let v = Self::load_keys();
        let prefix = if namespace.is_empty() || namespace == DEFAULT_NAMESPACE {
            Self::prefix().to_string()
        } else {
            format!("{}.{}", Self::prefix(), namespace)
        };
        v.iter()
            .map(|(k, o, v)| {
                (
                    format!("{}.{}", prefix, k),
                    *o,
                    match v {
                        Some(p) => String::from_property(p.clone()).ok(),
                        _ => None,
                    },
                )
            })
            .collect()
    }
}

#[allow(dead_code)]
fn print_keys<T: Buildable>() {
    println!("/// |property|required|default|");
    println!("/// |-|-|-|");
    for (k, r, v) in T::list_keys(DEFAULT_NAMESPACE) {
        println!("/// |{}|{}|{}|", k, r, v.unwrap_or("".to_owned()));
    }
}

/// Factory for build buildable
pub trait Factory: Environment {
    /// Build by namespace
    fn build<T: Buildable>(&self) -> Result<T::Product, PropertyError> {
        self.build_by_namespace::<T>(DEFAULT_NAMESPACE)
    }

    /// Build by namespace
    fn build_by_namespace<T: Buildable>(
        &self,
        namespace: &str,
    ) -> Result<T::Product, PropertyError> {
        self.build_by_namespace_and_customizer::<T>(namespace, T::Customizer::default())
    }

    /// Build by namespace
    fn build_by_customizer<T: Buildable>(
        &self,
        customizer: T::Customizer,
    ) -> Result<T::Product, PropertyError> {
        self.build_by_namespace_and_customizer::<T>(DEFAULT_NAMESPACE, customizer)
    }

    /// Build by namespace and customizer
    fn build_by_namespace_and_customizer<T: Buildable>(
        &self,
        namespace: &str,
        customizer: T::Customizer,
    ) -> Result<T::Product, PropertyError>;
}

impl Factory for Salak {
    fn build_by_namespace_and_customizer<T: Buildable>(
        &self,
        namespace: &str,
        customizer: T::Customizer,
    ) -> Result<T::Product, PropertyError> {
        T::build(namespace, self, customizer)
    }
}