refactor: Reorganize charging and errors modules into proper directory structure

- Move charging module files into charging/ directory (types.rs, engine.rs, credit_management.rs, rating_billing.rs)
- Move error module files into errors/ directory (types.rs, helpers.rs)
- Create mod.rs files for charging and errors modules with simplified exports
- Update import paths to use super:: for intra-module references
- Remove charging_new/errors_new aliases and use charging/errors directly
- Simplify module
This commit is contained in:
nutcas3
2026-04-14 16:29:27 +03:00
parent c1f408c789
commit c63c92245f
17 changed files with 199 additions and 209 deletions
+3 -17
View File
@@ -1,20 +1,6 @@
pub mod charging_types;
pub mod charging_engine;
pub mod types;
pub mod engine;
pub mod credit_management;
pub mod rating_billing;
pub mod monitoring_sync;
pub mod monitoring_types;
pub mod sync_operations;
pub mod monitoring;
pub use charging_types::{
SubscriberAccount, AccountStatus, UsageEvent, UsageType, RatingPlan,
ChargingSession, SessionStatus, ChargingRule, Condition, Action
};
pub use charging_engine::ChargingEngine;
pub use monitoring::{SystemStats, HealthStatus};
pub use monitoring_types::{PerformanceMetrics, ErrorStats};
pub use crate::errors::{ChargingError, ChargingResult, ErrorContext};
pub use engine::ChargingEngine;
@@ -1,7 +1,7 @@
use redis::AsyncCommands;
use tracing::{info, warn, error, debug};
use crate::charging_types::{SubscriberAccount, UsageEvent};
use super::types::{SubscriberAccount, UsageEvent};
use crate::errors::{ChargingError, ChargingResult, ErrorContext};
impl super::ChargingEngine {
@@ -1,7 +1,7 @@
use std::collections::HashMap;
use std::time::Duration;
use crate::charging_types::{RatingPlan, SubscriberAccount};
use super::types::{RatingPlan, SubscriberAccount};
use crate::errors::{ChargingError, ChargingResult, ErrorContext};
pub struct ChargingEngine {
+6
View File
@@ -0,0 +1,6 @@
pub mod types;
pub mod engine;
pub mod credit_management;
pub mod rating_billing;
pub use engine::ChargingEngine;
@@ -1,7 +1,7 @@
use chrono::Utc;
use tracing::{info, debug, warn};
use crate::charging_types::{UsageEvent, UsageType, RatingPlan};
use super::types::{UsageEvent, UsageType, RatingPlan};
use crate::errors::{ChargingError, ChargingResult, ErrorContext};
impl super::ChargingEngine {
+2 -5
View File
@@ -1,5 +1,2 @@
pub mod error_types;
pub mod error_helpers;
pub use error_types::{ChargingError};
pub use error_helpers::{ChargingResult, ErrorContext, validate_ip, validate_bytes, validate_imsi, validate_session_id, validate_amount, log_error};
pub mod types;
pub mod helpers;
+2
View File
@@ -0,0 +1,2 @@
pub mod types;
pub mod helpers;
+3 -13
View File
@@ -1,18 +1,8 @@
mod api;
mod charging_new as charging;
mod errors_new as errors;
mod models;
// Include the new modular components
mod charging_types;
mod charging_engine;
mod credit_management;
mod rating_billing;
mod monitoring_sync;
mod sync_operations;
mod charging;
mod monitoring;
mod error_types;
mod error_helpers;
mod errors;
mod models;
use anyhow::Result;
use std::sync::Arc;
+4 -171
View File
@@ -1,171 +1,4 @@
use tracing::{info, debug};
use std::time::SystemTime;
use crate::errors::{ChargingError, ChargingResult, ErrorContext};
impl super::ChargingEngine {
pub async fn get_system_statistics(&self) -> ChargingResult<SystemStats> {
let mut conn = self.redis_client.get_async_connection().await
.context("Failed to get Redis connection")?;
let active_sessions: u64 = conn.get("stats:active_sessions").await.unwrap_or(0);
let total_accounts: u64 = conn.keys("account:*").await.unwrap_or_default().len() as u64;
let blocked_users: u64 = conn.keys("block:*").await.unwrap_or_default().len() as u64;
let low_balance_alerts: u64 = conn.keys("alert:low_balance:*").await.unwrap_or_default().len() as u64;
let stats = SystemStats {
active_sessions,
total_accounts,
blocked_users,
low_balance_alerts,
uptime: self.get_uptime().await?,
};
Ok(stats)
}
async fn get_uptime(&self) -> ChargingResult<u64> {
// This would track the actual uptime in a real implementation
// For now, return a placeholder
Ok(SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_secs())
}
pub async fn health_check(&self) -> ChargingResult<HealthStatus> {
let mut conn = self.redis_client.get_async_connection().await
.context("Failed to get Redis connection")?;
// Test Redis connection
let _: String = conn.get("health_check").await.unwrap_or_else(|_| "ok".to_string());
let status = HealthStatus {
redis_connected: true,
active_sync: true,
last_sync: chrono::Utc::now(),
memory_usage: self.get_memory_usage().await?,
};
Ok(status)
}
async fn get_memory_usage(&self) -> ChargingResult<u64> {
// This would get actual memory usage in a real implementation
// For now, return a placeholder
Ok(50_000_000) // 50MB placeholder
}
pub async fn get_performance_metrics(&self) -> ChargingResult<PerformanceMetrics> {
let mut conn = self.redis_client.get_async_connection().await
.context("Failed to get Redis connection")?;
// Get Redis info
let info: String = redis::cmd("INFO").query_async(&mut conn).await.unwrap_or_default();
// Parse Redis info for metrics (simplified)
let connected_clients = self.extract_metric(&info, "connected_clients");
let used_memory = self.extract_metric(&info, "used_memory");
let total_commands_processed = self.extract_metric(&info, "total_commands_processed");
let metrics = PerformanceMetrics {
connected_clients,
used_memory,
total_commands_processed,
requests_per_second: self.calculate_rps().await?,
average_response_time: self.calculate_avg_response_time().await?,
};
Ok(metrics)
}
fn extract_metric(&self, info: &str, metric: &str) -> u64 {
info.lines()
.find(|line| line.starts_with(metric))
.and_then(|line| line.split(':').nth(1))
.and_then(|value| value.parse::<u64>().ok())
.unwrap_or(0)
}
async fn calculate_rps(&self) -> ChargingResult<f64> {
// This would calculate actual requests per second
// For now, return a placeholder
Ok(100.0)
}
async fn calculate_avg_response_time(&self) -> ChargingResult<f64> {
// This would calculate actual average response time
// For now, return a placeholder
Ok(5.0) // 5ms
}
pub async fn get_error_statistics(&self) -> ChargingResult<ErrorStats> {
let mut conn = self.redis_client.get_async_connection().await
.context("Failed to get Redis connection")?;
let pattern = "error:*".to_string();
let keys: Vec<String> = conn.keys(&pattern).await
.context("Failed to get error keys")?;
let mut total_errors = 0u64;
let mut error_types = std::collections::HashMap::new();
for key in keys {
if let Ok(count) = conn.get::<_, u64>(&key).await {
total_errors += count;
let error_type = key.split(':').nth(1).unwrap_or("unknown");
*error_types.entry(error_type.to_string()).or_insert(0) += count;
}
}
let stats = ErrorStats {
total_errors,
error_types,
last_error: self.get_last_error().await?,
};
Ok(stats)
}
async fn get_last_error(&self) -> ChargingResult<Option<String>> {
let mut conn = self.redis_client.get_async_connection().await
.context("Failed to get Redis connection")?;
let last_error: Option<String> = conn.get("last_error").await.unwrap_or(None);
Ok(last_error)
}
}
#[derive(Debug, Clone)]
pub struct SystemStats {
pub active_sessions: u64,
pub total_accounts: u64,
pub blocked_users: u64,
pub low_balance_alerts: u64,
pub uptime: u64,
}
#[derive(Debug, Clone)]
pub struct HealthStatus {
pub redis_connected: bool,
pub active_sync: bool,
pub last_sync: chrono::DateTime<chrono::Utc>,
pub memory_usage: u64,
}
#[derive(Debug, Clone)]
pub struct PerformanceMetrics {
pub connected_clients: u64,
pub used_memory: u64,
pub total_commands_processed: u64,
pub requests_per_second: f64,
pub average_response_time: f64,
}
#[derive(Debug, Clone)]
pub struct ErrorStats {
pub total_errors: u64,
pub error_types: std::collections::HashMap<String, u64>,
pub last_error: Option<String>,
}
pub mod sync;
pub mod types;
pub mod monitoring;
pub mod operations;
@@ -0,0 +1,4 @@
pub mod sync;
pub mod types;
pub mod monitoring;
pub mod operations;
@@ -0,0 +1,172 @@
use tracing::{info, debug};
use std::time::SystemTime;
use crate::errors::{ChargingError, ChargingResult, ErrorContext};
use super::types::{SystemStats, HealthStatus};
impl super::ChargingEngine {
pub async fn get_system_statistics(&self) -> ChargingResult<SystemStats> {
let mut conn = self.redis_client.get_async_connection().await
.context("Failed to get Redis connection")?;
let active_sessions: u64 = conn.get("stats:active_sessions").await.unwrap_or(0);
let total_accounts: u64 = conn.keys("account:*").await.unwrap_or_default().len() as u64;
let blocked_users: u64 = conn.keys("block:*").await.unwrap_or_default().len() as u64;
let low_balance_alerts: u64 = conn.keys("alert:low_balance:*").await.unwrap_or_default().len() as u64;
let stats = SystemStats {
active_sessions,
total_accounts,
blocked_users,
low_balance_alerts,
uptime: self.get_uptime().await?,
};
Ok(stats)
}
async fn get_uptime(&self) -> ChargingResult<u64> {
// This would track the actual uptime in a real implementation
// For now, return a placeholder
Ok(SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_secs())
}
pub async fn health_check(&self) -> ChargingResult<HealthStatus> {
let mut conn = self.redis_client.get_async_connection().await
.context("Failed to get Redis connection")?;
// Test Redis connection
let _: String = conn.get("health_check").await.unwrap_or_else(|_| "ok".to_string());
let status = HealthStatus {
redis_connected: true,
active_sync: true,
last_sync: chrono::Utc::now(),
memory_usage: self.get_memory_usage().await?,
};
Ok(status)
}
async fn get_memory_usage(&self) -> ChargingResult<u64> {
// This would get actual memory usage in a real implementation
// For now, return a placeholder
Ok(50_000_000) // 50MB placeholder
}
pub async fn get_performance_metrics(&self) -> ChargingResult<PerformanceMetrics> {
let mut conn = self.redis_client.get_async_connection().await
.context("Failed to get Redis connection")?;
// Get Redis info
let info: String = redis::cmd("INFO").query_async(&mut conn).await.unwrap_or_default();
// Parse Redis info for metrics (simplified)
let connected_clients = self.extract_metric(&info, "connected_clients");
let used_memory = self.extract_metric(&info, "used_memory");
let total_commands_processed = self.extract_metric(&info, "total_commands_processed");
let metrics = PerformanceMetrics {
connected_clients,
used_memory,
total_commands_processed,
requests_per_second: self.calculate_rps().await?,
average_response_time: self.calculate_avg_response_time().await?,
};
Ok(metrics)
}
fn extract_metric(&self, info: &str, metric: &str) -> u64 {
info.lines()
.find(|line| line.starts_with(metric))
.and_then(|line| line.split(':').nth(1))
.and_then(|value| value.parse::<u64>().ok())
.unwrap_or(0)
}
async fn calculate_rps(&self) -> ChargingResult<f64> {
// This would calculate actual requests per second
// For now, return a placeholder
Ok(100.0)
}
async fn calculate_avg_response_time(&self) -> ChargingResult<f64> {
// This would calculate actual average response time
// For now, return a placeholder
Ok(5.0) // 5ms
}
pub async fn get_error_statistics(&self) -> ChargingResult<ErrorStats> {
let mut conn = self.redis_client.get_async_connection().await
.context("Failed to get Redis connection")?;
let pattern = "error:*".to_string();
let keys: Vec<String> = conn.keys(&pattern).await
.context("Failed to get error keys")?;
let mut total_errors = 0u64;
let mut error_types = std::collections::HashMap::new();
for key in keys {
if let Ok(count) = conn.get::<_, u64>(&key).await {
total_errors += count;
let error_type = key.split(':').nth(1).unwrap_or("unknown");
*error_types.entry(error_type.to_string()).or_insert(0) += count;
}
}
let stats = ErrorStats {
total_errors,
error_types,
last_error: self.get_last_error().await?,
};
Ok(stats)
}
async fn get_last_error(&self) -> ChargingResult<Option<String>> {
let mut conn = self.redis_client.get_async_connection().await
.context("Failed to get Redis connection")?;
let last_error: Option<String> = conn.get("last_error").await.unwrap_or(None);
Ok(last_error)
}
}
#[derive(Debug, Clone)]
pub struct SystemStats {
pub active_sessions: u64,
pub total_accounts: u64,
pub blocked_users: u64,
pub low_balance_alerts: u64,
pub uptime: u64,
}
#[derive(Debug, Clone)]
pub struct HealthStatus {
pub redis_connected: bool,
pub active_sync: bool,
pub last_sync: chrono::DateTime<chrono::Utc>,
pub memory_usage: u64,
}
#[derive(Debug, Clone)]
pub struct PerformanceMetrics {
pub connected_clients: u64,
pub used_memory: u64,
pub total_commands_processed: u64,
pub requests_per_second: f64,
pub average_response_time: f64,
}
#[derive(Debug, Clone)]
pub struct ErrorStats {
pub total_errors: u64,
pub error_types: std::collections::HashMap<String, u64>,
pub last_error: Option<String>,
}