Skip to content

Commit

Permalink
Merge pull request #38 from spiralover/refactor/database
Browse files Browse the repository at this point in the history
refactor: database + redis
  • Loading branch information
Ahmard authored Aug 14, 2024
2 parents 04d06d8 + b2e2ee2 commit bc8c70f
Show file tree
Hide file tree
Showing 16 changed files with 127 additions and 103 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
# Medullah Changelog
medullah-web changelog file

## 0.13.0 (2024-08-14)
* refactor(database): feature is now optional
* fix(readme): broken changelog link
* refactor(id-generator): removed feature
* refactor(redis + cache): scope feature to "feat-redis"

## 0.12.0 (2024-08-14)
* fix(reqwest): scope feature to "feat-reqwest"
* refactor(responder): 'respond_map' now has http status-like names
Expand Down
12 changes: 1 addition & 11 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 9 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "medullah-web"
version = "0.12.0"
version = "0.13.0"
edition = "2021"
license = "MIT"
description = "Micro-Framework Base on Ntex"
Expand All @@ -9,9 +9,10 @@ repository = "https://github.com/spiralover/medullah-web"
publish = ["spiral", "crates-io"]

[features]
default = ["r2d2"]
default = ["feat-ntex"]
feat-database = ["diesel", "r2d2", 'sha2']
feat-rabbitmq = ["lapin", 'deadpool-lapin']
feat-redis = ["redis", 'deadpool-redis']
feat-base64 = ["base64"]
feat-hmac = ["hmac", 'hex']
feat-reqwest = ["reqwest"]
Expand All @@ -21,8 +22,7 @@ feat-crypto = ["rust-argon2", "jsonwebtoken", "subtle"]
feat-regex = ["fancy-regex"]
feat-validator = ["validator"]
feat-templating = ["tera"]
feat-id-generator = ["nanoid"]
feat-ntex = ["feat-database", "ntex", "ntex-cors"]
feat-ntex = ["ntex", "ntex-cors"]
feat-static = ["ntex-files"]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand All @@ -35,14 +35,16 @@ lapin = { version = "2.5.0", optional = true }
deadpool-lapin = { version = "0.12.1", features = ["rt_tokio_1"], optional = true }

# Redis
redis = { version = "0.26.0", default-features = false, features = ["tokio-native-tls-comp", "connection-manager"] }
deadpool-redis = { version = "0.16.0", features = ["rt_tokio_1"] }
redis = { version = "0.26.0", default-features = false, optional = true, features = [
"tokio-native-tls-comp", "connection-manager"
] }
deadpool-redis = { version = "0.16.0", features = ["rt_tokio_1"], optional = true }

toml = { version = "0.8.14" }
uuid = { version = "1.10.0", features = ["v4", "serde"] }
log = { version = "0.4.22" }
serde = { version = "1.0.203", features = ["derive"] }
tokio = { version = "1.39.2", features = ["rt-multi-thread", "macros"] }
tokio = { version = "1.39.2", features = ["rt-multi-thread", "macros", "time"] }
chrono = { version = "0.4.38", features = ["serde"] }
dotenv = { version = "0.15.0" }
env_logger = { version = "0.11.3" }
Expand All @@ -57,7 +59,6 @@ hmac = { version = "0.12.1", optional = true }
fancy-regex = { version = "0.13.0", optional = true }
rust-argon2 = { version = "2.1.0", optional = true }
tera = { version = "1.20.0", optional = true }
nanoid = { version = "0.4.0", optional = true }
ntex = { version = "2.0.3", features = ["tokio"], optional = true }
ntex-files = { version = "2.0.0", optional = true }
ntex-multipart = { version = "2.0.0", optional = true }
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
Medullah is micro-framework built upon [Rust's Ntex](https://ntex.rs).

## ChangeLog
You can find our changelog [here](https://github.com/medullah-org/medullah/blob/master/CHANGELOG.md)
You can find our changelog [here](CHANGELOG.md)
11 changes: 11 additions & 0 deletions src/app_setup.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::{env, fs};
use std::path::Path;
#[allow(unused_imports)]
use std::sync::Arc;

#[cfg(feature = "feat-database")]
Expand All @@ -22,12 +23,15 @@ use crate::helpers::password::Password;
use crate::MEDULLAH;
#[cfg(feature = "feat-rabbitmq")]
use crate::prelude::RabbitMQ;
#[cfg(feature = "feat-redis")]
use crate::prelude::Redis;
#[cfg(feature = "feat-rabbitmq")]
use crate::rabbitmq::conn::establish_rabbit_connection;
#[cfg(feature = "feat-rabbitmq")]
use crate::rabbitmq::conn::establish_rabbit_connection_pool;
#[cfg(feature = "feat-redis")]
use crate::redis::conn::{establish_redis_connection, establish_redis_connection_pool};
#[cfg(feature = "feat-redis")]
use crate::services::cache_service::CacheService;

pub struct MedullahSetup {
Expand All @@ -50,8 +54,11 @@ async fn create_app_state(setup: MedullahSetup) -> MedullahState {
#[cfg(feature = "feat-database")]
let database_pool = establish_database_connection(&env_prefix);

#[cfg(feature = "feat-redis")]
let redis_client = establish_redis_connection(&env_prefix);
#[cfg(feature = "feat-redis")]
let redis_pool = establish_redis_connection_pool(&env_prefix);
#[cfg(feature = "feat-redis")]
let redis = Arc::new(Redis::new(redis_pool.clone()));

// RabbitMQ
Expand Down Expand Up @@ -85,8 +92,11 @@ async fn create_app_state(setup: MedullahSetup) -> MedullahState {
app_public_key: setup.public_key,
app_key: env::var(format!("{}_APP_KEY", env_prefix)).unwrap(),

#[cfg(feature = "feat-redis")]
redis_client: Arc::new(redis_client),
#[cfg(feature = "feat-redis")]
redis_pool,
#[cfg(feature = "feat-redis")]
redis: redis.clone(),
#[cfg(feature = "feat-rabbitmq")]
rabbitmq_client: rabbit_client.clone(),
Expand All @@ -112,6 +122,7 @@ async fn create_app_state(setup: MedullahSetup) -> MedullahState {
mailer_config: make_mailer_config(&env_prefix),

services: AppServices {
#[cfg(feature = "feat-redis")]
cache: Arc::new(CacheService::new(redis)),
},
}
Expand Down
9 changes: 9 additions & 0 deletions src/app_state.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::fmt::{Debug, Formatter};
#[allow(unused_imports)]
use std::sync::Arc;

#[cfg(feature = "feat-redis")]
use redis::Client as RedisClient;
#[cfg(feature = "feat-templating")]
use tera::{Context, Tera};
Expand All @@ -10,7 +12,9 @@ use crate::helpers::jwt::Jwt;
use crate::helpers::password::Password;
#[cfg(feature = "feat-rabbitmq")]
use crate::rabbitmq::RabbitMQ;
#[cfg(feature = "feat-redis")]
use crate::redis::Redis;
#[cfg(feature = "feat-redis")]
use crate::services::cache_service::CacheService;

#[derive(Clone)]
Expand All @@ -28,8 +32,11 @@ pub struct MedullahState {
#[cfg(feature = "feat-templating")]
pub(crate) tera: Tera,

#[cfg(feature = "feat-redis")]
pub(crate) redis_client: Arc<RedisClient>,
#[cfg(feature = "feat-redis")]
pub(crate) redis_pool: deadpool_redis::Pool,
#[cfg(feature = "feat-redis")]
pub(crate) redis: Arc<Redis>,
#[cfg(feature = "feat-rabbitmq")]
pub rabbitmq_client: Arc<lapin::Connection>,
Expand Down Expand Up @@ -80,6 +87,7 @@ pub struct AppHelpers {

#[derive(Clone)]
pub struct AppServices {
#[cfg(feature = "feat-redis")]
pub cache: Arc<CacheService>,
}

Expand All @@ -89,6 +97,7 @@ impl MedullahState {
&self.database
}

#[cfg(feature = "feat-redis")]
pub fn redis(&self) -> Arc<Redis> {
self.redis.clone()
}
Expand Down
15 changes: 15 additions & 0 deletions src/enums/app_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ pub enum AppMessage {
ChronoParseError(chrono::ParseError),
#[cfg(feature = "feat-rabbitmq")]
RabbitmqError(lapin::Error),
#[cfg(feature = "feat-redis")]
RedisError(redis::RedisError),
#[cfg(feature = "feat-redis")]
RedisPoolError(deadpool::managed::PoolError<redis::RedisError>),
#[cfg(feature = "feat-rabbitmq")]
RmqPoolError(deadpool::managed::PoolError<lapin::Error>),
Expand All @@ -73,6 +75,7 @@ pub enum AppMessage {
BlockingNtexIoError(BlockingError<io::Error>),
#[cfg(feature = "feat-ntex")]
BlockingErrorCanceled,
#[cfg(feature = "feat-database")]
R2d2Error(r2d2::Error),
#[cfg(feature = "feat-database")]
DatabaseError(diesel::result::Error),
Expand All @@ -93,6 +96,7 @@ fn get_message(status: &AppMessage) -> String {
}
AppMessage::Redirect(url) => format!("Redirecting to '{}'...", url),
AppMessage::EntityNotFound(entity) => format!("Such {} does not exits", entity),
#[cfg(feature = "feat-database")]
AppMessage::R2d2Error(error) => error.to_string(),
#[cfg(feature = "feat-rabbitmq")]
AppMessage::RmqPoolError(error) => error.to_string(),
Expand All @@ -106,7 +110,9 @@ fn get_message(status: &AppMessage) -> String {
AppMessage::SerdeError500(error) => error.to_string(),
#[cfg(feature = "feat-rabbitmq")]
AppMessage::RabbitmqError(error) => error.to_string(),
#[cfg(feature = "feat-redis")]
AppMessage::RedisError(error) => error.to_string(),
#[cfg(feature = "feat-redis")]
AppMessage::RedisPoolError(error) => error.to_string(),
AppMessage::JoinError(error) => error.to_string(),
#[cfg(feature = "reqwest")]
Expand Down Expand Up @@ -189,6 +195,7 @@ fn send_response(message: &AppMessage) -> ntex::web::HttpResponse {
log::error!("IO Error: {}", message);
Responder::internal_server_error()
}
#[cfg(feature = "feat-database")]
AppMessage::R2d2Error(message) => {
log::error!("R2d2 Error: {}", message);
Responder::internal_server_error()
Expand All @@ -208,10 +215,12 @@ fn send_response(message: &AppMessage) -> ntex::web::HttpResponse {
log::error!("Rabbitmq Error: {}", message);
Responder::internal_server_error()
}
#[cfg(feature = "feat-redis")]
AppMessage::RedisError(message) => {
log::error!("Redis Error: {}", message);
Responder::internal_server_error()
}
#[cfg(feature = "feat-redis")]
AppMessage::RedisPoolError(message) => {
log::error!("Redis Pool Error: {}", message);
Responder::internal_server_error()
Expand Down Expand Up @@ -296,6 +305,7 @@ fn send_response(message: &AppMessage) -> ntex::web::HttpResponse {
Some(String::from("Validation Error")),
StatusCode::BAD_REQUEST,
),
#[cfg(feature = "feat-database")]
AppMessage::DatabaseError(err) => match err {
diesel::result::Error::NotFound => {
Responder::not_found_message("Such entity not found")
Expand Down Expand Up @@ -323,12 +333,14 @@ pub fn get_status_code(status: &AppMessage) -> StatusCode {
AppMessage::WarningMessage(_msg) => StatusCode::BAD_REQUEST,
AppMessage::WarningMessageString(_msg) => StatusCode::BAD_REQUEST,
AppMessage::EntityNotFound(_msg) => StatusCode::NOT_FOUND,
#[cfg(feature = "feat-database")]
AppMessage::DatabaseError(diesel::result::Error::NotFound) => StatusCode::NOT_FOUND,
AppMessage::HttpClientError(_msg, _code) => StatusCode::INTERNAL_SERVER_ERROR,
#[cfg(feature = "feat-crypto")]
AppMessage::JwtError(_) => StatusCode::INTERNAL_SERVER_ERROR,
#[cfg(feature = "feat-crypto")]
AppMessage::ArgonError(_) => StatusCode::INTERNAL_SERVER_ERROR,
#[cfg(feature = "feat-database")]
AppMessage::R2d2Error(_) => StatusCode::INTERNAL_SERVER_ERROR,
#[cfg(feature = "feat-rabbitmq")]
AppMessage::RmqPoolError(_) => StatusCode::INTERNAL_SERVER_ERROR,
Expand All @@ -342,6 +354,7 @@ pub fn get_status_code(status: &AppMessage) -> StatusCode {
AppMessage::ReqwestResponseError(_msg) => StatusCode::INTERNAL_SERVER_ERROR,
#[cfg(feature = "feat-validator")]
AppMessage::FormValidationError(_msg) => StatusCode::BAD_REQUEST,
#[cfg(feature = "feat-redis")]
AppMessage::RedisError(_msg) => StatusCode::INTERNAL_SERVER_ERROR,
#[cfg(feature = "feat-rabbitmq")]
AppMessage::RabbitmqError(_msg) => StatusCode::INTERNAL_SERVER_ERROR,
Expand Down Expand Up @@ -417,6 +430,7 @@ impl From<ntex::http::error::PayloadError> for AppMessage {
}
}

#[cfg(feature = "feat-database")]
impl From<r2d2::Error> for AppMessage {
fn from(value: r2d2::Error) -> Self {
AppMessage::R2d2Error(value)
Expand Down Expand Up @@ -457,6 +471,7 @@ impl From<lapin::Error> for AppMessage {
}
}

#[cfg(feature = "feat-redis")]
impl From<redis::RedisError> for AppMessage {
fn from(value: redis::RedisError) -> Self {
AppMessage::RedisError(value)
Expand Down
17 changes: 0 additions & 17 deletions src/helpers/id_generator.rs

This file was deleted.

2 changes: 0 additions & 2 deletions src/helpers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ pub mod fs;
pub mod hmac;
#[cfg(feature = "feat-ntex")]
pub mod http;
#[cfg(feature = "feat-id-generator")]
pub mod id_generator;
pub mod json;
#[cfg(feature = "feat-ntex")]
pub mod json_message;
Expand Down
12 changes: 8 additions & 4 deletions src/helpers/once_lock.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
#[allow(unused_imports)]
use std::sync::{Arc, OnceLock};

#[cfg(feature = "feat-database")]
use diesel::PgConnection;
#[cfg(feature = "feat-database")]
use diesel::r2d2::ConnectionManager;
use redis::Client;

use crate::app_state::MedullahState;
#[cfg(feature = "feat-database")]
use crate::database::DatabaseConnectionHelper;
use crate::MEDULLAH;
use crate::redis::Redis;
#[cfg(feature = "feat-redis")]
use crate::services::cache_service::CacheService;

pub trait OnceLockHelper<'a> {
Expand All @@ -27,15 +27,18 @@ pub trait OnceLockHelper<'a> {
MEDULLAH.get().unwrap().database()
}

fn redis_client(&self) -> Arc<Client> {
#[cfg(feature = "feat-redis")]
fn redis_client(&self) -> Arc<redis::Client> {
Arc::clone(&self.app().redis_client)
}

#[cfg(feature = "feat-redis")]
fn redis_pool(&self) -> deadpool_redis::Pool {
self.app().redis_pool.clone()
}

fn redis(&self) -> &Redis {
#[cfg(feature = "feat-redis")]
fn redis(&self) -> &crate::redis::Redis {
&MEDULLAH.get().unwrap().redis
}

Expand All @@ -54,6 +57,7 @@ pub trait OnceLockHelper<'a> {
Arc::clone(&self.app().rabbitmq)
}

#[cfg(feature = "feat-redis")]
fn cache(&self) -> &CacheService {
&MEDULLAH.get().unwrap().services.cache
}
Expand Down
Loading

0 comments on commit bc8c70f

Please sign in to comment.