Skip to content

Commit

Permalink
Code optimization.
Browse files Browse the repository at this point in the history
1. Use better_default crate to optimize the implementation of the
   Default feature of the struct.
2. Add macros rv_error_response and rv_error_response_status.
  • Loading branch information
wa5i committed Sep 18, 2024
1 parent 4907518 commit e388354
Show file tree
Hide file tree
Showing 21 changed files with 107 additions and 329 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ derive_more = "0.99.17"
dashmap = "5.5"
tokio = "1.38"
ctor = "0.2.8"
better_default = "1.0.5"

# optional dependencies
openssl = { version = "0.10.64", optional = true }
Expand Down
20 changes: 20 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,12 @@ pub enum RvError {
source: actix_web::http::header::ToStrError,
},

#[error("Some url error happened, {:?}", .source)]
UrlError {
#[from]
source: url::ParseError,
},

/// Database Errors Begin
///
#[error("Database type is not support now. Please try postgressql or mysql again.")]
Expand Down Expand Up @@ -391,3 +397,17 @@ impl<T> From<PoisonError<RwLockReadGuard<'_, T>>> for RvError {
RvError::ErrRwLockReadPoison
}
}

#[macro_export]
macro_rules! rv_error_response {
($message:expr) => {
RvError::ErrResponse($message.to_string())
};
}

#[macro_export]
macro_rules! rv_error_response_status {
($status:expr, $message:expr) => {
RvError::ErrResponseStatus($status, $message.to_string())
};
}
8 changes: 1 addition & 7 deletions src/http/logical.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ struct Auth {
renewable: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct LogicalResponse {
renewable: bool,
lease_id: String,
Expand All @@ -39,12 +39,6 @@ struct LogicalResponse {
data: HashMap<String, Value>,
}

impl Default for LogicalResponse {
fn default() -> Self {
Self { renewable: false, lease_id: String::new(), lease_duration: 0, auth: None, data: HashMap::new() }
}
}

async fn logical_request_handler(
req: HttpRequest,
mut body: web::Bytes,
Expand Down
15 changes: 1 addition & 14 deletions src/logical/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};

use super::lease::Lease;

#[derive(Debug, Clone, Serialize, Deserialize, Deref, DerefMut)]
#[derive(Debug, Clone, Default, Serialize, Deserialize, Deref, DerefMut)]
pub struct Auth {
#[deref]
#[deref_mut]
Expand All @@ -18,16 +18,3 @@ pub struct Auth {
pub internal_data: HashMap<String, String>,
pub metadata: HashMap<String, String>,
}

impl Default for Auth {
fn default() -> Self {
Self {
lease: Lease::default(),
client_token: String::new(),
display_name: String::new(),
policies: Vec::new(),
internal_data: HashMap::new(),
metadata: HashMap::new(),
}
}
}
7 changes: 1 addition & 6 deletions src/logical/connection.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
use openssl::x509::X509;

#[derive(Default)]
pub struct Connection {
pub peer_addr: String,
pub peer_tls_cert: Option<Vec<X509>>,
}

impl Default for Connection {
fn default() -> Self {
Self { peer_addr: String::new(), peer_tls_cert: None }
}
}
17 changes: 4 additions & 13 deletions src/logical/lease.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,23 @@
use std::time::{Duration, SystemTime};

use serde::{Deserialize, Serialize};
use better_default::Default;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Lease {
#[serde(rename = "lease")]
pub ttl: Duration,
#[serde(skip)]
pub max_ttl: Duration,
#[default(true)]
pub renewable: bool,
#[serde(skip)]
pub increment: Duration,
#[serde(skip)]
#[default(Some(SystemTime::now()))]
pub issue_time: Option<SystemTime>,
}

impl Default for Lease {
fn default() -> Self {
Self {
ttl: Duration::new(0, 0),
max_ttl: Duration::new(0, 0),
renewable: true,
increment: Duration::new(0, 0),
issue_time: Some(SystemTime::now()),
}
}
}

impl Lease {
pub fn new() -> Self {
Self { ..Default::default() }
Expand Down
24 changes: 3 additions & 21 deletions src/logical/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::{collections::HashMap, sync::Arc};

use serde_json::{Map, Value};
use tokio::task::JoinHandle;
use better_default::Default;

use super::{Operation, Path};
use crate::{
Expand All @@ -10,9 +11,11 @@ use crate::{
storage::{Storage, StorageEntry},
};

#[derive(Default)]
pub struct Request {
pub id: String,
pub name: String,
#[default(Operation::Read)]
pub operation: Operation,
pub path: String,
pub match_path: Option<Arc<Path>>,
Expand All @@ -27,27 +30,6 @@ pub struct Request {
pub tasks: Vec<JoinHandle<()>>,
}

impl Default for Request {
fn default() -> Self {
Request {
id: String::new(),
name: String::new(),
operation: Operation::Read,
path: String::new(),
match_path: None,
headers: None,
body: None,
data: None,
client_token: String::new(),
storage: None,
connection: None,
secret: None,
auth: None,
tasks: Vec::new(),
}
}
}

impl Request {
pub fn new(path: &str) -> Self {
Self { path: path.to_string(), ..Default::default() }
Expand Down
17 changes: 2 additions & 15 deletions src/logical/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::collections::HashMap;
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use better_default::Default;

use crate::{
errors::RvError,
Expand All @@ -15,7 +16,7 @@ lazy_static! {
static ref HTTP_STATUS_CODE: &'static str = "http_status_code";
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Response {
#[serde(default)]
pub request_id: String,
Expand All @@ -30,20 +31,6 @@ pub struct Response {
pub warnings: Vec<String>,
}

impl Default for Response {
fn default() -> Self {
Response {
request_id: String::new(),
headers: None,
data: None,
auth: None,
secret: None,
redirect: String::new(),
warnings: Vec::new(),
}
}
}

impl Response {
pub fn new() -> Self {
Self { ..Default::default() }
Expand Down
37 changes: 7 additions & 30 deletions src/modules/auth/expiration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use delay_timer::prelude::*;
use derive_more::Deref;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use better_default::Default;

use super::TokenStore;
use crate::{
Expand Down Expand Up @@ -44,56 +45,32 @@ struct LeaseEntry {
pub expire_time: SystemTime,
}

#[derive(Default)]
pub struct ExpirationTask {
pub last_task_id: u64,
pub task_id_map: HashMap<String, u64>,
pub task_id_remove_pending: Vec<u64>,
pub task_timer: DelayTimer,
}

#[derive(Default)]
pub struct ExpirationManagerInner {
pub router: Option<Arc<Router>>,
pub id_view: Option<Arc<BarrierView>>,
pub token_view: Option<Arc<BarrierView>>,
#[default(Arc::new(RwLock::new(None)))]
pub token_store: Arc<RwLock<Option<Arc<TokenStore>>>>,
#[default(RwLock::new(ExpirationTask::default()))]
pub task: RwLock<ExpirationTask>,
}

#[derive(Deref)]
#[derive(Default, Deref)]
pub struct ExpirationManager {
#[deref]
#[default(Arc::new(ExpirationManagerInner::default()))]
pub inner: Arc<ExpirationManagerInner>,
}

impl Default for ExpirationTask {
fn default() -> Self {
Self {
last_task_id: 0,
task_id_map: HashMap::new(),
task_id_remove_pending: Vec::new(),
task_timer: DelayTimerBuilder::default().build(),
}
}
}

impl Default for ExpirationManagerInner {
fn default() -> Self {
Self {
router: None,
id_view: None,
token_view: None,
token_store: Arc::new(RwLock::new(None)),
task: RwLock::new(ExpirationTask::default()),
}
}
}

impl Default for ExpirationManager {
fn default() -> Self {
Self { inner: Arc::new(ExpirationManagerInner::default()) }
}
}

impl LeaseEntry {
fn renewable(&self) -> bool {
let now = SystemTime::now();
Expand Down
39 changes: 3 additions & 36 deletions src/modules/auth/token_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ struct TokenReqData {
renewable: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TokenEntry {
pub id: String,
pub parent: String,
Expand All @@ -72,53 +72,20 @@ pub struct TokenEntry {
pub ttl: u64,
}

#[derive(Default)]
pub struct TokenStoreInner {
pub router: Arc<Router>,
pub view: Option<Arc<dyn Storage + Send + Sync>>,
pub salt: String,
pub expiration: Arc<ExpirationManager>,
}

#[derive(Deref)]
#[derive(Default, Deref)]
pub struct TokenStore {
#[deref]
pub inner: Arc<TokenStoreInner>,
}

impl Default for TokenEntry {
fn default() -> Self {
Self {
id: String::new(),
parent: String::new(),
policies: Vec::new(),
path: String::new(),
meta: HashMap::new(),
display_name: String::new(),
num_uses: 0,
ttl: 0,
}
}
}

impl Default for TokenStoreInner {
fn default() -> Self {
Self {
router: Arc::new(Router::new()),
view: None,
salt: String::new(),
expiration: Arc::new(ExpirationManager::default()),
}
}
}

impl Default for TokenStore {
fn default() -> Self {
let inner = TokenStoreInner { ..TokenStoreInner::default() };

Self { inner: Arc::new(inner) }
}
}

impl TokenStore {
pub fn new(core: &Core, expiration: Arc<ExpirationManager>) -> Result<TokenStore, RvError> {
if core.system_view.is_none() {
Expand Down
Loading

0 comments on commit e388354

Please sign in to comment.