Skip to content

Commit

Permalink
add comments
Browse files Browse the repository at this point in the history
  • Loading branch information
4t145 committed Oct 17, 2023
1 parent 83e0670 commit d4235e6
Show file tree
Hide file tree
Showing 21 changed files with 273 additions and 95 deletions.
12 changes: 10 additions & 2 deletions tardis/src/basic/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,9 +206,11 @@ impl TardisField {
/// ```
pub type TrimString = Mapped<String, Trim>;

// This function is `non_snake_case` for being compatible with the old version
/// This function is `non_snake_case` for being compatible with the old version
/// # Deprecated
/// Please use `TrimString::new` instead
#[allow(non_snake_case)]
#[deprecated(since = "1.0.0", note = "Please use `TrimString::new` instead")]
// #[deprecated(since = "1.0.0", note = "Please use `TrimString::new` instead")]
pub fn TrimString(string: impl Into<String>) -> TrimString {
TrimString::new(string.into())
}
Expand All @@ -225,6 +227,12 @@ impl AsRef<str> for TrimString {
}
}

impl TrimString {
pub fn as_str(&self) -> &str {
self.deref()
}
}

pub type TrimStr<'a> = Mapped<&'a str, Trim>;
pub type Base64EncodedString = Mapped<String, Base64Encode>;
pub type Base64DecodedString = Mapped<String, Base64Decode>;
11 changes: 10 additions & 1 deletion tardis/src/basic/tracing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,20 @@ use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::EnvFilter;
#[allow(unused_imports)]
use tracing_subscriber::{fmt::Layer as FmtLayer, layer::SubscriberExt, prelude::*, reload::Layer as ReloadLayer, Registry};

/// # Tardis Tracing
/// Tardis tracing is a wrapper of tracing-subscriber. It provides configurable layers as runtime.
///
/// To initialize the tracing, use [TardisTracingInitializer].
///
/// To update config at runtime, use method [`TardisTracing::update_config`].
///
#[derive(Default)]
pub struct TardisTracing<C = LogConfig> {
configer: Vec<Box<dyn Fn(&C) -> TardisResult<()> + Send + Sync>>,
}

// create a configurable layer, recieve a layer and a configer, return a reload layer and a config function
fn create_configurable_layer<L, S, C>(layer: L, configer: impl Fn(&C) -> TardisResult<L> + Send + Sync) -> TardisResult<(ReloadLayer<L, S>, impl Fn(&C) -> TardisResult<()>)> {
let (reload_layer, reload_handle) = ReloadLayer::new(layer);
let config_layer_fn = move |conf: &C| -> TardisResult<()> {
Expand Down Expand Up @@ -117,7 +126,7 @@ impl TardisTracing<LogConfig> {
}

/// Update tardis tracing config, and this will reload all configurable layers
///
/// LogConfig
pub fn update_config(&self, config: &LogConfig) -> TardisResult<()> {
for configer in &self.configer {
(configer)(config)?
Expand Down
9 changes: 8 additions & 1 deletion tardis/src/config/config_dto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,14 +189,21 @@ impl Default for AppConfig {
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(default)]
pub struct ConfCenterConfig {
/// kind of config center / 配置中心的类型
pub kind: String,
/// url of config center / 配置中心的地址
pub url: String,
/// username of config center / 配置中心的用户名
pub username: String,
/// password of config center / 配置中心的密码
pub password: String,
/// group of config / 配置的分组
pub group: Option<String>,
/// format of config / 配置的格式
pub format: Option<String>,
/// namespace of config / 配置的命名空间
pub namespace: Option<String>,
/// config change polling interval, in milliseconds / 配置变更轮询间隔,单位毫秒
/// config change polling interval, in milliseconds / 配置变更轮询间隔,单位毫秒,默认5000ms
pub config_change_polling_interval: Option<u64>,
}

Expand Down
3 changes: 3 additions & 0 deletions tardis/src/config/config_dto/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,14 @@ pub use os::*;
pub struct TardisComponentConfig<T, C: Default = ()> {
#[serde(flatten)]
#[builder(default, setter(into))]
/// common config for all modules
common: C,
#[serde(flatten)]
/// the default module config
pub default: T,
#[builder(default, setter(into))]
#[serde(default = "Default::default")]
/// submodule configs
pub modules: HashMap<String, T>,
}

Expand Down
6 changes: 6 additions & 0 deletions tardis/src/config/config_dto/component/mail.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,22 @@ use typed_builder::TypedBuilder;
///
#[derive(Debug, Serialize, Deserialize, Clone, TypedBuilder)]
pub struct MailModuleConfig {
/// SMTP host
#[builder(setter(into))]
pub smtp_host: String,
/// SMTP port, default by 587
#[builder(default = 587)]
pub smtp_port: u16,
/// SMTP username
#[builder(setter(into))]
pub smtp_username: String,
/// SMTP password
#[builder(setter(into))]
pub smtp_password: String,
/// default from address
#[builder(setter(into))]
pub default_from: String,
/// weather to use STARTTLS, default by false
#[builder(default = false)]
pub starttls: bool,
}
8 changes: 8 additions & 0 deletions tardis/src/config/config_dto/log.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use tracing_subscriber::filter::Directive;
use typed_builder::TypedBuilder;
Expand Down Expand Up @@ -26,18 +28,24 @@ pub use tracing_appender::*;
pub struct LogConfig {
#[builder(default = "info".parse::<Directive>().expect(""), setter(into))]
#[serde(deserialize_with = "deserialize_directive", serialize_with = "serialize_directive")]
/// the defualt log level
pub level: Directive,
#[builder(default, setter(into))]
#[serde(deserialize_with = "deserialize_directives", serialize_with = "serialize_directives")]
/// tracing filtering directive, e.g. `tardis=debug,sqlx=off`
pub directives: Vec<Directive>,
#[cfg(feature = "tracing")]
#[builder(default)]
/// open telemetry tracing config
pub tracing: TracingConfig,
#[cfg(feature = "tracing-appender")]
#[builder(default)]
/// tracing appender config
/// a `None` value means no file output
pub tracing_appender: Option<TracingAppenderConfig>,
/// extension config for custom tracing layers
#[builder(default)]
pub ext: HashMap<String, crate::serde_json::Value>,
}

fn serialize_directive<S>(value: &Directive, serializer: S) -> Result<S::Ok, S::Error>
Expand Down
14 changes: 13 additions & 1 deletion tardis/src/crypto/crypto_aead.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,18 @@ use rand::rngs::ThreadRng;
/// Aead (Authenticated Encryption with Associated Data)
///
/// This part includes aead encryption and decryption, and cbc/ecb encryption and decryption.
pub struct TardisCryptoAead {}
///
/// # Example
/// ```ignore
/// use tardis::crypto::crypto_aead::TardisCryptoAead;
/// use tardis::crypto::crypto_aead::algorithm::Aes128;
///
/// TardisCryptoAead.encrypt_cbc::<Aes128>(message, iv, key);
/// TardisCryptoAead.decrypt_cbc::<Aes128>(message, iv, key);
/// ```
///
///
pub struct TardisCryptoAead;

impl TardisCryptoAead {
/// Encrypy with cbc,
Expand Down Expand Up @@ -111,6 +122,7 @@ impl TardisCryptoAead {
}
}

/// algorithms of aead
pub mod algorithm {
pub use aes::{Aes128, Aes192, Aes256};
pub use aes_gcm::{Aes128Gcm, Aes256Gcm};
Expand Down
28 changes: 18 additions & 10 deletions tardis/src/crypto/crypto_base64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,25 @@ use crate::basic::error::TardisError;
use crate::basic::result::TardisResult;
use crate::utils::mapper::{Base64Decode, Base64Encode, Mapper};
use crate::TardisFuns;

/// # TardisCryptoBase64
/// Encode and decode with base64.
///
pub struct TardisCryptoBase64;

impl TardisCryptoBase64 {
pub fn decode(&self, data: impl AsRef<[u8]>) -> TardisResult<String> {
match general_purpose::STANDARD.decode(data) {
Ok(result) => Ok(String::from_utf8(result)?),
Err(error) => Err(TardisError::format_error(
&format!("[Tardis.Crypto] Base64 decode error:{error}"),
"406-tardis-crypto-base64-decode-error",
)),
}
/// decode from base64 to a utf8 string
pub fn decode_to_string(&self, data: impl AsRef<[u8]>) -> TardisResult<String> {
let decoded = self.decode(data)?;
let code = String::from_utf8(decoded)?;
Ok(code)
}

/// decode from base64, to raw binary data
pub fn decode(&self, data: impl AsRef<[u8]>) -> TardisResult<Vec<u8>> {
general_purpose::STANDARD
.decode(data)
.map_err(|error| TardisError::format_error(&format!("[Tardis.Crypto] Base64 decode error:{error}"), "406-tardis-crypto-base64-decode-error"))
}

pub fn encode(&self, data: impl AsRef<[u8]>) -> String {
Expand Down Expand Up @@ -52,13 +60,13 @@ impl<'a> Mapper<&'a str> for Base64Encode {
impl Mapper<String> for Base64Decode {
type Output = TardisResult<String>;
fn map(value: String) -> TardisResult<String> {
TardisCryptoBase64.decode(value)
TardisCryptoBase64.decode_to_string(value)
}
}

impl<'a> Mapper<&'a str> for Base64Decode {
type Output = TardisResult<String>;
fn map(value: &'a str) -> TardisResult<String> {
TardisCryptoBase64.decode(value)
TardisCryptoBase64.decode_to_string(value)
}
}
20 changes: 20 additions & 0 deletions tardis/src/crypto/crypto_digest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use digest::KeyInit;

use output::*;
pub struct TardisCryptoDigest;

/// algorithms for digest
pub mod algorithm {
pub use digest::Digest;
pub use hmac::{Hmac, Mac};
Expand All @@ -27,6 +29,8 @@ pub mod output {

use crate::utils::mapper::Mapper;

/// Mapper digest output into hexcode
#[derive(Default, Debug)]
pub struct HexCodeMapper<A: digest::Digest>(PhantomData<A>);
impl<A: digest::Digest> Mapper<digest::Output<A>> for HexCodeMapper<A> {
type Output = String;
Expand All @@ -35,6 +39,8 @@ pub mod output {
}
}

/// Mapper digest output into bytes
#[derive(Default, Debug)]
pub struct BytesMapper<A: digest::Digest>(PhantomData<A>);
impl<A: digest::Digest> Mapper<digest::Output<A>> for BytesMapper<A> {
type Output = Vec<u8>;
Expand All @@ -43,6 +49,7 @@ pub mod output {
}
}
}

/// Digest handle / 摘要处理
///
/// # Examples
Expand Down Expand Up @@ -93,6 +100,11 @@ impl TardisCryptoDigest {
}

/// Digest the data, and map the output into hexcode by default.
///
/// # Examples
/// ```ignore
/// TardisCryptoDigest.digest::<algorithm::Sha1>("测试").unwrap();
/// ```
pub fn digest<A: digest::Digest>(&self, data: impl AsRef<[u8]>) -> TardisResult<String> {
self.digest_hex::<A>(data)
}
Expand All @@ -108,6 +120,12 @@ impl TardisCryptoDigest {
}

/// Digest the data, and map the output into a specific type which determined by `M`.
///
/// # Examples
/// ```ignore
/// use tardis::crypto::crypto_digest::{TardisCryptoDigest, algorithm::Sha1, output::HexCodeMapper};
/// let hexcode = TardisCryptoDigest.digest_as::<Sha1, HexCodeMapper<Sha1>>("测试").unwrap();
/// ```
pub fn digest_as<A: digest::Digest, M: Mapper<digest::Output<A>>>(&self, data: impl AsRef<[u8]>) -> TardisResult<M::Output> {
self.digest_iter_as::<A, M, _>(Some(data))
}
Expand All @@ -129,10 +147,12 @@ impl TardisCryptoDigest {
Ok(out)
}

/// Digest the data, and map the output into hexcode by default.
pub fn digest_hmac<A: Mac + KeyInit>(&self, data: impl AsRef<[u8]>, key: impl AsRef<[u8]>) -> TardisResult<String> {
self.digest_hmac_raw::<A>(data, key).map(hex::encode)
}

/// Digest the data
pub fn digest_hmac_raw<A: Mac + KeyInit>(&self, data: impl AsRef<[u8]>, key: impl AsRef<[u8]>) -> TardisResult<Vec<u8>> {
let mut hmac = <A as Mac>::new_from_slice(key.as_ref()).map_err(|_| TardisError::internal_error("hmac key with invalid length", "406-tardis-crypto-hmac-key-invalid"))?;
hmac.update(data.as_ref());
Expand Down
3 changes: 3 additions & 0 deletions tardis/src/crypto/crypto_hex.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use crate::basic::{error::TardisError, result::TardisResult};

/// # TardisCryptoHex
/// Encode and decode with hex.
pub struct TardisCryptoHex;

impl TardisCryptoHex {
Expand Down
5 changes: 5 additions & 0 deletions tardis/src/crypto/crypto_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ macro_rules! gen_rand_n_hex {
$(
paste! {
#[inline]
#[doc = "generate a random hex string with length of " $N "."]
pub fn [<rand_ $N _hex>](&self) -> String {
self.rand_n_hex::<$N>()
}
Expand All @@ -21,6 +22,7 @@ macro_rules! gen_rand_n_bytes {
$(
paste! {
#[inline]
#[doc = "generate random " $N " bytes."]
pub fn [<rand_ $N _bytes>](&self) -> [u8; $N] {
self.rand_n_bytes::<$N>()
}
Expand All @@ -29,11 +31,14 @@ macro_rules! gen_rand_n_bytes {
};
}
impl TardisCryptoKey {
/// generate a random hex string with length of N
pub fn rand_n_hex<const N: usize>(&self) -> String {
let mut key = vec![0; N / 2];
rand::rngs::OsRng.fill_bytes(&mut key);
hex::encode(key)
}

/// generate random N bytes
pub fn rand_n_bytes<const N: usize>(&self) -> [u8; N] {
let mut key = [0; N];
rand::rngs::OsRng.fill_bytes(&mut key);
Expand Down
Loading

0 comments on commit d4235e6

Please sign in to comment.